UPDATE TBDD_MODULES SET DB_VERSION = '1.5.4.1' WHERE SHORT_NAME = 'SIG_ENV_CR'
GO
CREATE FUNCTION dbo.FNDD_Generate5DigitRandomCode()
RETURNS CHAR(5)
AS
BEGIN
    DECLARE @Code CHAR(5), @Rand1 INT, @Rand2 INT, @Rand3 INT, @Rand4 INT, @Rand5 INT
    
    SET @Rand1 = ABS(CHECKSUM(CONVERT(VARBINARY, CURRENT_TIMESTAMP))) % 36
    SET @Rand2 = ABS(CHECKSUM(CONVERT(VARBINARY, CURRENT_TIMESTAMP) + CAST(@Rand1 AS VARBINARY))) % 36
    SET @Rand3 = ABS(CHECKSUM(CONVERT(VARBINARY, CURRENT_TIMESTAMP) + CAST(@Rand2 AS VARBINARY))) % 36
    SET @Rand4 = ABS(CHECKSUM(CONVERT(VARBINARY, CURRENT_TIMESTAMP) + CAST(@Rand3 AS VARBINARY))) % 36
    SET @Rand5 = ABS(CHECKSUM(CONVERT(VARBINARY, CURRENT_TIMESTAMP) + CAST(@Rand4 AS VARBINARY))) % 36
    
    SET @Code =
        CHAR(CASE WHEN @Rand1 < 10 THEN 48 + @Rand1 ELSE 55 + @Rand1 END) +
        CHAR(CASE WHEN @Rand2 < 10 THEN 48 + @Rand2 ELSE 55 + @Rand2 END) +
        CHAR(CASE WHEN @Rand3 < 10 THEN 48 + @Rand3 ELSE 55 + @Rand3 END) +
        CHAR(CASE WHEN @Rand4 < 10 THEN 48 + @Rand4 ELSE 55 + @Rand4 END) +
        CHAR(CASE WHEN @Rand5 < 10 THEN 48 + @Rand5 ELSE 55 + @Rand5 END)
    
    RETURN @Code
END
GO
CREATE TRIGGER [dbo].TBSIG_ENVELOPE_RECEIVER_AFT_UPD ON [dbo].[TBSIG_ENVELOPE_RECEIVER]
FOR INSERT
AS
BEGIN 
	DECLARE @ENVELOPE_ID INT,@RECEIVER_ID INT,@ACCESS_CODE NVARCHAR(64)
	SELECT  
		@ENVELOPE_ID = ENVELOPE_ID,
		@RECEIVER_ID = RECEIVER_ID,
		@ACCESS_CODE = ACCESS_CODE FROM inserted
	
	IF LEN(@ACCESS_CODE) = 0
		BEGIN
			SELECT @ACCESS_CODE = [dbo].[FNDD_Generate5DigitRandomCode] ();
			UPDATE TBSIG_ENVELOPE_RECEIVER SET ACCESS_CODE = @ACCESS_CODE FROM INSERTED 
				WHERE TBSIG_ENVELOPE_RECEIVER.ENVELOPE_ID = INSERTED.ENVELOPE_ID AND TBSIG_ENVELOPE_RECEIVER.RECEIVER_ID = INSERTED.RECEIVER_ID;
		END
END	