DROP PROCEDURE OP_CARD_MONTInsProc
GO
CREATE PROCEDURE OP_CARD_MONTInsProc
(
    @SITEID        UD_IDSITE,
    @CARDID        char(2),
    @DATEPOS       UD_FECHA,
    @DATEPROCE     UD_FECHA,
    @CURYID        UD_CURYID,
    @TOTALCARD     UD_MONTO,
    @STATUS        bit                  = NULL,
    @USERID        UD_USERID
)
AS
BEGIN
    BEGIN TRAN

    INSERT INTO OP_CARD_MONT(SITEID,CARDID,DATEPOS,DATEPROCE,CURYID,TOTALCARD,STATUS,USERID
                             )
    VALUES(@SITEID,@CARDID,@DATEPOS,@DATEPROCE,@CURYID,@TOTALCARD,@STATUS,@USERID
           )

    IF (@@error!=0)
    BEGIN
        RAISERROR  20000 'Error Insertando en  OP_CARD_MONT '
        ROLLBACK TRAN
        RETURN(1)
    
    END

    IF NOT EXISTS (SELECT * FROM OP_CARD_MONTSALES WHERE SITEID=@SITEID AND CARDID=@CARDID AND DATEPROCE=@DATEPROCE)	
    BEGIN
    	INSERT INTO OP_CARD_MONTSALES(SITEID,CARDID,DATEPROCE,CURYID,STATUS,USERID,TOTALPENSALES)
    	SELECT T.SITEID,T.CARDID,@DATEPROCE,@CURYID,0,@USERID,SUM(T.TOTCARDPEN) FROM OP_SALESCARD AS T JOIN OP_SALES AS S
	ON T.SITEID=S.SITEID AND T.DOCTYPEID=S.DOCTYPEID AND T.NBRDOCUMENT=S.NBRDOCUMENT
    	WHERE T.SITEID=@SITEID AND T.CARDID=@CARDID AND T.DATEPROCESALES=@DATEPROCE AND S.DOCSTATUSID<>'AN'
    	GROUP BY T.SITEID,T.CARDID

    	IF (@@error!=0)
    	BEGIN
        	RAISERROR  20000 'Error Insertando en  OP_CARD_MONTSALES '
        	ROLLBACK TRAN
        	RETURN(1)
    	END
    END

    COMMIT TRAN

END

