UPDATE TBDD_MODULES SET DB_VERSION = '2.5.0.2' where NAME = 'Record-Organizer' 
GO 

ALTER TABLE TBPMO_DOC_ID_CHANGED ADD [PARENT_ID] BIGINT NOT NULL DEFAULT 0
GO
ALTER TABLE TBPMO_DOC_ID_CHANGED ADD [FILENAME] VARCHAR(200) NOT NULL DEFAULT ''
GO
CREATE TRIGGER [dbo].[TBPMO_DOC_ID_CHANGED_UPD] ON [dbo].TBPMO_DOC_ID_CHANGED
FOR INSERT
AS
BEGIN 
	DECLARE @DocID BIGINT, @PARENT_ID BIGINT, @FILENAME VARCHAR(200)
	SELECT  @DocID = OLD_DOC_ID FROM inserted
	
	DECLARE @ECM_USR_ID INTEGER
	SELECT @PARENT_ID = dwParentID,@FILENAME = szLongName
		FROM [DD_VMP01_APS01_windream60].[dbo].BaseAttributes where dwDocID = @DocID
			
	UPDATE TBPMO_DOC_ID_CHANGED SET [FILENAME] = @FILENAME,[PARENT_ID] = @PARENT_ID
	FROM INSERTED
	WHERE TBPMO_DOC_ID_CHANGED.GUID = INSERTED.GUID
END	
GO

ALTER PROCEDURE [dbo].[PRPMO_DOC_HANDLE_DOCID_CHANGED] AS
DECLARE
	@GUID	INTEGER,
	@OLD_DOC_ID	INTEGER,
	@PARENT_ID	BIGINT,
	@FILENAME	VARCHAR(200),
	@DOC_PATH	VARCHAR(500),
	@USER_ID	INTEGER,
	@HOUR_EXIST	INTEGER	
			--select * from TBPMO_DOC_ID_CHANGED					
DECLARE c_REDO CURSOR FOR 
	SELECT GUID,OLD_DOC_ID,PARENT_ID,USER_ID,UPPER(FILENAME),DATEDIFF(HOUR,CREATED_WHEN,GETDATE())
	FROM TBPMO_DOC_ID_CHANGED WHERE 
	NEW_DOC_ID IS NULL --AND PARENT_ID > 0
  OPEN c_REDO 
    FETCH NEXT FROM c_REDO INTO @GUID,@OLD_DOC_ID,@PARENT_ID,@USER_ID,@FILENAME,@HOUR_EXIST
    WHILE @@FETCH_STATUS = 0
	BEGIN
		PRINT CONVERT(VARCHAR(10),@PARENT_ID)
		PRINT CONVERT(VARCHAR(100),@FILENAME)
				DECLARE @NEW_DOC_ID INTEGER
				SELECT @NEW_DOC_ID = DocID FROM VWPMO_DOC_SYNC
				WHERE UPPER(Filename)  = @FILENAME AND dwParentID = @PARENT_ID
		
			
				IF @NEW_DOC_ID > 0
					BEGIN
						PRINT CONVERT(VARCHAR(10),@NEW_DOC_ID)
						EXEC PRPMO_DOC_CHANGE_DOCID @OLD_DOC_ID,@NEW_DOC_ID,'DD_HANDLE_DOC_CHANGED'

						UPDATE TBPMO_DOC_ID_CHANGED SET NEW_DOC_ID = @NEW_DOC_ID, CHANGED_WHEN = GETDATE() WHERE GUID = @GUID
						IF NOT EXISTS(SELECT GUID FROM TBPMO_DOC_USER_REFRESH_VIEW WHERE USER_ID = @USER_ID AND REFRESHED_WHEN IS NULL)
							INSERT INTO TBPMO_DOC_USER_REFRESH_VIEW (USER_ID) VALUES (@USER_ID)
						ELSE
							UPDATE TBPMO_DOC_USER_REFRESH_VIEW SET REFRESHED_WHEN = NULL WHERE USER_ID = @USER_ID
					END
				ELSE
					IF @HOUR_EXIST > 48
						UPDATE TBPMO_DOC_ID_CHANGED SET NEW_DOC_ID = 9999, CHANGED_WHEN = GETDATE() WHERE GUID = @GUID
		FETCH NEXT FROM c_REDO INTO @GUID,@OLD_DOC_ID,@PARENT_ID,@USER_ID,@FILENAME,@HOUR_EXIST
	END
CLOSE c_REDO
DEALLOCATE c_REDO
GO