/*
=======================================================================================
'Job.................:  
'Função..............: 
'Objetivo............: Incluir registro na pendencia para conciliação. Registros de Cupom não fiscal
'Tabelas.............: 
'Dt Modificação......: 20/01/2021
'Modificação.........: 
'=======================================================================================
Tag #A001 - Alteração do codigo  
Tag #I001 - Inclusão de novo codigo 
*/
IF OBJECT_ID('PDV_CUPOM_NAO_FISCAL_TEF_PEND') IS NULL 
BEGIN 
	 CREATE TABLE PDV_CUPOM_NAO_FISCAL_TEF_PEND (
		ID_CTR				BIGINT IDENTITY (1,1), 
		CD_EMP				INT, 
		CD_FILIAL			INT,
	    NR_COO				INT,
		CD_CTR 				BIGINT,
		DT_CAD				DATETIME, 

		CONSTRAINT PK_PDV_CUPOM_NAO_FISCAL_TEF_PEND PRIMARY KEY (ID_CTR)
	 )
END 

GO 
IF EXISTS (SELECT * FROM SYS.TRIGGERS WHERE OBJECT_ID = OBJECT_ID(N'[DBO].[TRG_PDV_CUPOM_NAO_FISCAL_TEF_ULT_MOV]') )
BEGIN 	
	DROP TRIGGER [DBO].[TRG_PDV_CUPOM_NAO_FISCAL_TEF_ULT_MOV];
END 
GO

CREATE TRIGGER [DBO].[TRG_PDV_CUPOM_NAO_FISCAL_TEF_ULT_MOV] ON  PDV_CUPOM_NAO_FISCAL_TEF
FOR  INSERT
AS 
BEGIN 

 INSERT INTO PDV_CUPOM_NAO_FISCAL_TEF_PEND (CD_EMP, CD_FILIAL, NR_COO, CD_CTR, DT_CAD)
 SELECT   
		INSERTED.CD_EMP,
		INSERTED.CD_FILIAL,
		PDV_CUPOM_NAO_FISCAL.NR_COO  ,
		PDV_CUPOM_NAO_FISCAL.CD_CTR,
		GETDATE ()
	FROM
		INSERTED  
		JOIN PDV_CUPOM_NAO_FISCAL ON PDV_CUPOM_NAO_FISCAL.CD_EMP	  = INSERTED.CD_EMP
								 AND PDV_CUPOM_NAO_FISCAL.CD_FILIAL   = INSERTED.CD_FILIAL
								 AND PDV_CUPOM_NAO_FISCAL.CD_CTR      = INSERTED.CD_CTR

		LEFT JOIN PDV_CUPOM_NAO_FISCAL_TEF_PEND  ON PDV_CUPOM_NAO_FISCAL_TEF_PEND.CD_EMP	 = INSERTED.CD_EMP
											    AND PDV_CUPOM_NAO_FISCAL_TEF_PEND.CD_FILIAL  = INSERTED.CD_FILIAL
											    AND PDV_CUPOM_NAO_FISCAL_TEF_PEND.CD_CTR     = PDV_CUPOM_NAO_FISCAL.CD_CTR
												AND PDV_CUPOM_NAO_FISCAL_TEF_PEND.NR_COO      = PDV_CUPOM_NAO_FISCAL.NR_COO
  WHERE INSERTED.CD_EMP = 1
    AND PDV_CUPOM_NAO_FISCAL_TEF_PEND.CD_EMP IS NULL


--SELECT * FROM GLB_DT_MOVIMENTO WHERE CD_CTR_DT_MOVIMENTO  = 1296
  

END   
