USE [TryNFeOnline]
GO

ALTER TABLE [dbo].[produtoimposto] ADD 
[idnUtilizarCreditoSNnoICMSnaImportacaoXML] [bit] NULL,
[idnCalcularPartilhaIcmsPorForaAntesDescICMS] [bit] NULL
GO
ALTER TABLE [dbo].[NFseServico] ADD
[idnNaoEnviarPisCofinsNoRPS] [bit] NULL
GO
ALTER TABLE [dbo].[operacao] ADD
[idnNaoEnviarPisCofinsNoRPS] [bit] NULL
GO
ALTER TABLE [dbo].[notafiscal] ADD 
[codPromoGalderma] [varchar] (500) COLLATE Latin1_General_CI_AS NULL
GO
IF EXISTS (SELECT 1 FROM dashboardgrupos WHERE id = 5 and descricao = 'FINANCEIRO')
BEGIN
INSERT [dbo].[Dashboard] ( [descricao], [idDashboardGrupo], [xml]) VALUES ( N'Fluxo de Caixa', 5, N'<Dashboard CurrencyCulture="pt-BR"><Title Text="Dashboard" /><DataSources><SqlDataSource Name="Fonte de dados SQL 1" ComponentName="dashboardSqlDataSource1" DataProcessingMode="Client"><Connection Name="localhost_TryNFeOnline_Connection" ProviderKey="MSSqlServer"><Parameters><Parameter Name="server" Value="localhost\sqlexpress" /><Parameter Name="database" Value="TryNFeOnline" /><Parameter Name="useIntegratedSecurity" Value="True" /><Parameter Name="read only" Value="1" /><Parameter Name="generateConnectionHelper" Value="false" /><Parameter Name="userid" Value="" /><Parameter Name="password" Value="" /></Parameters></Connection><Query Type="CustomSqlQuery" Name="DataInicial"><Sql>SET DATEFIRST 1;

-- Primeiro dia do mês atual
SELECT ''ESTE MÊS'' AS Periodo, DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1) AS DataReferencia, 1 as id
UNION ALL
-- Primeiro dia do mês passado
SELECT ''MÊS PASSADO'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE())), MONTH(DATEADD(MONTH, -1, GETDATE())), 1),  2 as id
UNION ALL
-- Primeiro dia do mês de 2 meses atrás
SELECT ''ÚLTIMOS 2 MESES'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -2, GETDATE())), MONTH(DATEADD(MONTH, -2, GETDATE())), 1),  3 as id
UNION ALL
-- Primeiro dia do mês de 3 meses atrás
SELECT ''ÚLTIMOS 3 MESES'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -3, GETDATE())), MONTH(DATEADD(MONTH, -3, GETDATE())), 1),  4 as id
UNION ALL
-- Primeiro dia do mês de 4 meses atrás
SELECT ''ÚLTIMOS 4 MESES'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -4, GETDATE())), MONTH(DATEADD(MONTH, -4, GETDATE())), 1),  5 as id
UNION ALL
-- Primeiro dia do mês de 5 meses atrás
SELECT ''ÚLTIMOS 5 MESES'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -5, GETDATE())), MONTH(DATEADD(MONTH, -5, GETDATE())), 1),  6 as id
UNION ALL
-- Primeiro dia do mês de 6 meses atrás
SELECT ''ÚLTIMOS 6 MESES'', DATEFROMPARTS(YEAR(DATEADD(MONTH, -6, GETDATE())), MONTH(DATEADD(MONTH, -6, GETDATE())), 1),  7 as id 
UNION ALL
-- Primeiro dia do ano atual
SELECT ''ESTE ANO'', DATEFROMPARTS(YEAR(GETDATE()), 1, 1), 8 as id
UNION ALL
-- Primeiro dia do ano anterior
SELECT ''ANO PASSADO'', DATEFROMPARTS(YEAR(GETDATE()) - 1, 1, 1), 9 as id
UNION ALL
-- Alguma data bem antiga para "todos os registros"
SELECT ''TODOS OS REGISTROS'', (select top 1 data from caixa order by data asc), 10 as id
</Sql></Query><Query Type="CustomSqlQuery" Name="Fluxo"><Parameter Name="dataInicial" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataInicial)</Parameter><Parameter Name="idEmitente" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idEmitente)</Parameter><Parameter Name="idOperadorLogado" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idOperadorLogado)</Parameter><Parameter Name="somenteMeuCaixa" Type="DevExpress.DataAccess.Expression">(System.Boolean)(?somenteMeuCaixa)</Parameter><Sql>---saldo da movimentação até a data inicial
SELECT distinct DATEADD(DAY, -1, @dataInicial) AS dataCaixa, 0 AS valorRecebido, 0 AS valorPago,
    ISNULL(SUM(CASE WHEN f.idnReceitaDespesa = ''+'' THEN fpp.valor ELSE 0 END -
                  CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valor ELSE 0 END), 0) AS saldo--, pc.idPagamento
FROM FaturaParcelaPagamento fpp 
left join CaixaMovimento cm on cm.idFaturaParcelaPagamentoOrigem = fpp.id
left join FaturaParcela fp on fp.id = fpp.idFaturaParcela
left join fatura f on f.id = fp.idFatura
left join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
inner join caixa c on c.id = cm.idCaixa
Where (((f.idnLancamentoCartao = 0) or (f.idnLancamentoCartao is null)) or (f.idnReceitaDespesa = ''-''))
AND CAST(c.data AS DATE) &lt; @dataInicial
and (f.idEmitente = @idEmitente)
and (@somenteMeuCaixa = 0 or c.idOperador = @idOperadorLogado)

UNION ALL

--movimentação diária
SELECT
    resumo.dataCaixa,
    resumo.valorRecebido,
    resumo.valorPago,
    SUM(resumo.valorRecebido - resumo.valorPago)
        OVER (ORDER BY resumo.dataCaixa ROWS UNBOUNDED PRECEDING) +
        ISNULL(saldoAnterior, 0) AS saldo
FROM (
SELECT
    dataCaixa,
    SUM(valorRecebido) AS valorRecebido,
    SUM(valorPago) AS valorPago
FROM (
    SELECT DISTINCT
        CAST(c.data AS DATE) AS dataCaixa,
        CASE WHEN f.idnReceitaDespesa = ''+'' THEN fpp.valor ELSE 0 END AS valorRecebido,
        CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valor ELSE 0 END AS valorPago, fpp.idFaturaParcela
    FROM FaturaParcelaPagamento fpp
    LEFT JOIN CaixaMovimento cm ON cm.idFaturaParcelaPagamentoOrigem = fpp.id
    INNER JOIN caixa c ON c.id = cm.idCaixa
    LEFT JOIN FaturaParcela fp ON fp.id = fpp.idFaturaParcela
    LEFT JOIN fatura f ON f.id = fp.idFatura
    LEFT JOIN ReceitaDespesa rd ON rd.id = f.idReceitaDespesa
    WHERE CAST(c.data AS DATE) &gt;= @dataInicial
    AND ((f.idnLancamentoCartao = 0 OR f.idnLancamentoCartao IS NULL) OR (f.idnReceitaDespesa = ''-''))
	and (f.idEmitente = @idEmitente)
	and (@somenteMeuCaixa = 0 or c.idOperador = @idOperadorLogado)
) AS base
GROUP BY dataCaixa
) AS resumo

CROSS APPLY (
    SELECT distinct SUM(CASE WHEN f.idnReceitaDespesa = ''+'' THEN fpp.valor ELSE 0 END -
                   CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valor ELSE 0 END) AS saldoAnterior--, pc.idPagamento
FROM FaturaParcelaPagamento fpp
left join CaixaMovimento cm on cm.idFaturaParcelaPagamentoOrigem = fpp.id
inner join caixa c on c.id = cm.idCaixa
left join FaturaParcela fp on fp.id = fpp.idFaturaParcela
left join fatura f on f.id = fp.idFatura
left join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
WHERE c.data &lt; @dataInicial
	and (((f.idnLancamentoCartao = 0) or (f.idnLancamentoCartao is null)) or (f.idnReceitaDespesa = ''-''))
	and (f.idEmitente = @idEmitente)
	and (@somenteMeuCaixa = 0 or c.idOperador = @idOperadorLogado)
) AS saldoBase

ORDER BY dataCaixa
</Sql></Query><Query Type="CustomSqlQuery" Name="Vencimentos"><Parameter Name="dataInicial" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataInicial)</Parameter><Parameter Name="idEmitente" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idEmitente)</Parameter><Sql>-- saldo das faturas vencidas (até a data final - 1 dia)
SELECT 
--	''VENCIDOS ATÉ '' + CONVERT(VARCHAR(10), DATEADD(DAY, -1, CAST(GETDATE() AS DATE)), 103) AS dataVencimento,
    DATEADD(DAY, -1, CAST(GETDATE() AS DATE)) AS dataVencimento,
	SUM(CASE WHEN f.idnReceitaDespesa = ''+'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorReceber,
    SUM(CASE WHEN f.idnReceitaDespesa = ''-'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorPagar
FROM FaturaParcela fp
INNER JOIN fatura f ON f.id = fp.idFatura
left join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
WHERE COALESCE(fp.saldo, 0) &gt; 0
  AND CAST(fp.dataVencimento AS DATE) &lt; CAST(GETDATE() AS DATE)
  AND COALESCE(fp.idnBaixado, 0) = 0
  and coalesce(rd.idnIgnorarNosRelatorios,0) = 0
  and (((f.idnLancamentoCartao = 0) or (f.idnLancamentoCartao is null)) or (f.idnReceitaDespesa = ''-''))
  and (f.idEmitente = @idEmitente)

UNION ALL

-- vencimentos do dia (igual à data final)
SELECT 
--    CONVERT(VARCHAR(50), fp.dataVencimento, 103) AS dataVencimento, 
	fp.dataVencimento AS dataVencimento, 
    SUM(CASE WHEN f.idnReceitaDespesa = ''+'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorReceber,
    SUM(CASE WHEN f.idnReceitaDespesa = ''-'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorPagar
FROM FaturaParcela fp
INNER JOIN fatura f ON f.id = fp.idFatura
left join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
WHERE COALESCE(fp.saldo, 0) &gt; 0
  AND CAST(fp.dataVencimento AS DATE) = CAST(GETDATE() AS DATE)
  AND COALESCE(fp.idnBaixado, 0) = 0
  and coalesce(rd.idnIgnorarNosRelatorios,0) = 0
  and (((f.idnLancamentoCartao = 0) or (f.idnLancamentoCartao is null)) or (f.idnReceitaDespesa = ''-''))
  and (f.idEmitente = @idEmitente)
GROUP BY fp.dataVencimento

UNION ALL

-- próximos vencimentos (após a data final)
SELECT 
--    CONVERT(VARCHAR(50), fp.dataVencimento, 103) AS dataVencimento, 
	fp.dataVencimento AS dataVencimento, 
    SUM(CASE WHEN f.idnReceitaDespesa = ''+'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorReceber,
    SUM(CASE WHEN f.idnReceitaDespesa = ''-'' THEN COALESCE(fp.saldo, 0) ELSE 0 END) AS valorPagar
FROM FaturaParcela fp
INNER JOIN fatura f ON f.id = fp.idFatura
left join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
WHERE COALESCE(fp.saldo, 0) &gt; 0
  AND CAST(fp.dataVencimento AS DATE) &gt; CAST(GETDATE() AS DATE)
  AND COALESCE(fp.idnBaixado, 0) = 0
  and coalesce(rd.idnIgnorarNosRelatorios,0) = 0
  and (((f.idnLancamentoCartao = 0) or (f.idnLancamentoCartao is null)) or (f.idnReceitaDespesa = ''-''))
  and (f.idEmitente = @idEmitente)

GROUP BY fp.dataVencimento</Sql></Query><Query Type="CustomSqlQuery" Name="ReceitaDespesa"><Parameter Name="dataInicial" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataInicial)</Parameter><Parameter Name="idEmitente" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idEmitente)</Parameter><Parameter Name="somenteMeuCaixa" Type="DevExpress.DataAccess.Expression">(System.Boolean)(?somenteMeuCaixa)</Parameter><Parameter Name="idOperadorLogado" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idOperadorLogado)</Parameter><Sql>SELECT
    resumo.dataCaixa,
    resumo.valores,
	resumo.receitaDespesa
FROM (
SELECT
    dataCaixa,
    SUM(valores) AS valores,
	descricao as receitaDespesa
FROM (
    SELECT DISTINCT
        CAST(c.data AS DATE) AS dataCaixa,
        CASE WHEN f.idnReceitaDespesa = ''+'' THEN fpp.valor else fpp.valor*-1 END AS valores, 
		fpp.idFaturaParcela, f.idReceitaDespesa, rd.descricao
    FROM FaturaParcelaPagamento fpp
    LEFT JOIN CaixaMovimento cm ON cm.idFaturaParcelaPagamentoOrigem = fpp.id
    INNER JOIN caixa c ON c.id = cm.idCaixa
    LEFT JOIN FaturaParcela fp ON fp.id = fpp.idFaturaParcela
    LEFT JOIN fatura f ON f.id = fp.idFatura
    LEFT JOIN ReceitaDespesa rd ON rd.id = f.idReceitaDespesa
    WHERE CAST(c.data AS DATE) &gt;= @dataInicial
      AND COALESCE(rd.idnIgnorarNosRelatorios, 0) = 0
      AND ((f.idnLancamentoCartao = 0 OR f.idnLancamentoCartao IS NULL) OR (f.idnReceitaDespesa = ''-''))
	and (f.idEmitente = @idEmitente)
	and (@somenteMeuCaixa = 0 or c.idOperador = @idOperadorLogado)
) AS base
GROUP BY dataCaixa, descricao
) AS resumo

ORDER BY dataCaixa</Sql></Query><Query Type="CustomSqlQuery" Name="Detalhado"><Parameter Name="idEmitente" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idEmitente)</Parameter><Parameter Name="idOperadorLogado" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idOperadorLogado)</Parameter><Parameter Name="somenteMeuCaixa" Type="DevExpress.DataAccess.Expression">(System.Boolean)(?somenteMeuCaixa)</Parameter><Sql>DECLARE @ehAdmin BIT = (SELECT ISNULL(idnAdministrador, 0) FROM operador WHERE operador.id = @idOperadorLogado);

WITH Movimentacoes AS (
    SELECT 
        (CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valor * -1 ELSE fpp.valor END) AS valor,
        (CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valorJuro * -1 ELSE fpp.valorJuro END) AS valorJuro,
        (CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valorMulta * -1 ELSE fpp.valorMulta END) AS valorMulta,
        (CASE WHEN f.idnReceitaDespesa = ''-'' THEN fpp.valorDesconto * -1 ELSE fpp.valorDesconto END) AS valorDesconto,
        CASE 
            WHEN pa.razaosocial IS NOT NULL THEN pa.razaosocial 
            ELSE f.historico 
        END AS razaoSocialParceiro,
        CAST(cm.dataHora AS DATE) AS dataCaixa,
        f.numeroDocumento,
        recDes.descricao AS dscReceitaDespesa,
        (SELECT * FROM NumerariosPagamentoDescricao(fpp.idPagamento)) AS numerario,
        recDes.idnApenasAdministradoresTemAcesso
    FROM FaturaParcelaPagamento fpp
    INNER JOIN FaturaParcela fp ON fp.id = fpp.idFaturaParcela
    INNER JOIN Fatura f ON f.id = fp.idFatura
    LEFT JOIN parceiro pa ON pa.id = f.idParceiro
    INNER JOIN CaixaMovimento cm ON cm.idFaturaParcelaPagamentoOrigem = fpp.id
    INNER JOIN Caixa ca ON ca.id = cm.idCaixa
    INNER JOIN ReceitaDespesa recDes ON recDes.id = f.idReceitaDespesa
    WHERE (((f.idnLancamentoCartao = 0) OR (f.idnLancamentoCartao IS NULL)) OR (f.idnReceitaDespesa = ''-''))
        AND (f.idEmitente = @idEmitente)
	and (@somenteMeuCaixa = 0 or ca.idOperador = @idOperadorLogado)
)

-- Resultado final
SELECT 
    valor,
    valorJuro,
    valorMulta,
    valorDesconto,
    razaoSocialParceiro,
    dataCaixa,
    numeroDocumento,
    dscReceitaDespesa,
    numerario,
    idnApenasAdministradoresTemAcesso

FROM Movimentacoes
WHERE @ehAdmin = 1 OR ISNULL(idnApenasAdministradoresTemAcesso, 0) = 0

UNION ALL

-- Se não for admin, soma os ocultos e mostra como "OUTROS"
SELECT 
    SUM(valor) as valor, 
    SUM(valorJuro) as valorJuros, 
    SUM(valorMulta) as valorMulta, 
    SUM(valorDesconto) as valorDesconto, 
    NULL as razaoSocialParceiro, 
	dataCaixa as dataCaixa, 
	NULL as numeroDocumento, 
    ''OUTROS VALORES'' as dscReceitaDespesa, 
    NULL as numerario, 
	NULL as idnApenasAdministradoresTemAcesso

FROM Movimentacoes
WHERE ISNULL(idnApenasAdministradoresTemAcesso, 0) = 1
AND @ehAdmin = 0
GROUP BY dataCaixa 
HAVING COUNT(*) &gt; 0</Sql></Query><Query Type="CustomSqlQuery" Name="Emitente"><Sql>select id, concat(id, '' - '', razaosocial) as emitente from emitente where isnull(idnBaixa, 0) = 0</Sql></Query><Query Type="CustomSqlQuery" Name="VencimentosDetalhados"><Parameter Name="idEmitente" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idEmitente)</Parameter><Sql>select (case when fp.dataVencimento &lt; CAST(DATEADD(day, -1, GETDATE()) AS DATE) then CAST(DATEADD(day, -1, GETDATE()) AS DATE) else fp.dataVencimento end) as dataVencimento, --este é o filtro, ideal seria passar data de ontem para todas que vencem até ontem
fp.dataVencimento as dataVencimentoOriginal,
fp.parcela, fp.idFatura, (case when f.idnReceitaDespesa = ''-'' then fp.valor*-1 else fp.valor end) as valor, fp.observacao, p.razaosocial as parceiro,
rd.descricao as receitaDespesa

from FaturaParcela fp
inner join fatura f on f.id = fp.idFatura
left join parceiro p on p.id = f.idParceiro
inner join ReceitaDespesa rd on rd.id = f.idReceitaDespesa
where isnull(fp.idnBaixado, 0) = 0
and (fp.saldo &gt; 0)
and (f.idEmitente = @idEmitente)</Sql></Query><ResultSchema><DataSet Name="Fonte de dados SQL 1"><View Name="DataInicial"><Field Name="Periodo" Type="String" /><Field Name="DataReferencia" Type="DateTime" /><Field Name="id" Type="Int32" /></View><View Name="Fluxo"><Field Name="dataCaixa" Type="DateTime" /><Field Name="valorRecebido" Type="Decimal" /><Field Name="valorPago" Type="Decimal" /><Field Name="saldo" Type="Decimal" /></View><View Name="Vencimentos"><Field Name="dataVencimento" Type="DateTime" /><Field Name="valorReceber" Type="Decimal" /><Field Name="valorPagar" Type="Decimal" /></View><View Name="ReceitaDespesa"><Field Name="dataCaixa" Type="DateTime" /><Field Name="valores" Type="Decimal" /><Field Name="receitaDespesa" Type="String" /></View><View Name="Detalhado"><Field Name="valor" Type="Decimal" /><Field Name="valorJuro" Type="Decimal" /><Field Name="valorMulta" Type="Decimal" /><Field Name="valorDesconto" Type="Decimal" /><Field Name="razaoSocialParceiro" Type="String" /><Field Name="dataCaixa" Type="DateTime" /><Field Name="numeroDocumento" Type="Int32" /><Field Name="dscReceitaDespesa" Type="String" /><Field Name="numerario" Type="String" /><Field Name="idnApenasAdministradoresTemAcesso" Type="Boolean" /></View><View Name="Emitente"><Field Name="id" Type="Int32" /><Field Name="emitente" Type="String" /></View><View Name="VencimentosDetalhados"><Field Name="dataVencimento" Type="DateTime" /><Field Name="dataVencimentoOriginal" Type="DateTime" /><Field Name="parcela" Type="Int32" /><Field Name="idFatura" Type="Int32" /><Field Name="valor" Type="Decimal" /><Field Name="observacao" Type="String" /><Field Name="parceiro" Type="String" /><Field Name="receitaDespesa" Type="String" /></View></DataSet></ResultSchema><ConnectionOptions CloseConnection="true" DbCommandTimeout="2500" /></SqlDataSource></DataSources><Parameters><Parameter Name="dataInicial" Type="System.DateTime" Value="2025-01-01T00:00:00" Description="Data Inicial (Períodos Anteriores)"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="DataInicial" ValueMember="DataReferencia" DisplayMember="Periodo" SortByMember="id" /></Parameter><Parameter Name="idEmitente" Type="System.Int32" Value="1" Description="Emitente"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Emitente" ValueMember="id" DisplayMember="emitente" /></Parameter><Parameter Name="idOperadorLogado" Type="System.Int32" Value="0" Description="idOperadorLogado" Visible="false" /><Parameter Name="somenteMeuCaixa" Type="System.Boolean" Value="false" Description="Mostrar Somente Movimentações do Operador Logado" /></Parameters><Items><Chart ComponentName="chartDashboardItem1" Name="Fluxo de Caixa" ShowCaption="false" ParentContainer="dashboardTabPage1" DataSource="dashboardSqlDataSource1" DataMember="Fluxo"><InteractivityOptions IgnoreMasterFilters="true" /><DataItems><Dimension DataMember="dataCaixa" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Measure DataMember="valorPago" DefaultId="DataItem3"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Measure><Measure DataMember="valorRecebido" DefaultId="DataItem2"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Measure><Measure DataMember="saldo" DefaultId="DataItem1"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Measure></DataItems><Arguments><Argument DefaultId="DataItem0" /></Arguments><Panes><Pane Name="Painel 1"><Series><Simple Name="Valores Pagos"><Value DefaultId="DataItem3" /></Simple><Simple Name="Valores Recebidos"><Value DefaultId="DataItem2" /></Simple><Simple Name="Saldo" SeriesType="Line"><Value DefaultId="DataItem1" /></Simple></Series></Pane></Panes><ChartLegend OutsidePosition="TopCenterHorizontal" /></Chart><Grid ComponentName="gridDashboardItem1" Name="Saldo da Movimentação até a Data Inicial e Movimentação até a Data de Hoje" ParentContainer="dashboardTabPage1" DataSource="dashboardSqlDataSource1" DataMember="Fluxo" IsMasterFilterCrossDataSource="true"><InteractivityOptions MasterFilterMode="Single" /><DataItems><Dimension DataMember="dataCaixa" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Dimension DataMember="valorRecebido" DefaultId="DataItem1"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="valorPago" DefaultId="DataItem2"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="saldo" DefaultId="DataItem3"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 1" DataItem="DataItem3" DataItemApplyTo="DataItem3"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="FontRed" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Data Base e Data dos Caixas" Weight="53.988868274582558"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Valores Recebidos" Weight="85.99257884972171"><Dimension DefaultId="DataItem1" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Valores Pagos" Weight="90.723562152133582"><Dimension DefaultId="DataItem2" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Saldo" Weight="69.294990723562151"><Dimension DefaultId="DataItem3" /></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid><Grid ComponentName="gridDashboardItem2" Name="Saldo Total dos Valores Vencidos até Ontem, Total dos Vencimentos de Hoje e Próximos Vencimentos" ParentContainer="dashboardTabPage1" DataSource="dashboardSqlDataSource1" DataMember="Vencimentos" IsMasterFilterCrossDataSource="true"><InteractivityOptions MasterFilterMode="Single" /><DataItems><Dimension DataMember="dataVencimento" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Dimension DataMember="valorPagar" DefaultId="DataItem1"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="valorReceber" DefaultId="DataItem2"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 1"><FormatConditionExpression Expression="Iif([DataItem0] = AddDays(Today(), -1), ''Vencidos até o dia '' + [DataItem0], [DataItem0])"><AppearanceSettings AppearanceType="PaleRed" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 2"><FormatConditionExpression Expression="[DataItem0] = LocalDateTimeYesterday()"><AppearanceSettings AppearanceType="Custom" BackColor="-374457" /></FormatConditionExpression></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Data Vencimento" Weight="83.487940630797766"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Valores à Pagar" Weight="89.55644732863108"><Dimension DefaultId="DataItem1" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Valores à Receber" Weight="77.419433932964452"><Dimension DefaultId="DataItem2" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid><TabContainer ComponentName="tabContainerDashboardItem1" Name="Tab Container 1"><Pages><Page ComponentName="dashboardTabPage1" Name="Fluxo" /><Page ComponentName="dashboardTabPage2" Name="Movimentação" /></Pages></TabContainer><Grid ComponentName="gridDashboardItem3" Name="Totalizadores das Receitas e Despesas" ParentContainer="dashboardTabPage2" DataSource="dashboardSqlDataSource1" DataMember="ReceitaDespesa"><DataItems><Dimension DataMember="dataCaixa" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Dimension DataMember="valores" DefaultId="DataItem2"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="receitaDespesa" DefaultId="DataItem1" /></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 1" Enabled="false"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" BackColor="-16724386" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 2" Enabled="false"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="Custom" BackColor="-374457" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 3" ApplyToRow="true" DataItem="DataItem2" DataItemApplyTo="DataItem2"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" ForeColor="-16741313" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 4" ApplyToRow="true" DataItem="DataItem2" DataItemApplyTo="DataItem2"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="FontRed" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Data Caixa" Weight="21.614339268978444"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Receita / Despesa" Weight="156.7830365510778"><Dimension DefaultId="DataItem1" /></GridDimensionColumn><GridDimensionColumn Name="Valor" Weight="46.602624179943767"><Dimension DefaultId="DataItem2" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid><Pie ComponentName="pieDashboardItem2" Name="Totais dos Recebimentos e Pagamentos" ParentContainer="dashboardTabPage1" DataSource="dashboardSqlDataSource1" DataMember="ReceitaDespesa" PieType="Donut" LabelContentType="ArgumentAndValue"><DataItems><Dimension DataMember="receitaDespesa" DefaultId="DataItem0" /><Measure DataMember="valores" DefaultId="DataItem1"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Measure><Dimension DataMember="dataCaixa" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem3" /></DataItems><SeriesDimensions><SeriesDimension DefaultId="DataItem3" /></SeriesDimensions><Arguments><Argument DefaultId="DataItem0" /></Arguments><Values><Value DefaultId="DataItem1" /></Values></Pie><Grid ComponentName="gridDashboardItem4" Name="Movimentação Detalhada" ParentContainer="dashboardTabPage2" DataSource="dashboardSqlDataSource1" DataMember="Detalhado"><DataItems><Dimension DataMember="dataCaixa" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Dimension DataMember="razaoSocialParceiro" DefaultId="DataItem1" /><Dimension DataMember="dscReceitaDespesa" DefaultId="DataItem2" /><Dimension DataMember="valor" DefaultId="DataItem3"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="valorDesconto" DefaultId="DataItem4"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="valorJuro" DefaultId="DataItem5"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="numerario" DefaultId="DataItem7" /><Dimension DataMember="numeroDocumento" DefaultId="DataItem6"><NumericFormat FormatType="Number" Precision="0" Unit="Ones" IncludeGroupSeparator="true" CustomFormatString="" /></Dimension><Dimension DataMember="valorMulta" DefaultId="DataItem8" /></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 1" ApplyToRow="true" DataItem="DataItem3" DataItemApplyTo="DataItem3"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" ForeColor="-16741313" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 2" ApplyToRow="true" DataItem="DataItem3" DataItemApplyTo="DataItem3"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="FontRed" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Data Caixa" Weight="49.204879700826496"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Parceiro" Weight="144.44013073468423"><Dimension DefaultId="DataItem1" /></GridDimensionColumn><GridDimensionColumn Name="Receita / Despesa" Weight="126.34543303825126"><Dimension DefaultId="DataItem2" /></GridDimensionColumn><GridDimensionColumn Name="Número Documento" Weight="78.410356684542876"><Dimension DefaultId="DataItem6" /></GridDimensionColumn><GridDimensionColumn Name="Valor Desconto" Weight="66.347224886920884"><Dimension DefaultId="DataItem4" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Valor Juros" Weight="61.268011498448473"><Dimension DefaultId="DataItem5" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Valor Multa" Weight="57.7760522938737"><Dimension DefaultId="DataItem8" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Valor" Weight="53.649191415739857"><Dimension DefaultId="DataItem3" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn><GridDimensionColumn Name="Numérario" Weight="39.998805434220252"><Dimension DefaultId="DataItem7" /></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid><Grid ComponentName="gridDashboardItem5" Name="Vencimentos Detalhados" ParentContainer="dashboardTabPage2" DataSource="dashboardSqlDataSource1" DataMember="VencimentosDetalhados"><DataItems><Dimension DataMember="dataVencimento" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem0" /><Dimension DataMember="valor" DefaultId="DataItem1"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="parceiro" DefaultId="DataItem2" /><Dimension DataMember="parcela" DefaultId="DataItem3" /><Dimension DataMember="idFatura" DefaultId="DataItem4"><NumericFormat FormatType="Number" Precision="0" Unit="Ones" IncludeGroupSeparator="true" CustomFormatString="" /></Dimension><Dimension DataMember="observacao" DefaultId="DataItem5" /><Dimension DataMember="dataVencimentoOriginal" DateTimeGroupInterval="DayMonthYear" DefaultId="DataItem6" /><Dimension DataMember="receitaDespesa" DefaultId="DataItem7" /></DataItems><HiddenDimensions><Dimension DefaultId="DataItem0" /></HiddenDimensions><FormatRules><GridItemFormatRule Name="FormatRule 1" ApplyToRow="true" DataItem="DataItem1" DataItemApplyTo="DataItem1"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" ForeColor="-16741313" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 2" ApplyToRow="true" DataItem="DataItem1" DataItemApplyTo="DataItem1"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="FontRed" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Data Vencimento" Weight="45.0210871602624"><Dimension DefaultId="DataItem6" /></GridDimensionColumn><GridDimensionColumn Name="Código Fatura" Weight="27.799906279287708"><Dimension DefaultId="DataItem4" /></GridDimensionColumn><GridDimensionColumn Name="Parceiro" Weight="123.00843486410491"><Dimension DefaultId="DataItem2" /></GridDimensionColumn><GridDimensionColumn Name="Receita / Despesa" Weight="121.77835051546386"><Dimension DefaultId="DataItem7" /></GridDimensionColumn><GridDimensionColumn Name="Parcela" Weight="24.601686972820982"><Dimension DefaultId="DataItem3" /></GridDimensionColumn><GridDimensionColumn Name="Observações" Weight="136.04732895970005"><Dimension DefaultId="DataItem5" /></GridDimensionColumn><GridDimensionColumn Name="Valor" Weight="46.743205248359864"><Dimension DefaultId="DataItem1" /><Totals><Total Type="Sum" /></Totals></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid></Items><ColorScheme><Entry DataSource="dashboardSqlDataSource1" DataMember="Fluxo" Color="-14513441"><MeasureKey><Definition DataMember="saldo" /></MeasureKey></Entry><Entry DataSource="dashboardSqlDataSource1" DataMember="Fluxo" Color="-1495286"><MeasureKey><Definition DataMember="valorPago" /></MeasureKey></Entry><Entry DataSource="dashboardSqlDataSource1" DataMember="Fluxo" Color="-14359995"><MeasureKey><Definition DataMember="valorRecebido" /></MeasureKey></Entry></ColorScheme><LayoutTree><LayoutGroup Orientation="Vertical" Weight="100"><LayoutTabContainer DashboardItem="tabContainerDashboardItem1" Weight="100"><LayoutTabPage Orientation="Vertical" DashboardItem="dashboardTabPage1" Weight="100"><LayoutItem DashboardItem="chartDashboardItem1" Weight="36.883116883116884" /><LayoutGroup Weight="63.116883116883116"><LayoutGroup Orientation="Vertical" Weight="64.818266542404473"><LayoutItem DashboardItem="gridDashboardItem1" Weight="50.617283950617285" /><LayoutItem DashboardItem="gridDashboardItem2" Weight="49.382716049382715" /></LayoutGroup><LayoutItem DashboardItem="pieDashboardItem2" Weight="35.181733457595527" /></LayoutGroup></LayoutTabPage><LayoutTabPage Orientation="Vertical" DashboardItem="dashboardTabPage2" Weight="100"><LayoutItem DashboardItem="gridDashboardItem4" Weight="34.675324675324674" /><LayoutItem DashboardItem="gridDashboardItem3" Weight="33.766233766233768" /><LayoutItem DashboardItem="gridDashboardItem5" Weight="31.558441558441558" /></LayoutTabPage></LayoutTabContainer></LayoutGroup></LayoutTree></Dashboard>')
END
GO

CREATE FUNCTION [dbo].[EstoqueMovimentoComSaldo]
(
	@dataInf Date = null,
	@idEmitenteInf int,
	@idProdutoInf int = 0,
	@idProdutoClassificacaoInf int = 0,
	@idContaInf int = 0,
	@dataInicial Date
)
RETURNS 
@Resultado TABLE 
(	
		idProduto int,
		idProdutoClassificacao int,
		dscProduto varchar(240),
		codigoProdutoClasse varchar(50),
		preco decimal(18,4),
		precoCadastro decimal(18,4),
		unidadeMedida varchar(30),
		unidadeMedidaConvertida varchar(30),
		fatorConversao decimal(18,4),
		qtd decimal(18,4),
		idOperacao int,
		idnOperacao varchar(5),
		idConta int,
		dscConta varchar(200),		
		numeroDocumento varchar(50) null,
		dscOperacao varchar(100),
		data datetime,
		idGrupo int,
		dscGrupo varchar(100),
		idNF int,
		saldoEstoqueInicial decimal(18,4)
)
AS
BEGIN

	declare @data datetime = @dataInf;
	declare @idEmitente int = @idEmitenteInf;
	declare @idProduto int = 0;
	declare @idProdutoClassificacao int = 0;
	declare @idConta int = 0;

	--declare @idnConsiderarPedidosFaturadosNoEstoque bit = 0;

	--SET @idnConsiderarPedidosFaturadosNoEstoque = (select coalesce(idnConsiderarPedidosFaturadosNoEstoque, 0) from configuracoes)
	
declare @ResultadoTemp TABLE 
(	
		idProduto int,
		idProdutoClassificacao int,
		dscProduto varchar(240),
		codigoProdutoClasse varchar(50),
		preco decimal(18,4),
		precoCadastro decimal(18,4),
		unidadeMedida varchar(30),
		unidadeMedidaConvertida varchar(30),
		fatorConversao decimal(18,4),
		qtd decimal(18,4),
		idOperacao int,
		idnOperacao varchar(5),
		idConta int,
		dscConta varchar(200),		
		numeroDocumento varchar(50) null,
		dscOperacao varchar(100),
		data datetime,
		idGrupo int,
		dscGrupo varchar(100),
		idNF int,
		saldoEstoqueInicial decimal(18,4)
)

	declare @idnConsiderarPedidosFaturadosNoEstoque bit = 0;
	
	SET @idnConsiderarPedidosFaturadosNoEstoque = (select coalesce(valor, 'false') from ConfiguracoesValorParametro('idnConsiderarPedidosFaturadosNoEstoque'))
	declare @dataInicialEstoque date = dateadd(DD,-1,@dataInicial);
	
	if (@idContaInf > 0)
		SET @idConta = @idContaInf;
	
	if (@idProdutoClassificacaoInf > 0)
		SET @idProdutoClassificacao = @idProdutoClassificacaoInf;
	
	if (@idProdutoInf > 0)
		SET @idProduto = @idProdutoInf;
	
	if (@data is null)
		SET @data = (SELECT GETDATE());
			
	declare @ProdutosLista as ListaProdutos

	declare @ProdutoEstoque TABLE
	(
		idProduto int,
		idProdutoClassificacao int,
		custoCalculado decimal(18,4),
		precoCalculado decimal(18,4),
		precoMinimo decimal(18,4),
		qtd	decimal(18,4)
	)
	
	INSERT into @ResultadoTemp
	select idproduto, idProdutoClassificacao, dscproduto, codigoProdutoClasse, preco, precoCadastro, unidadeMedida, unidadeMedidaConvertida, fatorConversao, qtd, idoperacao, idnoperacao, idconta,
	dscconta, numeroDocumento, dscoperacao, data, idGrupo, dscGrupo, idNF,0
	from EstoqueMovimento(@dataInf,@idEmitente,@idProduto,@idProdutoClassificacao,@idConta,@dataInicial)

	INSERT into @ProdutosLista
	select distinct r.idproduto, r.idprodutoclassificacao from @ResultadoTemp r

	INSERT into @ProdutoEstoque
	select idProduto, idProdutoClassificacao, custoCalculado, precoCalculado, precoMinimo, qtd from EstoqueProdutos2(@dataInicialEstoque,@idEmitente,0,0,@idConta,0,1,1,@ProdutosLista, 1, 1)

	INSERT into @Resultado
	select rt.idproduto, rt.idProdutoClassificacao, rt.dscproduto, rt.codigoProdutoClasse, rt.preco, rt.precoCadastro, rt.unidadeMedida, rt.unidadeMedidaConvertida, rt.fatorConversao, rt.qtd, rt.idoperacao, rt.idnoperacao, rt.idconta,
	rt.dscconta, rt.numeroDocumento, rt.dscoperacao, rt.data, rt.idGrupo, rt.dscGrupo, rt.idNF, pe.qtd
	from @ResultadoTemp rt
	left join @ProdutoEstoque pe on pe.idProduto = rt.idProduto

	RETURN 
END
GO

IF EXISTS (SELECT 1 FROM ReportsGrupos WHERE id = 9 and descricao = 'ESTOQUE')
BEGIN
INSERT [dbo].[Reports] ([descricao], [idReportsGrupo], [xml]) VALUES (N'Consulta Movimentação de Estoque', 9, N'<XtraReportsLayoutSerializer SerializerVersion="22.2.6.0" Ref="1" ControlType="DevExpress.XtraReports.UI.XtraReport, DevExpress.XtraReports.v22.2, Version=22.2.6.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a" Name="XtraReport" Margins="50, 49, 46.875, 51.5095863" PageWidth="850" PageHeight="1100" Version="22.2" DataMember="Movimentos" DataSource="#Ref-0" Font="Arial, 9.75pt"><Parameters><Item1 Ref="4" Description="Código Filial" ValueSourceSettings="#Ref-2" ValueInfo="1" Name="idFilial" Type="#Ref-3" /><Item2 Ref="6" Description="Código da Conta de Estoque" ValueSourceSettings="#Ref-5" ValueInfo="1" Name="idConta" Type="#Ref-3" /><Item3 Ref="9" Description="Agrupamento" ValueSourceSettings="#Ref-7" ValueInfo="mensal" Name="modoAgrupamento" /><Item4 Ref="11" Description="Código Produto" ValueSourceSettings="#Ref-10" ValueInfo="0" Name="idProduto" Type="#Ref-3" /><Item5 Ref="13" Description="Data Inicial" ValueInfo="2025-06-01" Name="dataInicial" Type="#Ref-12"><ExpressionBindings><Item1 Ref="14" PropertyName="Value" Expression="AddMonths(AddDays(Today(), 1-GetDay(Today())), -1)" /></ExpressionBindings></Item5><Item6 Ref="15" Description="Data Final" ValueInfo="2025-08-12" Name="dataCompetencia" Type="#Ref-12"><ExpressionBindings><Item1 Ref="16" PropertyName="Value" Expression="Today()" /></ExpressionBindings></Item6></Parameters><Bands><Item1 Ref="17" ControlType="TopMarginBand" Name="TopMargin" HeightF="46.875" /><Item2 Ref="18" ControlType="BottomMarginBand" Name="BottomMargin" HeightF="51.5095863" /><Item3 Ref="19" ControlType="DetailBand" Name="Detail" KeepTogetherWithDetailReports="true" HeightF="23.5000019" KeepTogether="true"><Controls><Item1 Ref="20" ControlType="XRLine" Name="line1" LineStyle="Dash" SizeF="751,2.333334" LocationFloat="1.40666962E-05,21.1666679" /><Item2 Ref="21" ControlType="XRLabel" Name="label2" Multiline="true" Text="label2" SizeF="168.655319,21.1666679" LocationFloat="0,0" Font="Arial, 9.75pt, style=Bold" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="22" EventName="BeforePrint" PropertyName="Text" Expression="[periodo]" /></ExpressionBindings><StylePriority Ref="23" UseFont="false" /></Item2><Item3 Ref="24" ControlType="XRLabel" Name="label6" TextFormatString="{0:N2}" Multiline="true" Text="label6" TextAlignment="TopRight" SizeF="134.583252,21.1666679" LocationFloat="616.416748,0" Font="Arial, 9.75pt, style=Bold" BackColor="Transparent" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="25" EventName="BeforePrint" PropertyName="Text" Expression="[saldoFinal]" /></ExpressionBindings><StylePriority Ref="26" UseFont="false" UseBackColor="false" UseTextAlignment="false" /></Item3><Item4 Ref="27" ControlType="XRLabel" Name="label5" TextFormatString="{0:N2}" Multiline="true" Text="label5" TextAlignment="TopRight" SizeF="134.583252,21.1666679" LocationFloat="197.666977,0" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="28" EventName="BeforePrint" PropertyName="Text" Expression="[saldoInicial]" /></ExpressionBindings><StylePriority Ref="29" UseTextAlignment="false" /></Item4><Item5 Ref="30" ControlType="XRLabel" Name="label4" TextFormatString="{0:N2}" Multiline="true" Text="label4" TextAlignment="TopRight" SizeF="134.583252,21.1666679" LocationFloat="476.8335,0" ForeColor="255,240,0,0" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="31" EventName="BeforePrint" PropertyName="Text" Expression="[qtdSaida]" /></ExpressionBindings><StylePriority Ref="32" UseForeColor="false" UseTextAlignment="false" /></Item5><Item6 Ref="33" ControlType="XRLabel" Name="label3" TextFormatString="{0:N2}" Multiline="true" Text="label3" TextAlignment="TopRight" SizeF="134.583252,21.1666679" LocationFloat="337.250244,0" ForeColor="255,0,176,80" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="34" EventName="BeforePrint" PropertyName="Text" Expression="[qtdEntrada]" /></ExpressionBindings><StylePriority Ref="35" UseForeColor="false" UseTextAlignment="false" /></Item6></Controls></Item3><Item4 Ref="36" ControlType="GroupHeaderBand" Name="GroupHeader1" HeightF="24.4230518" KeepTogether="true" BackColor="Gainsboro"><GroupFields><Item1 Ref="37" FieldName="codigoProdutoClasse" /></GroupFields><Controls><Item1 Ref="38" ControlType="XRLabel" Name="label1" Multiline="true" TextTrimming="None" Text="label1" TextAlignment="TopLeft" SizeF="749.999939,16.4230518" LocationFloat="1.00001311,4" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="39" EventName="BeforePrint" PropertyName="Text" Expression="[codigoProdutoClasse] + '' - '' + [dscProduto]" /></ExpressionBindings><StylePriority Ref="40" UseTextAlignment="false" /></Item1><Item2 Ref="41" ControlType="XRLabel" Name="label13" Multiline="true" TextTrimming="None" Text="&#x9;" TextAlignment="TopLeft" SizeF="750.999939,24.4230518" LocationFloat="0,0" Padding="2,2,0,0,100"><StylePriority Ref="42" UseTextAlignment="false" /></Item2></Controls><StylePriority Ref="43" UseBackColor="false" /></Item4><Item5 Ref="44" ControlType="ReportHeaderBand" Name="ReportHeader" HeightF="113.710228" Font="Arial, 9.75pt, style=Bold"><Controls><Item1 Ref="45" ControlType="XRLabel" Name="label23" Multiline="true" Text="label23" SizeF="361.338776,18.1666718" LocationFloat="134.583252,67.45831" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="46" EventName="BeforePrint" PropertyName="Text" Expression="[modoAgrupamento]" /></ExpressionBindings><StylePriority Ref="47" UseFont="false" /></Item1><Item2 Ref="48" ControlType="XRLabel" Name="label22" Multiline="true" Text="Agrupamento:" SizeF="107.575775,18.1666718" LocationFloat="0,67.45831" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><StylePriority Ref="49" UseFont="false" /></Item2><Item3 Ref="50" ControlType="XRLabel" Name="label21" Multiline="true" Text="Data Final:" SizeF="100,18.1666718" LocationFloat="550.3544,18.2083435" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><StylePriority Ref="51" UseFont="false" /></Item3><Item4 Ref="52" ControlType="XRLabel" Name="label20" Multiline="true" Text="Data Inicial:" SizeF="100,18.1666718" LocationFloat="550.3544,0" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><StylePriority Ref="53" UseFont="false" /></Item4><Item5 Ref="54" ControlType="XRLabel" Name="label19" TextFormatString="{0:d}" Multiline="true" Text="label19" SizeF="100,18.1666718" LocationFloat="650.999939,0.0416641235" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="55" EventName="BeforePrint" PropertyName="Text" Expression="?dataInicial" /></ExpressionBindings><StylePriority Ref="56" UseFont="false" /></Item5><Item6 Ref="57" ControlType="XRLabel" Name="label18" TextFormatString="{0:d}" Multiline="true" Text="label18" SizeF="100,18.1666718" LocationFloat="650.999939,18.2083435" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="58" EventName="BeforePrint" PropertyName="Text" Expression="Iif(?dataCompetencia == null, GetDate(Today()), ?dataCompetencia) " /></ExpressionBindings><StylePriority Ref="59" UseFont="false" /></Item6><Item7 Ref="60" ControlType="XRLabel" Name="label17" Multiline="true" Text="Filial:" SizeF="110.494705,18.1666679" LocationFloat="0,49.29165" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><StylePriority Ref="61" UseFont="false" /></Item7><Item8 Ref="62" ControlType="XRLabel" Name="label16" Multiline="true" Text="label16" SizeF="616.4166,18.1666679" LocationFloat="134.583252,49.2916679" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="63" EventName="BeforePrint" PropertyName="Text" Expression="[emitente]" /></ExpressionBindings><StylePriority Ref="64" UseFont="false" /></Item8><Item9 Ref="65" ControlType="XRLabel" Name="label15" Multiline="true" Text="label15" SizeF="361.338776,18.1666718" LocationFloat="134.583252,31.1249886" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><ExpressionBindings><Item1 Ref="66" EventName="BeforePrint" PropertyName="Text" Expression="[contaEstoque]" /></ExpressionBindings><StylePriority Ref="67" UseFont="false" /></Item9><Item10 Ref="68" ControlType="XRLabel" Name="label14" Multiline="true" Text="Conta de Estoque:" SizeF="134.583252,18.1666718" LocationFloat="0,31.1249886" Font="Arial, 9.75pt" Padding="2,2,0,0,100"><StylePriority Ref="69" UseFont="false" /></Item10><Item11 Ref="70" ControlType="XRLine" Name="line2" SizeF="750,2" LocationFloat="1.00003672,111.710228" /><Item12 Ref="71" ControlType="XRLabel" Name="label12" Multiline="true" Text="Período" SizeF="134.583252,18.1666718" LocationFloat="0,93.54357" Padding="2,2,0,0,100" /><Item13 Ref="72" ControlType="XRLabel" Name="label11" Multiline="true" Text="Saldo Final" TextAlignment="TopRight" SizeF="134.583252,18.1666718" LocationFloat="616.4168,93.54357" Padding="2,2,0,0,100"><StylePriority Ref="73" UseTextAlignment="false" /></Item13><Item14 Ref="74" ControlType="XRLabel" Name="label10" Multiline="true" Text="Saídas" TextAlignment="TopRight" SizeF="134.583252,18.1666718" LocationFloat="476.833527,93.54357" Padding="2,2,0,0,100"><StylePriority Ref="75" UseTextAlignment="false" /></Item14><Item15 Ref="76" ControlType="XRLabel" Name="label9" Multiline="true" Text="Entradas" TextAlignment="TopRight" SizeF="134.583252,18.1666718" LocationFloat="337.250244,93.54357" Padding="2,2,0,0,100"><StylePriority Ref="77" UseTextAlignment="false" /></Item15><Item16 Ref="78" ControlType="XRLabel" Name="label8" Multiline="true" Text="Saldo Inicial" TextAlignment="TopRight" SizeF="134.583252,18.1666718" LocationFloat="197.666992,93.54357" Padding="2,2,0,0,100"><StylePriority Ref="79" UseTextAlignment="false" /></Item16><Item17 Ref="80" ControlType="XRLabel" Name="label7" Multiline="true" Text="Relatório de Movimentação e Saldos de Estoque" SizeF="402.041626,28.125" LocationFloat="0,0" Font="Arial, 12pt, style=Bold" Padding="2,2,0,0,100"><StylePriority Ref="81" UseFont="false" /></Item17></Controls><StylePriority Ref="82" UseFont="false" /></Item5></Bands><ParameterPanelLayoutItems><Item1 Ref="83" LayoutItemType="Parameter" Parameter="#Ref-4" /><Item2 Ref="84" LayoutItemType="Parameter" Parameter="#Ref-6" /><Item3 Ref="85" LayoutItemType="Parameter" Parameter="#Ref-9" /><Item4 Ref="86" LayoutItemType="Parameter" Parameter="#Ref-11" /><Item5 Ref="87" LayoutItemType="Parameter" Parameter="#Ref-13" /><Item6 Ref="88" LayoutItemType="Parameter" Parameter="#Ref-15" /></ParameterPanelLayoutItems><ComponentStorage><Item1 Ref="0" ObjectType="DevExpress.DataAccess.Sql.SqlDataSource,DevExpress.DataAccess.v22.2" Name="sqlDataSource1" Base64=" " /></ComponentStorage><ObjectStorage><Item1 Ref="2" ObjectType="DevExpress.XtraReports.Parameters.DynamicListLookUpSettings, DevExpress.Printing.v22.2.Core" DataSource="#Ref-0" DataMember="Emitente" ValueMember="id" DisplayMember="emitente" /><Item2 ObjectType="DevExpress.XtraReports.Serialization.ObjectStorageInfo, DevExpress.XtraReports.v22.2" Ref="3" Content="System.Int32" Type="System.Type" /><Item3 Ref="5" ObjectType="DevExpress.XtraReports.Parameters.DynamicListLookUpSettings, DevExpress.Printing.v22.2.Core" DataSource="#Ref-0" DataMember="EstoqueConta" ValueMember="id" DisplayMember="descricao" /><Item4 Ref="7" ObjectType="DevExpress.XtraReports.Parameters.DynamicListLookUpSettings, DevExpress.Printing.v22.2.Core" DataSource="#Ref-0" DataMember="FiltroDatas" ValueMember="valor" DisplayMember="descricao" /><Item5 Ref="10" ObjectType="DevExpress.XtraReports.Parameters.DynamicListLookUpSettings, DevExpress.Printing.v22.2.Core" DataSource="#Ref-0" DataMember="Produto" ValueMember="id" DisplayMember="descricao" /><Item6 ObjectType="DevExpress.XtraReports.Serialization.ObjectStorageInfo, DevExpress.XtraReports.v22.2" Ref="12" Content="System.DateTime" Type="System.Type" /></ObjectStorage></XtraReportsLayoutSerializer>')
update ReportsGrupos set idnInativo = 0 where id = 9
END
GO
INSERT INTO [dbo].[configuracaoNovo]([nomeParametro],[descricaoSimplificada],[descricaoDetalhada],[tipoValor],[valor],[grupo],[subgrupo],[tamanhoValorMaximo],[idnParametroMultilinhas],[idnParametroRadio],[idnParametroSelecaoPasta],[idnPermiteAlteracaoApenasPorAdmins],[idnCampoSenha],[tabelaSelecao],[filtroSelecao],[validacaoRegularExpression],[idnPermiteSelecaoMultiplaOpcoes]) 
VALUES ('idnNaoEnviarEmailEncerramentoMDFe', 'Não enviar o e-mail de encerramento do MDFe automáticamente', 'Ative o parâmetro para o sistema NÃO fazer o envio do e-mail de encerramento do MDFe automáticamente após o mesmo ser encerrado.', 'bool', 'false', 'Email', 'MDFe',null,0,0,0,0,0,null,null,null,0)
GO
IF EXISTS (SELECT 1 FROM dashboardgrupos WHERE id = 9 and descricao = 'ESTOQUE')
BEGIN
INSERT [dbo].[Dashboard] ( [descricao], [idDashboardGrupo], [xml]) VALUES (N'Consulta de Movimentos do Estoque', 9, N'<Dashboard CurrencyCulture="pt-BR"><Title Text="Dashboard" /><DataSources><SqlDataSource Name="Fonte de dados SQL 1" ComponentName="dashboardSqlDataSource1" DataProcessingMode="Client"><Connection Name="localhost_TryNFeOnlineV805_Connection" ProviderKey="MSSqlServer"><Parameters><Parameter Name="server" Value="localhost\sqlexpress" /><Parameter Name="database" Value="TryNFeOnline" /><Parameter Name="useIntegratedSecurity" Value="True" /><Parameter Name="read only" Value="1" /><Parameter Name="generateConnectionHelper" Value="false" /><Parameter Name="userid" Value="" /><Parameter Name="password" Value="" /></Parameters></Connection><Query Type="CustomSqlQuery" Name="FiltroDatas"><Sql>SELECT ''diario''       AS valor, ''DIÁRIO''         AS descricao
UNION ALL
SELECT ''mensal'',       ''MENSAL''
UNION ALL
SELECT ''bimestral'',    ''BIMESTRAL''
UNION ALL
SELECT ''trimestral'',   ''TRIMESTRAL''
UNION ALL
SELECT ''quadrimestral'',''QUADRIMESTRAL''
UNION ALL
SELECT ''semestral'',    ''SEMESTRAL''
UNION ALL
SELECT ''anual'',        ''ANUAL''</Sql></Query><Query Type="CustomSqlQuery" Name="Emitente"><Sql>select id, concat(id, '' - '', razaosocial) as emitente from emitente where isnull(idnBaixa,0) = 0</Sql></Query><Query Type="CustomSqlQuery" Name="ContaEstoque"><Sql>select id, concat(id, '' - '', descricao) as descricao from EstoqueConta</Sql></Query><Query Type="CustomSqlQuery" Name="Produto"><Sql>select id, concat(id, '' - '', descricao) as descricao 
from produto 
where isnull(idnBaixa,0) = 0
order by id asc</Sql></Query><Query Type="CustomSqlQuery" Name="Movimentos"><Parameter Name="dataCompetencia" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataCompetencia)</Parameter><Parameter Name="dataMesPassado" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataMesPassado)</Parameter><Parameter Name="modoAgrupamento" Type="DevExpress.DataAccess.Expression">(System.String)(?modoAgrupamento)</Parameter><Parameter Name="idFilial" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idFilial)</Parameter><Parameter Name="idProduto" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idProduto)</Parameter><Parameter Name="idProdutoClassificacao" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idProdutoClassificacao)</Parameter><Parameter Name="idConta" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idConta)</Parameter><Parameter Name="dataAtual" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataAtual)</Parameter><Sql>declare @Movimentos table 
(
	idProduto int, 
	idProdutoClassificacao int, 
	codigoProdutoClasse int,
	dscProduto varchar(300), 
	unidadeMedida varchar(10),  
	dataMovimento date,
	idContaEstoque int,
	qtdSaida decimal(18,4),	
	qtdEntrada decimal(18,4),
	saldoEstoqueInicial decimal(18,4)
)

-- Preenchimento da tabela
insert into @Movimentos
select 
	idProduto, 
	idProdutoClassificacao, 
	codigoProdutoClasse,
	dscProduto, 
	unidadeMedida,  
	cast(data as date) as data, 
	idConta,
	sum(case when idnOperacao = ''-'' then qtd else 0 end) as qtdSaida,
	sum(case when idnOperacao = ''+'' then qtd else 0 end) as qtdEntrada,
	saldoEstoqueInicial
from EstoqueMovimentoComSaldo(@dataAtual, @idFilial, @idProduto, @idProdutoClassificacao, @idConta, @dataMesPassado)
group by 
	idProduto, 
	idProdutoClassificacao, 
	codigoProdutoClasse,
	dscProduto, 
	unidadeMedida, 
	saldoEstoqueInicial, 
	cast(data as date), 
	idConta;

-- Resultado agrupado dinamicamente com saldo acumulado
WITH Movimentos AS (
    SELECT 
        m.idProduto,
        m.idProdutoClassificacao,
		codigoProdutoClasse,
        m.dscProduto,
        m.unidadeMedida,
        m.qtdEntrada,
        m.qtdSaida,
        (m.qtdEntrada - (m.qtdSaida * -1)) AS saldo,
        m.saldoEstoqueInicial,

        -- Agrupamento dinâmico
        CASE 
			WHEN @modoAgrupamento = ''diario'' THEN CONVERT(varchar(10), m.dataMovimento, 120) -- yyyy-MM-dd
			WHEN @modoAgrupamento = ''mensal'' THEN FORMAT(m.dataMovimento, ''yyyy-MM'') -- Ex: 2025-08
			WHEN @modoAgrupamento = ''bimestral'' THEN FORMAT(m.dataMovimento, ''yyyy'') + ''-B'' + CAST(((DATEPART(MONTH, m.dataMovimento) - 1) / 2 + 1) AS varchar)
			WHEN @modoAgrupamento = ''trimestral'' THEN FORMAT(m.dataMovimento, ''yyyy'') + ''-T'' + CAST(((DATEPART(MONTH, m.dataMovimento) - 1) / 3 + 1) AS varchar)
			WHEN @modoAgrupamento = ''quadrimestral'' THEN FORMAT(m.dataMovimento, ''yyyy'') + ''-Q'' + CAST(((DATEPART(MONTH, m.dataMovimento) - 1) / 4 + 1) AS varchar)
			WHEN @modoAgrupamento = ''semestral'' THEN FORMAT(m.dataMovimento, ''yyyy'') + ''-S'' + CAST(((DATEPART(MONTH, m.dataMovimento) - 1) / 6 + 1) AS varchar)
			WHEN @modoAgrupamento = ''anual'' THEN FORMAT(m.dataMovimento, ''yyyy'') -- Ex: 2025
		ELSE FORMAT(m.dataMovimento, ''yyyy-MM-dd'') -- padrão: diário
	END AS periodo,
	m.dataMovimento
    FROM @Movimentos m
),
MovimentosAgrupados AS (
    SELECT 
        idProduto,
        idProdutoClassificacao,
		codigoProdutoClasse,
        dscProduto,
        unidadeMedida,
        periodo,
        MIN(dataMovimento) as dataBaseConsulta, -- usado para ordenação cronológica
        SUM(qtdEntrada) as qtdEntrada,
        SUM(qtdSaida) as qtdSaida,
        SUM(qtdEntrada - (qtdSaida * -1)) as saldoPeriodo,
        MIN(saldoEstoqueInicial) as saldoEstoqueInicial -- geralmente só existe na primeira linha mesmo
    FROM Movimentos
    GROUP BY 
        idProduto,
        idProdutoClassificacao,
		codigoProdutoClasse,
        dscProduto,
        unidadeMedida,
        periodo
),
SaldoAcumulado AS (
    SELECT 
        ma.*,
        ROW_NUMBER() OVER (PARTITION BY idProduto, idProdutoClassificacao ORDER BY dataBaseConsulta) as rn
    FROM MovimentosAgrupados ma
),
SaldoFinalizado AS (
    SELECT 
        *,
        SUM(
            CASE 
                WHEN rn = 1 THEN saldoEstoqueInicial + saldoPeriodo
                ELSE saldoPeriodo
            END
        ) OVER (
            PARTITION BY idProduto, idProdutoClassificacao 
            ORDER BY dataBaseConsulta 
            ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
        ) as saldoFinal
    FROM SaldoAcumulado
)
SELECT 
	codigoProdutoClasse,
    dscProduto,
    unidadeMedida,
    periodo,
    qtdEntrada,
    qtdSaida,
    CASE 
        WHEN rn = 1 THEN saldoEstoqueInicial
        ELSE NULL
    END as saldoInicial,
    saldoFinal
FROM SaldoFinalizado
ORDER BY idProduto, idProdutoClassificacao, periodo
</Sql></Query><Query Type="CustomSqlQuery" Name="Classificacao"><Sql>select id, concat(sequencia, '' - '', case when dscAbreviadoNFe = '''' then descricao else dscAbreviadoNFe end) as classificacao 
from ProdutoClassificacao 
where isnull(idnBaixado,0) = 0</Sql></Query><ResultSchema><DataSet Name="Fonte de dados SQL 1"><View Name="FiltroDatas"><Field Name="valor" Type="String" /><Field Name="descricao" Type="String" /></View><View Name="Emitente"><Field Name="id" Type="Int32" /><Field Name="emitente" Type="String" /></View><View Name="ContaEstoque"><Field Name="id" Type="Int32" /><Field Name="descricao" Type="String" /></View><View Name="Produto"><Field Name="id" Type="Int32" /><Field Name="descricao" Type="String" /></View><View Name="Movimentos"><Field Name="codigoProdutoClasse" Type="Int32" /><Field Name="dscProduto" Type="String" /><Field Name="unidadeMedida" Type="String" /><Field Name="periodo" Type="String" /><Field Name="qtdEntrada" Type="Decimal" /><Field Name="qtdSaida" Type="Decimal" /><Field Name="saldoInicial" Type="Decimal" /><Field Name="saldoFinal" Type="Decimal" /></View><View Name="Classificacao"><Field Name="id" Type="Int32" /><Field Name="classificacao" Type="String" /></View></DataSet></ResultSchema><ConnectionOptions CloseConnection="true" DbCommandTimeout="2500" /></SqlDataSource></DataSources><Parameters><Parameter Name="dataMesPassado" Type="System.DateTime" Value="2025-07-01T00:00:00" Description="Data Inicial" /><Parameter Name="dataAtual" Type="System.DateTime" Value="2025-08-12T00:00:00-03:00" Description="Data Competência" /><Parameter Name="modoAgrupamento" Value="mensal" Description="Agrupamento"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="FiltroDatas" ValueMember="valor" DisplayMember="descricao" /></Parameter><Parameter Name="idFilial" Type="System.Int32" Value="1" Description="Filial"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Emitente" ValueMember="id" DisplayMember="emitente" /></Parameter><Parameter Name="idProduto" Type="System.Int32" Value="0" Description="Produto"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Produto" ValueMember="id" DisplayMember="descricao" SortByMember="id" /></Parameter><Parameter Name="idProdutoClassificacao" Type="System.Int32" Value="0" Description="Classificação"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Classificacao" ValueMember="id" DisplayMember="classificacao" /></Parameter><Parameter Name="idConta" Type="System.Int32" Value="1" Description="Conta Estoque"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="ContaEstoque" ValueMember="id" DisplayMember="descricao" /></Parameter></Parameters><Items><Grid ComponentName="gridDashboardItem2" Name="Movimento de Estoque" DataSource="dashboardSqlDataSource1" DataMember="Movimentos"><DataItems><Dimension DataMember="periodo" DefaultId="DataItem0" /><Dimension DataMember="dscProduto" DefaultId="DataItem1" /><Dimension DataMember="qtdEntrada" DefaultId="DataItem2"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="qtdSaida" DefaultId="DataItem3"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="saldoFinal" DefaultId="DataItem4"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="saldoInicial" DefaultId="DataItem5"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="codigoProdutoClasse" DefaultId="DataItem6"><NumericFormat FormatType="Number" Precision="0" Unit="Ones" /></Dimension><Dimension DataMember="unidadeMedida" DefaultId="DataItem7" /></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 1" DataItem="DataItem5" DataItemApplyTo="DataItem5"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" FontStyle="Bold" ForeColor="-16732080" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 2" DataItem="DataItem5" DataItemApplyTo="DataItem5"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="Custom" FontStyle="Bold" ForeColor="-1048576" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 3" DataItem="DataItem2" DataItemApplyTo="DataItem2"><FormatConditionValue Condition="GreaterOrEqual"><AppearanceSettings AppearanceType="Custom" BackColor="-4070243" FontStyle="Bold" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 5" DataItemApplyTo="DataItem4"><FormatConditionExpression Expression="[DataItem6] &lt;&gt; ''null''"><AppearanceSettings AppearanceType="Custom" BackColor="-6108179" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 6" DataItemApplyTo="DataItem5"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-1842205" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 7" DataItemApplyTo="DataItem6"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-1842205" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 8" DataItemApplyTo="DataItem1"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-1842205" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 9" DataItemApplyTo="DataItem7"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-1842205" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 10" DataItemApplyTo="DataItem0"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-1842205" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 4" DataItemApplyTo="DataItem3"><FormatConditionExpression Expression="[DataItem3] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-29301" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Código Produto" Weight="28.637627432808163"><Dimension DefaultId="DataItem6" /></GridDimensionColumn><GridDimensionColumn Name="Descrição" Weight="310.56533827618171"><Dimension DefaultId="DataItem1" /></GridDimensionColumn><GridDimensionColumn Name="Unidade" Weight="31.696014828544957"><Dimension DefaultId="DataItem7" /></GridDimensionColumn><GridDimensionColumn Name="Período" Weight="48.100092678405936"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Saldo Inicial" Weight="44.48563484708064"><Dimension DefaultId="DataItem5" /></GridDimensionColumn><GridDimensionColumn Name="Total de Entradas" Weight="45.875810936051906"><Dimension DefaultId="DataItem2" /></GridDimensionColumn><GridDimensionColumn Name="Total de Saídas" Weight="48.9341983317887"><Dimension DefaultId="DataItem3" /></GridDimensionColumn><GridDimensionColumn Name="Saldo Final" Weight="41.7052826691381"><Dimension DefaultId="DataItem4" /></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid></Items><LayoutTree><LayoutGroup Orientation="Vertical" Weight="100"><LayoutItem DashboardItem="gridDashboardItem2" Weight="49.939246658566219" /></LayoutGroup></LayoutTree></Dashboard>')
END
GO

IF EXISTS (SELECT 1 FROM dashboardgrupos WHERE id = 9 and descricao = 'ESTOQUE')
BEGIN
INSERT [dbo].[Dashboard] ( [descricao], [idDashboardGrupo], [xml]) VALUES ( N'Consulta de Movimentos do Estoque Total', 9, N'<Dashboard CurrencyCulture="pt-BR"><Title Text="Dashboard" /><DataSources><SqlDataSource Name="Fonte de dados SQL 1" ComponentName="dashboardSqlDataSource1" DataProcessingMode="Client"><Connection Name="localhost_TryNFeOnlineV805_Connection" ProviderKey="MSSqlServer"><Parameters><Parameter Name="server" Value="localhost\sqlexpress" /><Parameter Name="database" Value="TryNFeOnline" /><Parameter Name="useIntegratedSecurity" Value="True" /><Parameter Name="read only" Value="1" /><Parameter Name="generateConnectionHelper" Value="false" /><Parameter Name="userid" Value="" /><Parameter Name="password" Value="" /></Parameters></Connection><Query Type="CustomSqlQuery" Name="FiltroDatas"><Sql>SELECT ''diario''       AS valor, ''DIÁRIO''         AS descricao
UNION ALL
SELECT ''mensal'',       ''MENSAL''
UNION ALL
SELECT ''bimestral'',    ''BIMESTRAL''
UNION ALL
SELECT ''trimestral'',   ''TRIMESTRAL''
UNION ALL
SELECT ''quadrimestral'',''QUADRIMESTRAL''
UNION ALL
SELECT ''semestral'',    ''SEMESTRAL''
UNION ALL
SELECT ''anual'',        ''ANUAL''</Sql></Query><Query Type="CustomSqlQuery" Name="Emitente"><Sql>select id, concat(id, '' - '', razaosocial) as emitente from emitente where isnull(idnBaixa,0) = 0</Sql></Query><Query Type="CustomSqlQuery" Name="ContaEstoque"><Sql>select id, concat(id, '' - '', descricao) as descricao from EstoqueConta</Sql></Query><Query Type="CustomSqlQuery" Name="Produto"><Sql>select id, concat(id, '' - '', descricao) as descricao 
from produto 
where isnull(idnBaixa,0) = 0
order by id asc</Sql></Query><Query Type="CustomSqlQuery" Name="Classificacao"><Sql>select id, concat(sequencia, '' - '', case when dscAbreviadoNFe = '''' then descricao else dscAbreviadoNFe end) as classificacao 
from ProdutoClassificacao 
where isnull(idnBaixado,0) = 0</Sql></Query><Query Type="CustomSqlQuery" Name="Movimentos"><Parameter Name="dataAtual" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataAtual)</Parameter><Parameter Name="dataMesPassado" Type="DevExpress.DataAccess.Expression">(System.DateTime)(?dataMesPassado)</Parameter><Parameter Name="idFilial" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idFilial)</Parameter><Parameter Name="idConta" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idConta)</Parameter><Parameter Name="idProduto" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idProduto)</Parameter><Parameter Name="idProdutoClassificacao" Type="DevExpress.DataAccess.Expression">(System.Int32)(?idProdutoClassificacao)</Parameter><Sql>-- Tabela temporária de movimentos agregados (já SEM data)
DECLARE @Movimentos TABLE
(
    idProduto               int,
    idProdutoClassificacao  int,
    codigoProdutoClasse     int,
    dscProduto              varchar(300),
    unidadeMedida           varchar(10),
    idContaEstoque          int,
    qtdSaida                decimal(18,4),
    qtdEntrada              decimal(18,4),
    saldoEstoqueInicial     decimal(18,4)
);

INSERT INTO @Movimentos
SELECT
    idProduto,
    idProdutoClassificacao,
    codigoProdutoClasse,
    dscProduto,
    unidadeMedida,
    idConta,
    SUM(CASE WHEN idnOperacao = ''-'' THEN qtd ELSE 0 END) AS qtdSaida,
    SUM(CASE WHEN idnOperacao = ''+'' THEN qtd ELSE 0 END) AS qtdEntrada,
    MIN(saldoEstoqueInicial)                               AS saldoEstoqueInicial  -- assume único por produto no período
FROM EstoqueMovimentoComSaldo(@dataAtual, @idFilial, @idProduto, @idProdutoClassificacao, @idConta, @dataMesPassado)
GROUP BY
    idProduto, idProdutoClassificacao, codigoProdutoClasse,
    dscProduto, unidadeMedida, idConta;

-- Total do período (por produto)
SELECT
	m.idProduto,
	m.idProdutoClassificacao,
    m.codigoProdutoClasse,
    m.dscProduto,
    m.unidadeMedida,
	MIN(m.saldoEstoqueInicial)                       AS saldoInicial,
    SUM(m.qtdEntrada)                                AS qtdEntrada,
    SUM(m.qtdSaida)                                  AS qtdSaida,
    MIN(m.saldoEstoqueInicial) + SUM(m.qtdEntrada) - (SUM(m.qtdSaida) *-1) AS saldoFinal
FROM @Movimentos m
GROUP BY
    m.codigoProdutoClasse, m.dscProduto, m.unidadeMedida, m.idProduto, m.idProdutoClassificacao
ORDER BY
    m.idProduto, m.idProdutoClassificacao;</Sql></Query><ResultSchema><DataSet Name="Fonte de dados SQL 1"><View Name="FiltroDatas"><Field Name="valor" Type="String" /><Field Name="descricao" Type="String" /></View><View Name="Emitente"><Field Name="id" Type="Int32" /><Field Name="emitente" Type="String" /></View><View Name="ContaEstoque"><Field Name="id" Type="Int32" /><Field Name="descricao" Type="String" /></View><View Name="Produto"><Field Name="id" Type="Int32" /><Field Name="descricao" Type="String" /></View><View Name="Classificacao"><Field Name="id" Type="Int32" /><Field Name="classificacao" Type="String" /></View><View Name="Movimentos"><Field Name="idProduto" Type="Int32" /><Field Name="idProdutoClassificacao" Type="Int32" /><Field Name="codigoProdutoClasse" Type="Int32" /><Field Name="dscProduto" Type="String" /><Field Name="unidadeMedida" Type="String" /><Field Name="saldoInicial" Type="Decimal" /><Field Name="qtdEntrada" Type="Decimal" /><Field Name="qtdSaida" Type="Decimal" /><Field Name="saldoFinal" Type="Decimal" /></View></DataSet></ResultSchema><ConnectionOptions CloseConnection="true" DbCommandTimeout="2500" /></SqlDataSource></DataSources><Parameters><Parameter Name="dataMesPassado" Type="System.DateTime" Value="2025-07-01T00:00:00" Description="Data Inicial" /><Parameter Name="dataAtual" Type="System.DateTime" Value="2025-08-12T00:00:00-03:00" Description="Data Final" /><Parameter Name="idFilial" Type="System.Int32" Value="1" Description="Filial"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Emitente" ValueMember="id" DisplayMember="emitente" /></Parameter><Parameter Name="idProduto" Type="System.Int32" Value="0" Description="Produto"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Produto" ValueMember="id" DisplayMember="descricao" SortByMember="id" /></Parameter><Parameter Name="idProdutoClassificacao" Type="System.Int32" Value="0" Description="Classificação"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="Classificacao" ValueMember="id" DisplayMember="classificacao" /></Parameter><Parameter Name="idConta" Type="System.Int32" Value="1" Description="Conta Estoque"><DynamicListLookUpSettings DataSourceName="dashboardSqlDataSource1" DataMember="ContaEstoque" ValueMember="id" DisplayMember="descricao" /></Parameter></Parameters><Items><Grid ComponentName="gridDashboardItem2" Name="Movimento de Estoque" DataSource="dashboardSqlDataSource1" DataMember="Movimentos"><DataItems><Dimension DataMember="qtdEntrada" DefaultId="DataItem4"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="qtdSaida" DefaultId="DataItem6"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="unidadeMedida" DefaultId="DataItem2" /><Dimension DataMember="dscProduto" DefaultId="DataItem1" /><Dimension DataMember="codigoProdutoClasse" DefaultId="DataItem0"><NumericFormat FormatType="Number" Precision="0" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="saldoInicial" DefaultId="DataItem3"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension><Dimension DataMember="saldoFinal" DefaultId="DataItem5"><NumericFormat FormatType="Number" Unit="Ones" IncludeGroupSeparator="true" /></Dimension></DataItems><FormatRules><GridItemFormatRule Name="FormatRule 11" DataItem="DataItem3" DataItemApplyTo="DataItem3"><FormatConditionValue Condition="Greater"><AppearanceSettings AppearanceType="Custom" FontStyle="Bold" ForeColor="-16732080" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 12" DataItem="DataItem3" DataItemApplyTo="DataItem3"><FormatConditionValue Condition="Less"><AppearanceSettings AppearanceType="Custom" FontStyle="Bold" ForeColor="-1048576" /><Value1 Type="System.Decimal" Value="0" /></FormatConditionValue></GridItemFormatRule><GridItemFormatRule Name="FormatRule 13" DataItemApplyTo="DataItem4"><FormatConditionExpression Expression="[DataItem4] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-4070243" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 14" DataItemApplyTo="DataItem6"><FormatConditionExpression Expression="[DataItem6] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-29301" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule><GridItemFormatRule Name="FormatRule 15" DataItemApplyTo="DataItem5"><FormatConditionExpression Expression="[DataItem5] Is Not Null"><AppearanceSettings AppearanceType="Custom" BackColor="-6108179" FontStyle="Bold" /></FormatConditionExpression></GridItemFormatRule></FormatRules><GridColumns><GridDimensionColumn Name="Código Produto" Weight="28.689864549276024"><Dimension DefaultId="DataItem0" /></GridDimensionColumn><GridDimensionColumn Name="Descrição" Weight="307.74170948155046"><Dimension DefaultId="DataItem1" /></GridDimensionColumn><GridDimensionColumn Name="Unidade" Weight="23.540401681457251"><Dimension DefaultId="DataItem2" /></GridDimensionColumn><GridDimensionColumn Name="Saldo Inicial" Weight="46.099953292853776"><Dimension DefaultId="DataItem3" /></GridDimensionColumn><GridDimensionColumn Name="Total de Entradas" Weight="43.647828117701984"><Dimension DefaultId="DataItem4" /></GridDimensionColumn><GridDimensionColumn Name="Total de Saídas" Weight="40.705277907519822"><Dimension DefaultId="DataItem6" /></GridDimensionColumn><GridDimensionColumn Name="Saldo Final" Weight="34.574964969640334"><Dimension DefaultId="DataItem5" /></GridDimensionColumn></GridColumns><GridOptions ColumnWidthMode="Manual" /><ColumnFilterOptions /></Grid></Items><LayoutTree><LayoutGroup Orientation="Vertical" Weight="100"><LayoutItem DashboardItem="gridDashboardItem2" Weight="50.060753341433781" /></LayoutGroup></LayoutTree></Dashboard>')
END
GO
UPDATE DashboardGrupos set idnInativo = 0 where id = 9
GO
INSERT INTO VERSAO(VERSAO, VERSAOATUALIZACAO, DATAATUALIZACAO, REVISAO) VALUES(559, 817, GETDATE(),1);