--### Zuri Wed 02/13/2019 17:22:02.73 ###  
--### Zuri9.1902.2406 ###  
--### 00 Namma #######################################################################################

IF OBJECT_ID('WFLOC_LOCATION') IS NULL
BEGIN
	CREATE TABLE WFLOC_LOCATION(
		LOC_N_ID int IDENTITY(1,1) NOT NULL,
		LOC_C_NAME varchar(50) NOT NULL,
		LOC_N_TIMEZONE int NOT NULL,
		CONSTRAINT PK_WFLOC_LOCATION PRIMARY KEY  (LOC_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFLOG_LOGMESSAGE') IS NULL
BEGIN
	CREATE TABLE WFLOG_LOGMESSAGE(
		LOG_N_ID int IDENTITY(1,1) NOT NULL,
		LOG_C_CATEGORY varchar(100) NOT NULL,
		LOG_D_TIMESTAMP datetime NOT NULL,
		LOG_C_MESSAGE text NOT NULL,
		LOG_N_TYPE int NOT NULL,
		LOG_N_EVENTCODE int NOT NULL,
		LOG_N_EVENTDETAIL int NOT NULL,
		LOG_C_USER varchar(100) NOT NULL,
		LOG_C_URL varchar(200) NOT NULL,
		LOG_C_USERADDRESS varchar(20) NOT NULL,
		LOG_C_AUTHTYPE varchar(50) NOT NULL,
		LOG_C_SERVERNAME VARCHAR(200),
		CONSTRAINT PK_TLOG_LOG PRIMARY KEY  (LOG_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFADL_AUDITLOG') IS NULL
BEGIN
	CREATE TABLE WFADL_AUDITLOG(
		ADL_N_ID int IDENTITY(1,1) NOT NULL,
		ADL_C_CATEGORY varchar(100) NOT NULL,
		ADL_D_TIMESTAMP datetime NOT NULL,
		ADL_C_MESSAGE text NOT NULL,
		ADL_N_TYPE int NOT NULL,
		ADL_N_EVENTCODE int NOT NULL,
		ADL_N_EVENTDETAIL int NOT NULL,
		ADL_C_USER varchar(100) NOT NULL,
		ADL_C_URL varchar(200) NOT NULL,
		ADL_C_USERADDRESS varchar(20) NOT NULL,
		ADL_C_AUTHTYPE varchar(50) NOT NULL,
		ADL_C_SERVERNAME VARCHAR(200),
		CONSTRAINT PK_WFADL_AUDITLOG PRIMARY KEY  (ADL_N_ID ASC)
	)
END
GO

IF OBJECT_ID('WFADX_AUDITEXCEPTION') IS NULL
BEGIN
	CREATE TABLE WFADX_AUDITEXCEPTION(
		ADX_N_ID int IDENTITY(1,1) NOT NULL,
		ADX_C_CATEGORY varchar(100) NOT NULL,
		CONSTRAINT PK_WFADX_AUDITEXCEPTION PRIMARY KEY  (ADX_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMBR_MEMBERSHIP') IS NULL
BEGIN
	CREATE TABLE WFMBR_MEMBERSHIP(
		MBR_N_USR_N_ID int NOT NULL,
		MBR_C_PASSWORD varchar(100) NOT NULL,
		MBR_C_PWDQUESTION varchar(256) NULL,
		MBR_C_PWDANSWER varchar(128) NULL,
		MBR_B_ISAPPROVED bit NOT NULL,
		MBR_B_ISLOCKEDOUT bit NOT NULL,
		MBR_D_CREATEDATE datetime NOT NULL,
		MBR_D_LASTLOGINDATE datetime NULL,
		MBR_D_LASTACTIVITYDATE datetime NULL,
		MBR_D_LASTLOCKEDOUTDATE datetime NULL,
		MBR_D_LASTPWDCHANGE datetime NULL,
		MBR_N_FAILEDPWDCOUNT int NOT NULL,
		MBR_D_FAILEDPWD datetime NULL,
		MBR_N_FAILEDANSWERCOUNT int NOT NULL,
		MBR_D_FAILEDANSWER datetime NULL,
		MBR_C_PWDTYPE varchar(3) NOT NULL,
		MBR_D_PWDEXPIRATION DATETIME NULL, 
		CONSTRAINT PK_WFMBR_MEMBERSHIP PRIMARY KEY  (MBR_N_USR_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMEI_MENUITEM') IS NULL
BEGIN
	CREATE TABLE WFMEI_MENUITEM(
		MEI_N_ID int IDENTITY(1,1) NOT NULL,
		MEI_N_MEN_N_ID int NOT NULL,
		MEI_C_READERS varchar(200) NOT NULL,
		MEI_C_NAME varchar(100) NOT NULL,
		MEI_C_URL varchar(1000) NOT NULL,
		MEI_C_TARGET varchar(20) NOT NULL,
		MEI_C_HIERARCHY nvarchar(45) NOT NULL,
		MEI_N_LOCALONLY bit NOT NULL,
		MEI_N_SYSTEMMENU bit NOT NULL,
		MEI_C_IMAGE varchar(100) NULL,
		MEI_C_STATUSBAR varchar(150) NULL,
		MEI_C_LANGUAGE varchar(5) NOT NULL,
		MEI_C_NAMEKEY varchar(50) NULL,
		MEI_C_CSSCLASS varchar(100) NULL,
		CONSTRAINT PK_TMEN_MENUITEM PRIMARY KEY  (MEI_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMEN_MENU') IS NULL
BEGIN
	CREATE TABLE WFMEN_MENU(
		MEN_N_ID int IDENTITY(1,1) NOT NULL,
		MEN_N_OWNER int NOT NULL,
		MEN_C_ALIAS varchar(50) NOT NULL,
		MEN_C_EDITORS varchar(100) NOT NULL,
		MEN_C_READERS varchar(200) NOT NULL,
		MEN_C_LANGUAGES varchar(50) NOT NULL,
		MEN_N_MST_N_ID int NULL,
		MEN_N_SYSTEMMENU bit NOT NULL,
		CONSTRAINT PK_WFMEN_MENU PRIMARY KEY  (MEN_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMET_MENUTRANSLATION') IS NULL
BEGIN
	CREATE TABLE WFMET_MENUTRANSLATION(
		MET_N_ID int IDENTITY(1,1) NOT NULL,
		MET_C_LANGUAGE varchar(5) NOT NULL,
		MET_C_NAMEKEY varchar(50) NOT NULL,
		MET_C_MESSAGE varchar(300) NOT NULL,
		CONSTRAINT PK_WFMET_MENUTRANSLATION PRIMARY KEY  (MET_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMPT_MENUPATTERN') IS NULL
BEGIN
	CREATE TABLE WFMPT_MENUPATTERN(
		MPT_N_ID int IDENTITY(1,1) NOT NULL,
		MPT_C_NAME nvarchar(20) NOT NULL,
		MPT_N_TOP smallint NULL,
		MPT_N_LEFT smallint NULL,
		MPT_N_PADDING smallint NULL,
		MPT_N_WIDTH smallint NULL,
		MPT_N_HEIGHT smallint NULL,
		MPT_C_ORIENTATION nvarchar(19) NULL,
		MPT_C_ALIGNMENT nvarchar(7) NULL,
		MPT_C_TRANSITION nvarchar(120) NULL,
		MPT_C_OF_FNCOLOR nvarchar(11) NULL,
		MPT_C_OF_BGCOLOR nvarchar(11) NULL,
		MPT_C_OF_BDCOLOR nvarchar(11) NULL,
		MPT_C_OF_BGIMAGE nvarchar(100) NULL,
		MPT_C_ON_FNCOLOR nvarchar(11) NULL,
		MPT_C_ON_BGCOLOR nvarchar(11) NULL,
		MPT_C_ON_BDCOLOR nvarchar(11) NULL,
		MPT_C_ON_BGIMAGE nvarchar(100) NULL,
		MPT_C_BD_COLOR nvarchar(11) NULL,
		MPT_N_BD_WIDTH smallint NULL,
		MPT_C_FNT_SIZE nvarchar(11) NULL,
		MPT_C_FNT_STYLE nvarchar(11) NULL,
		MPT_C_FNT_BOLD nvarchar(11) NULL,
		MPT_C_FNT_NAME nvarchar(60) NULL,
		MPT_C_FNT_DECORATION nvarchar(12) NULL,
		MPT_C_SUBIMAGE nvarchar(100) NULL,
		MPT_N_SUBIMAGEPADDING smallint NULL,
		MPT_C_SUBIMAGEPOSITION nvarchar(15) NULL,
		MPT_C_SEPCOLOR nvarchar(11) NULL,
		MPT_N_SEPSIZE smallint NULL,
		MPT_N_SEPPADDING smallint NULL,
		CONSTRAINT PK_TMPD_MENUPADRAO PRIMARY KEY  (MPT_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMSG_MESSAGE') IS NULL
BEGIN
	CREATE TABLE WFMSG_MESSAGE(
		MSG_N_ID int IDENTITY(1,1) NOT NULL,
		MSG_C_CATEGORY varchar(200) NOT NULL,
		MSG_C_TITLE varchar(200) NOT NULL,
		MSG_C_LINK varchar(300) NOT NULL,
		MSG_C_MESSAGE text NOT NULL,
		MSG_C_PUBDATE datetime NOT NULL,
		MSG_C_READERS varchar(200) NOT NULL,
		CONSTRAINT PK_WFMSG_MESSAGES PRIMARY KEY  (MSG_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFMST_MENUSTYLE') IS NULL
BEGIN
	CREATE TABLE WFMST_MENUSTYLE(
		MST_N_ID int IDENTITY(1,1) NOT NULL,
		MST_C_ALIAS varchar(50) NOT NULL,
		MST_N_ROOTPATTERNID int NOT NULL,
		MST_N_SUBPATTERNID int NOT NULL,
		MST_N_SELPATTERNID int NOT NULL,
		MST_N_OPENONCLICK bit NOT NULL,
		CONSTRAINT PK_TMST_MENUESTILO PRIMARY KEY (MST_N_ID ASC),
		CONSTRAINT IX_WFMST_MENUSTYLE UNIQUE (MST_C_ALIAS ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFOWN_OWNER') IS NULL
BEGIN
	CREATE TABLE WFOWN_OWNER(
		OWN_N_ID int NOT NULL,
		OWN_C_NAME nvarchar(50) NOT NULL,
		CONSTRAINT PK_WFOWN_OWNER PRIMARY KEY (OWN_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFPRF_PROFILE') IS NULL
BEGIN
	CREATE TABLE WFPRF_PROFILE(
		PRF_N_USR_N_ID int NOT NULL,
		PRF_C_PROPERTYNAMES text NOT NULL,
		PRF_C_PROPERTYVALUES text NOT NULL,
		PRF_D_LASTUPDATE datetime NOT NULL,
		CONSTRAINT PK_WFPRF_PROFILE_1 PRIMARY KEY (PRF_N_USR_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFRGP_ROLE_GROUP') IS NULL
BEGIN
	CREATE TABLE WFRGP_ROLE_GROUP(
		RGP_N_ID int IDENTITY(1,1) NOT NULL,
		RGP_C_GUID uniqueidentifier NOT NULL,
		RGP_C_NAME varchar(50) NOT NULL,
		RGP_N_OWNER int NOT NULL,
		RGP_B_ENABLED bit NOT NULL,
		CONSTRAINT PK_WFRGR_ROLE_GROUP PRIMARY KEY (RGP_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFRGR_ROLE_GROUP_ROLES') IS NULL
BEGIN
	CREATE TABLE WFRGR_ROLE_GROUP_ROLES(
		RGR_N_ID int IDENTITY(1,1) NOT NULL,
		RGR_N_ROL_N_ID int NOT NULL,
		RGR_N_RGR_N_ID int NOT NULL,
		CONSTRAINT PK_WFRGM_ROLE_GROUP_MEMBERS PRIMARY KEY (RGR_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFRGU_ROLE_GROUP_USERS') IS NULL
BEGIN
	CREATE TABLE WFRGU_ROLE_GROUP_USERS(
		RGU_N_ID int IDENTITY(1,1) NOT NULL,
		RGU_N_RGR_N_ID int NOT NULL,
		RGU_N_USR_N_ID int NOT NULL,
		CONSTRAINT PK_WFRGU_ROLE_GROUP_USERS PRIMARY KEY (RGU_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFROL_ROLE') IS NULL
BEGIN
	CREATE TABLE WFROL_ROLE(
		ROL_N_ID int IDENTITY(1,1) NOT NULL,
		ROL_C_GUID uniqueidentifier NOT NULL,
		ROL_C_NAME varchar(50) NOT NULL,
		ROL_N_OWNER int NOT NULL,
		ROL_B_SYSTEMROLE bit NOT NULL,
		ROL_B_WINROLE bit NOT NULL,
		ROL_B_ENABLED bit NOT NULL,
		CONSTRAINT PK_WFROL_ROLE PRIMARY KEY (ROL_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFRUS_ROLE_USERS') IS NULL
BEGIN
	CREATE TABLE WFRUS_ROLE_USERS(
		RUS_N_ID int IDENTITY(1,1) NOT NULL,
		RUS_N_ROL_N_ID int NOT NULL,
		RUS_N_USR_N_ID int NULL,
		CONSTRAINT PK_WFRMB_ROLE_MEMBERS PRIMARY KEY (RUS_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFTHB_THUMBNAILS') IS NULL
BEGIN
	CREATE TABLE WFTHB_THUMBNAILS(
		THB_N_ID int IDENTITY(1,1) NOT NULL,
		THB_C_URL nvarchar(400) NOT NULL,
		THB_C_FILENAME nvarchar(100) NOT NULL,
		THB_D_EXPIRATION datetime NOT NULL,
		CONSTRAINT PK_WFTHB_THUMBNAILS PRIMARY KEY (THB_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WFUSR_USER') IS NULL
BEGIN
	CREATE TABLE WFUSR_USER(
		USR_N_ID int IDENTITY(1,1) NOT NULL,
		USR_C_GUID uniqueidentifier NOT NULL,
		USR_C_LOGIN varchar(120) NOT NULL,
		USR_C_WINLOGON varchar(120) NOT NULL,
		USR_C_FULLNAME varchar(200) NOT NULL,
		USR_C_EMAIL varchar(250) NOT NULL,
		USR_C_IMAGE1 varchar(80) NULL,
		USR_C_IMAGE2 varchar(80) NULL,
		USR_C_COMPANY varchar(80) NULL,
		USR_N_OWNER int NOT NULL,
		USR_N_LOCATION int NULL,
		USR_B_SYSTEMUSER bit NOT NULL,
		USR_B_WINUSER bit NOT NULL,
		USR_D_BIRTHDATE datetime NULL,
		CONSTRAINT PK_WFUSR_USER PRIMARY KEY (USR_N_ID ASC)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('FK_WFMBR_MEMBERSHIP_WFUSR_USER') IS NULL
	ALTER TABLE WFMBR_MEMBERSHIP ADD CONSTRAINT FK_WFMBR_MEMBERSHIP_WFUSR_USER FOREIGN KEY(MBR_N_USR_N_ID)
	REFERENCES WFUSR_USER (USR_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFMEI_MENUITEM_WFMEN_MENU') IS NULL
	ALTER TABLE WFMEI_MENUITEM ADD CONSTRAINT FK_WFMEI_MENUITEM_WFMEN_MENU FOREIGN KEY(MEI_N_MEN_N_ID)
	REFERENCES WFMEN_MENU (MEN_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFMEN_MENU_WFOWN_OWNER') IS NULL
	ALTER TABLE WFMEN_MENU ADD CONSTRAINT FK_WFMEN_MENU_WFOWN_OWNER FOREIGN KEY(MEN_N_OWNER)
	REFERENCES WFOWN_OWNER (OWN_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFPRF_PROFILE_WFUSR_USER') IS NULL
	ALTER TABLE WFPRF_PROFILE ADD  CONSTRAINT FK_WFPRF_PROFILE_WFUSR_USER FOREIGN KEY(PRF_N_USR_N_ID)
	REFERENCES WFUSR_USER (USR_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRGM_ROLE_GROUP_MEMBERS_WFRGR_ROLE_GROUP') IS NULL
	ALTER TABLE WFRGR_ROLE_GROUP_ROLES  ADD  CONSTRAINT FK_WFRGM_ROLE_GROUP_MEMBERS_WFRGR_ROLE_GROUP FOREIGN KEY(RGR_N_RGR_N_ID)
	REFERENCES WFRGP_ROLE_GROUP (RGP_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRGM_ROLE_GROUP_MEMBERS_WFROL_ROLE') IS NULL
	ALTER TABLE WFRGR_ROLE_GROUP_ROLES  ADD  CONSTRAINT FK_WFRGM_ROLE_GROUP_MEMBERS_WFROL_ROLE FOREIGN KEY(RGR_N_ROL_N_ID)
	REFERENCES WFROL_ROLE (ROL_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRGU_ROLE_GROUP_USERS_WFRGP_ROLE_GROUP') IS NULL
	ALTER TABLE WFRGU_ROLE_GROUP_USERS  ADD  CONSTRAINT FK_WFRGU_ROLE_GROUP_USERS_WFRGP_ROLE_GROUP FOREIGN KEY(RGU_N_RGR_N_ID)
	REFERENCES WFRGP_ROLE_GROUP (RGP_N_ID)
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRGU_ROLE_GROUP_USERS_WFUSR_USER') IS NULL
	ALTER TABLE WFRGU_ROLE_GROUP_USERS  ADD  CONSTRAINT FK_WFRGU_ROLE_GROUP_USERS_WFUSR_USER FOREIGN KEY(RGU_N_USR_N_ID)
	REFERENCES WFUSR_USER (USR_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRMB_ROLE_MEMBERS_WFROL_ROLE') IS NULL
	ALTER TABLE WFRUS_ROLE_USERS  ADD  CONSTRAINT FK_WFRMB_ROLE_MEMBERS_WFROL_ROLE FOREIGN KEY(RUS_N_ROL_N_ID)
	REFERENCES WFROL_ROLE (ROL_N_ID)
	ON DELETE CASCADE
GO

--##########################################################################################################################

IF NOT OBJECT_ID('FK_WFRGP_ROLE_GROUP_WFOWN_OWNER') IS NULL
BEGIN
	ALTER TABLE dbo.WFRGP_ROLE_GROUP
		DROP CONSTRAINT FK_WFRGP_ROLE_GROUP_WFOWN_OWNER
END
GO

IF NOT OBJECT_ID('FK_WFROL_ROLE_WFOWN_OWNER') IS NULL
BEGIN
	ALTER TABLE dbo.WFROL_ROLE
		DROP CONSTRAINT FK_WFROL_ROLE_WFOWN_OWNER
END
GO

--####################################################################################################

IF OBJECT_ID('FK_WFRUS_ROLE_USERS_WFUSR_USER') IS NULL
	ALTER TABLE WFRUS_ROLE_USERS  ADD  CONSTRAINT FK_WFRUS_ROLE_USERS_WFUSR_USER FOREIGN KEY(RUS_N_USR_N_ID)
	REFERENCES WFUSR_USER (USR_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('FK_WFUSR_USER_WFLOC_LOCATION') IS NULL
	ALTER TABLE WFUSR_USER  ADD  CONSTRAINT FK_WFUSR_USER_WFLOC_LOCATION FOREIGN KEY(USR_N_LOCATION)
	REFERENCES WFLOC_LOCATION (LOC_N_ID)
GO

--####################################################################################################

IF OBJECT_ID('FK_WFUSR_USER_WFOWN_OWNER') IS NULL
	ALTER TABLE WFUSR_USER  ADD  CONSTRAINT FK_WFUSR_USER_WFOWN_OWNER FOREIGN KEY(USR_N_OWNER)
	REFERENCES WFOWN_OWNER (OWN_N_ID)
	ON DELETE CASCADE
GO

--####################################################################################################

IF OBJECT_ID('WFUSD_USERDEVICE') IS NULL 
BEGIN
	CREATE TABLE WFUSD_USERDEVICE (
		USD_N_ID INT NOT NULL IDENTITY CONSTRAINT PK_WFUSD PRIMARY KEY (USD_N_ID),
		USD_USR_N_ID INT NOT NULL CONSTRAINT FK_WFUSD__WFUSR FOREIGN KEY (USD_USR_N_ID) REFERENCES WFUSR_USER (USR_N_ID) ON DELETE CASCADE,
		USD_C_DEVICENAME VARCHAR(250),
		USD_C_DEVICEPLATFORM VARCHAR(20),
		USD_C_VERSION VARCHAR(20) NOT NULL,
		USD_N_DEVICETYPE INT NOT NULL,
		USD_C_DEVICETOKEN VARCHAR(500) NOT NULL,
		USD_N_STATUS INT NOT NULL,
		USD_D_REGISTERED DATETIME NOT NULL,
		USD_D_LASTACCESS DATETIME NOT NULL,
		USD_D_STATUSCHANGED DATETIME NOT NULL,
	)
END
GO

--####################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MEI_C_CSSCLASS' AND OBJECT_NAME(OBJECT_ID) = 'WFMEI_MENUITEM')
BEGIN
	ALTER TABLE WFMEI_MENUITEM ADD
		MEI_C_CSSCLASS VARCHAR(100) NULL
END
GO

--####################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MEN_N_MST_N_ID' AND OBJECT_NAME(OBJECT_ID) = 'WFMEN_MENU')
BEGIN
	ALTER TABLE WFMEN_MENU
		ADD MEN_N_MST_N_ID INT NULL
END
GO


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MEN_N_MST_N_ID' AND OBJECT_NAME(OBJECT_ID) = 'WFMEN_MENU' AND IS_NULLABLE = 0)
BEGIN
	ALTER TABLE WFMEN_MENU
		ALTER COLUMN MEN_N_MST_N_ID INT NULL
END
GO

--####################################################################################################

UPDATE WFMEI_MENUITEM SET MEI_C_URL = '#' WHERE MEI_C_URL = '' AND MEI_N_MEN_N_ID = 1
UPDATE WFMEI_MENUITEM SET MEI_C_IMAGE = '' WHERE MEI_C_IMAGE = 'transparente5px.gif' AND MEI_N_MEN_N_ID = 1

delete from WFMEI_MENUITEM where MEI_C_NAME='MENUS' AND (MEI_C_URL = '' OR MEI_C_URL = '#')
delete from WFMEI_MENUITEM where MEI_C_URL = '/WFAdmin/Menus/MenuItems.aspx'
delete from WFMEI_MENUITEM where MEI_C_URL = '/WFAdmin/Menus/MenuStyles.aspx'
delete from WFMEI_MENUITEM where MEI_C_URL = '/WFAdmin/Menus/MenuPatterns.aspx'

GO

--################### PACOTE 082012 CORREÇÃO PARA LOGINS NUMÉRICOS ###################

UPDATE WFUSR_USER SET USR_C_LOGIN = '#' + USR_C_LOGIN + '#' WHERE ISNUMERIC(USR_C_LOGIN) = 1
UPDATE WFUSR_USER SET USR_C_LOGIN = REPLACE(REPLACE(USR_C_LOGIN, '[' , '#' ),']','#')

GO

--################### PACOTE 8.6 - 201503 ###########################################################
IF NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE NAME = 'MBR_D_PWDEXPIRATION' AND OBJECT_ID = OBJECT_ID('WFMBR_MEMBERSHIP'))
BEGIN
	ALTER TABLE WFMBR_MEMBERSHIP ADD MBR_D_PWDEXPIRATION DATETIME NULL 
END
GO

-- ##################################################################################################
IF NOT EXISTS (SELECT * FROM WFADX_AUDITEXCEPTION WHERE ADX_C_CATEGORY = 'UpdateItem (WebFoundations.Objects.Membership)')
BEGIN
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.Objects.Membership)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.Objects.LogMessage)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.Objects.LogMessage)')
END
GO



-- ##################################################################################################
IF NOT EXISTS(SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'LOG_C_SERVERNAME' AND OBJECT_ID = OBJECT_ID('WFLOG_LOGMESSAGE'))
	ALTER TABLE WFLOG_LOGMESSAGE
	ADD LOG_C_SERVERNAME VARCHAR(200)
GO

IF NOT EXISTS(SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ADL_C_SERVERNAME' AND OBJECT_ID = OBJECT_ID('WFADL_AUDITLOG'))
	ALTER TABLE WFADL_AUDITLOG
	ADD ADL_C_SERVERNAME VARCHAR(200)
GO

--
--### 10 KINGU #######################################################################################

IF OBJECT_ID('WFFBK_FEEDBACKINFO') IS NULL
BEGIN
	CREATE TABLE WFFBK_FEEDBACKINFO(
		FBK_N_ID INT IDENTITY NOT NULL,
		FBK_C_NAME VARCHAR(300)  NULL,
		FBK_C_EMAIL VARCHAR(100)  NULL,
		FBK_C_MESSAGE VARCHAR(500)  NULL,
		FBK_C_USERLOGIN VARCHAR(100) NULL,
		FBK_C_FREEFIELD1 VARCHAR(500) NULL,
		FBK_C_FREEFIELD2 VARCHAR(500) NULL,
		FBK_D_DISPATCHDATE DATETIME NULL,
		CONSTRAINT PK_WFFBK_FEEDBACKINFO PRIMARY KEY(FBK_N_ID)
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WPPOR_PORTAL') IS NULL
	CREATE TABLE WPPOR_PORTAL(
		POR_N_ID int IDENTITY(1,1) NOT NULL,
		POR_C_NAME nvarchar(40) NOT NULL,
		POR_C_ALIAS nvarchar(40) NOT NULL,
		POR_C_FOLDER nvarchar(20) NOT NULL,
		POR_N_ADMROLE int NOT NULL,
		POR_N_ROOTAREA int NOT NULL,
		POR_C_READERS nvarchar(200) NOT NULL,
		POR_N_SYSTEMPORTAL bit NOT NULL,
		POR_N_LOCALONLY bit NOT NULL,
		POR_C_LANGUAGE varchar(5) NOT NULL,
		CONSTRAINT PK_Portals PRIMARY KEY (	POR_N_ID),
		CONSTRAINT IX_WPPOR_PORTAL UNIQUE NONCLUSTERED (POR_C_NAME)
	) 
GO

--####################################################################################################

IF OBJECT_ID('WPCNT_CONTAINER') IS NULL
BEGIN
	CREATE TABLE WPCNT_CONTAINER(
		CNT_N_ID int IDENTITY(1,1) NOT NULL,
		CNT_C_TITLE varchar(50) NOT NULL,
		CNT_C_FILENAME varchar(100) NOT NULL,
		CONSTRAINT PK_WPCNT_CONTAINER PRIMARY KEY (CNT_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WPMOD_MODULE') IS NULL
BEGIN
	CREATE TABLE WPMOD_MODULE (
		MOD_N_ID int IDENTITY(1,1) NOT NULL,
		MOD_C_OWNER uniqueidentifier NOT NULL,
		MOD_C_GUID uniqueidentifier NOT NULL,
		MOD_C_NAME varchar(50) NOT NULL,
		MOD_C_CATEGORY varchar(50) NOT NULL,
		MOD_C_COMPONENT varchar(100) NOT NULL,
		MOD_N_INTERACTIVE bit NOT NULL,
		MOD_N_LOCALONLY bit NOT NULL,
		CONSTRAINT PK_WFMOD_MODULE PRIMARY KEY (MOD_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WPTRK_TRACKING') IS NULL
BEGIN
	CREATE TABLE WPTRK_TRACKING(
		TRK_N_ID int IDENTITY(1,1) NOT NULL,
		TRK_C_PAGEALIAS varchar(80) NOT NULL,
		TRK_N_PAG_N_ID int NOT NULL,
		TRK_C_AREANAME varchar(50) NOT NULL,
		TRK_N_ARE_N_ID int NOT NULL,
		TRK_C_PORTALNAME varchar(40) NOT NULL,
		TRK_N_POR_N_ID int NOT NULL,
		TRK_C_USERNAME varchar(200) NOT NULL,
		TRK_C_USR_N_ID int NOT NULL,
		TRK_C_USERIP varchar(20) NOT NULL,
		TRK_N_MEI_N_ID int NOT NULL,
		TRK_C_MENUPATH varchar(200) NOT NULL,
		TRK_D_TIMESTAMP datetime NOT NULL,
		CONSTRAINT PK_WPTRK_TRACKING PRIMARY KEY CLUSTERED (TRK_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WPTAG_TAGS') IS NULL
BEGIN
	CREATE TABLE WPTAG_TAGS(
		TAG_N_ID int IDENTITY(1,1) NOT NULL,
		TAG_C_NAME varchar(100) NOT NULL,
		TAG_C_VIEWURL varchar(200) NOT NULL,
		TAG_N_IDENTIFIER varchar(50) NOT NULL,
		TAG_C_QUALIFIER varchar(50) NOT NULL,
		TAG_C_READERS varchar(200) NOT NULL,
		CONSTRAINT PK_TGTAG_TAGS PRIMARY KEY CLUSTERED (TAG_N_ID) 
	) 
END
GO

--####################################################################################################
IF OBJECT_ID('WCWIN_WINDOW') IS NULL
BEGIN
	CREATE TABLE WCWIN_WINDOW(
		WIN_N_CTT_N_ID int NOT NULL,
		WIN_C_URL varchar(200) NOT NULL,
		WIN_C_DESCRIPTION varchar(80) NOT NULL,
		WIN_C_WIDTH varchar(5) NOT NULL,
		WIN_C_HEIGHT varchar(5) NOT NULL,
		WIN_C_USERNAME varchar(100) NOT NULL,
		WIN_C_USERLOGIN varchar(100) NOT NULL,
		WIN_C_USEREMAIL varchar(100) NOT NULL,
		CONSTRAINT PK_WCWIN_WINDOW PRIMARY KEY CLUSTERED (WIN_N_CTT_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WCSUR_SENDURL') IS NULL
BEGIN
	CREATE TABLE WCSUR_SENDURL(
		SUR_N_CTT_N_ID int NOT NULL,
		SUR_C_IMAGE varchar(200) NOT NULL,
		SUR_C_MESSAGE varchar(100) NOT NULL,
		SUR_C_TEMPLATE text NOT NULL,
		CONSTRAINT PK_WCSUR_SENDURL PRIMARY KEY CLUSTERED (SUR_N_CTT_N_ID) 
	)  
END
GO

--####################################################################################################

IF OBJECT_ID('WCPOP_POPUP') IS NULL
BEGIN
	CREATE TABLE WCPOP_POPUP(
		POP_N_CTT_N_ID int NOT NULL,
		POP_C_WIDTH int NOT NULL,
		POP_C_HEIGHT int NOT NULL,
		POP_C_URL varchar(150) NOT NULL,
		POP_D_START datetime NULL,
		POP_D_END datetime NULL,
		CONSTRAINT PK_WCPOP_POPUP PRIMARY KEY CLUSTERED (POP_N_CTT_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WCPLL_POLL') IS NULL
BEGIN
	CREATE TABLE WCPLL_POLL(
		PLL_N_ID int IDENTITY(1,1) NOT NULL,
		PLL_N_ARE_N_ID int NOT NULL,
		PLL_C_QUESTION varchar(200) NOT NULL,
		PLL_C_MESSAGE varchar(200) NOT NULL,
		PLL_C_IMAGE varchar(200) NOT NULL,
		PLL_C_ALTTEXT varchar(50) NOT NULL,
		PLL_N_GRAPHTYPE smallint NOT NULL,
		PLL_N_UNIQUE bit NOT NULL,
		PLL_N_COLUMNS smallint NOT NULL,
		PLL_N_PUBLISHED bit NOT NULL,
		PLL_N_GRAPHHEIGHT int NOT NULL,
		PLL_N_GRAPHWIDTH int NOT NULL,
		PLL_C_VOTED text NOT NULL,
		CONSTRAINT PK_WCPLL_POLL PRIMARY KEY CLUSTERED (PLL_N_ID) 
	)  
END
GO

--####################################################################################################

IF OBJECT_ID('WCPBK_PHONEBOOK') IS NULL
BEGIN
	CREATE TABLE WCPBK_PHONEBOOK(
		PBK_N_ID int IDENTITY(1,1) NOT NULL,
		PBK_N_CTT_N_ID int NOT NULL,
		PBK_C_NAME varchar(100) NOT NULL,
		PBK_C_AREA varchar(25) NULL,
		PBK_C_PHONERES varchar(30) NULL,
		PBK_C_PHONEBUS varchar(30) NULL,
		PBK_C_MOBILE varchar(30) NULL,
		PBK_C_EMAIL varchar(200) NULL,
		PBK_C_JOBTITLE varchar(100) NULL,
		PBK_C_CATEGORY varchar(30) NULL,
		PBK_C_EXTENTION varchar(8) NULL,
		PBK_C_ADDRESS varchar(250) NULL,
		PBK_C_NEIGHBORHOOD varchar(50) NULL,
		PBK_C_CITY varchar(50) NULL,
		PBK_C_STATE varchar(4) NULL,
		PBK_C_ZIP varchar(50) NULL,
		PBK_C_FREE1 varchar(200) NULL,
		PBK_C_FREE2 varchar(200) NULL,
		CONSTRAINT PK_WCPBK_PHONEBOOK PRIMARY KEY CLUSTERED (PBK_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WCHTV_HTMLVIEW') IS NULL
BEGIN
	CREATE TABLE WCHTV_HTMLVIEW(
		HTV_N_CTT_N_ID int NOT NULL,
		HTV_C_CONTENT text NOT NULL,
		CONSTRAINT PK_WCHTV_HTMLVIEW PRIMARY KEY CLUSTERED (HTV_N_CTT_N_ID) 
	)  
END
GO

--####################################################################################################

IF OBJECT_ID('WCHEI_HEIR') IS NULL
BEGIN
	CREATE TABLE WCHEI_HEIR(
		HEI_N_CTT_N_ID int NOT NULL,
		HEI_N_INHERITEDCTT int NOT NULL,
		CONSTRAINT PK_WCHEI_HEIR PRIMARY KEY CLUSTERED (HEI_N_CTT_N_ID) 
	)
END
GO

--####################################################################################################

IF OBJECT_ID('WCFIL_FILE') IS NULL
BEGIN
	CREATE TABLE WCFIL_FILE(
		FIL_N_ID int IDENTITY(1,1) NOT NULL,
		FIL_N_CTT_N_ID int NOT NULL,
		FIL_C_CREATOR varchar(100) NOT NULL,
		FIL_D_CREATIONDATE datetime NOT NULL,
		FIL_C_FILENAME varchar(200) NOT NULL,
		FIL_C_TITLE varchar(80) NOT NULL,
		FIL_C_DESCRIPTION varchar(200) NOT NULL,
		FIL_C_CATEGORY varchar(100) NOT NULL,
		FIL_C_FREE1 varchar(200) NOT NULL,
		FIL_C_FREE2 varchar(200) NOT NULL,
		FIL_C_FREE3 varchar(200) NOT NULL,
		CONSTRAINT PK_WCFIL_FILE PRIMARY KEY CLUSTERED (FIL_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WCFDB_FEEDBACK') IS NULL
BEGIN
	CREATE TABLE WCFDB_FEEDBACK (
		FDB_N_ID int IDENTITY(1,1) NOT NULL,
		FDB_N_CTT_N_ID int NOT NULL,
		FDB_C_SUBJECT varchar(100) NOT NULL,
		FDB_C_EMAIL varchar(200) NOT NULL,
		CONSTRAINT PK_WCFDB_FEEDBACK PRIMARY KEY CLUSTERED (FDB_N_ID) 
	) 
END
GO
--####################################################################################################

IF OBJECT_ID('WCEVE_EVENT') IS NULL
BEGIN
	CREATE TABLE WCEVE_EVENT(
		EVE_N_ID int IDENTITY(1,1) NOT NULL,
		EVE_N_CTT_N_ID int NOT NULL,
		EVE_C_TITLE nvarchar(80) NOT NULL,
		EVE_D_BEGINDATE datetime NOT NULL,
		EVE_D_ENDDATE datetime NULL,
		EVE_C_DESCRIPTION nvarchar(200) NULL,
		EVE_C_LOCAL nvarchar(50) NULL,
		EVE_C_IMAGE nvarchar(100) NULL,
		CONSTRAINT PK_WCEVE_EVENT PRIMARY KEY CLUSTERED (EVE_N_ID) 
	) 
END
GO

--####################################################################################################

IF OBJECT_ID('WCDIV_DIVIDER') IS NULL
BEGIN
	CREATE TABLE WCDIV_DIVIDER(
		DIV_N_ID int IDENTITY(1,1) NOT NULL,
		DIV_N_CTT_N_ID int NOT NULL,
		DIV_C_WIDTH varchar(10) NOT NULL,
		DIV_N_ORDER int NOT NULL,
		DIV_C_DIVNAME varchar(50) NULL,
		DIV_B_HASCONTENT bit NOT NULL,
		CONSTRAINT PK_WCDIV_DIVIDER PRIMARY KEY CLUSTERED (	DIV_N_ID ) 
	) 
END
GO

--####################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYSCOLUMNS WHERE NAME = 'DIV_C_DIVNAME' AND ID = OBJECT_ID('dbo.WCDIV_DIVIDER'))
BEGIN
	ALTER TABLE dbo.WCDIV_DIVIDER ADD
		DIV_C_DIVNAME varchar(50) NULL
END
GO

--####################################################################################################

IF OBJECT_ID('WCCLS_CLASSIFIEDS') IS NULL
BEGIN
	CREATE TABLE WCCLS_CLASSIFIEDS(
		CLS_N_ID int IDENTITY(1,1) NOT NULL,
		CLS_N_CTT_N_ID int NOT NULL,
		CLS_C_TITLE varchar(80) NOT NULL,
		CLS_C_DESCRIPTION varchar(MAX) NOT NULL,
		CLS_C_USERNAME varchar(50) NOT NULL,
		CLS_C_USEREMAIL varchar(150) NULL,
		CLS_C_USERPHONE varchar(50) NULL,
		CLS_D_PUBLISHDATE datetime NOT NULL,
		CLS_C_IMAGE varchar(200) NOT NULL,
		CLS_C_THUMBNAIL varchar(200) NOT NULL,
		CLS_C_PRICE float NOT NULL,
		CONSTRAINT PK_WCCLS_CLASSIFIEDS PRIMARY KEY CLUSTERED (CLS_N_ID) 
	) 
END
GO

--####################################################################################################
IF OBJECT_ID('WPUCP_USER_COMPLEMENT') IS NULL
BEGIN
	CREATE TABLE WPUCP_USER_COMPLEMENT(
		UCP_N_USU_N_ID int NOT NULL,
		UCP_C_PHONEHOM varchar(18) NULL,
		UCP_C_PHONEWK varchar(18) NULL,
		UCP_C_PHONEMOB varchar(18) NULL,
		UCP_C_CONTACT varchar(50) NULL,
		UCP_C_ADDRESS varchar(200) NULL,
		UCP_C_NEIGHBORHOOD varchar(50) NULL,
		UCP_C_CITY varchar(50) NULL,
		UCP_C_ZIP varchar(50) NULL,
		UCP_C_STATE varchar(2) NULL,
		UCP_C_AREA varchar(30) NULL,
		UCP_C_EXTENTION varchar(8) NULL,
		UCP_C_CPF varchar(12) NULL,
		UCP_C_CGC varchar(14) NULL,
		UCP_C_NICKNAME varchar(200) NULL,
		UCP_C_JOBTITLE varchar(300) NULL,
		UCP_B_KEYUSER bit NULL,
		UCP_C_MANAGER varchar(100) NULL,
		CONSTRAINT PK_WPUCP_USER_COMPLEMENT PRIMARY KEY CLUSTERED (UCP_N_USU_N_ID),
		CONSTRAINT FK_WPUCP_USER_COMPLEMENT_WFUSR_USER FOREIGN KEY(UCP_N_USU_N_ID) REFERENCES WFUSR_USER (USR_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################


IF NOT OBJECT_ID('Aniversariantes') IS NULL
BEGIN
	DROP VIEW [dbo].[Aniversariantes]
END
GO

CREATE VIEW [dbo].[Aniversariantes]
AS
	SELECT
		USR_N_ID,
		USR_C_FULLNAME,
		USR_D_BIRTHDATE,
		USR_C_IMAGE1,
		UCP_C_AREA,
		USR_C_EMAIL,
		DAY(USR_D_BIRTHDATE) as [DAY],
		MONTH(USR_D_BIRTHDATE) as [MONTH]
	FROM
		WFUSR_USER
		LEFT JOIN WPUCP_USER_COMPLEMENT ON UCP_N_USU_N_ID = USR_N_ID	
		INNER JOIN WFMBR_MEMBERSHIP ON USR_N_ID = MBR_N_USR_N_ID
	WHERE
		USR_D_BIRTHDATE IS NOT NULL
		AND MBR_B_ISAPPROVED = 1
GO

--####################################################################################################

IF NOT OBJECT_ID('por_ListUserVisits') IS NULL
BEGIN
	DROP PROCEDURE por_ListUserVisits
END
GO
CREATE PROCEDURE por_ListUserVisits 
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime,
	@IN_PAGEID int
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		MAX(TRK_D_TIMESTAMP) AS LASTDATE,
		TRK_C_USERNAME
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_N_PAG_N_ID = @IN_PAGEID
	GROUP BY DATEPART(y,TRK_D_TIMESTAMP),TRK_C_USERNAME
	ORDER BY MAX(TRK_D_TIMESTAMP)
END

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListTagsCommon') IS NULL
BEGIN
	DROP PROCEDURE por_ListTagsCommon
END
GO
CREATE PROCEDURE por_ListTagsCommon 
(
	@IN_COUNT int
)
AS
BEGIN
	SELECT TOP (@IN_COUNT)
		 TAG_C_NAME,
		 COUNT(TAG_C_NAME) as ITEMCOUNT
	FROM 
		WPTAG_TAGS
	GROUP BY
		TAG_C_NAME
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListTags') IS NULL
BEGIN
	DROP PROCEDURE por_ListTags
END
GO
CREATE PROCEDURE por_ListTags 
(
	@IN_TAGNAME varchar(150)
)
AS
BEGIN
	SELECT 
		DISTINCT TAG_C_NAME 
	FROM 
		WPTAG_TAGS
	WHERE
		TAG_C_NAME like @IN_TAGNAME + '%'	
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_TrackUserAccess') IS NULL
BEGIN
	DROP PROCEDURE por_TrackUserAccess
END
GO
CREATE PROCEDURE por_TrackUserAccess 
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime,
	@IN_USERID int
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		MAX(TRK_D_TIMESTAMP) AS LASTDATE
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_C_USR_N_ID = @IN_USERID AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY DATEPART(y,TRK_D_TIMESTAMP)
	ORDER BY MAX(TRK_D_TIMESTAMP)
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_TrackPortalAccess') IS NULL
BEGIN
	DROP PROCEDURE por_TrackPortalAccess
END
GO
CREATE PROCEDURE por_TrackPortalAccess 
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime,
	@IN_PORTALID int
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		MAX(TRK_D_TIMESTAMP) AS LASTDATE
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_N_POR_N_ID = @IN_PORTALID  AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY DATEPART(y,TRK_D_TIMESTAMP)
	ORDER BY MAX(TRK_D_TIMESTAMP)
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_TrackPageAccess') IS NULL
BEGIN
	DROP PROCEDURE por_TrackPageAccess
END
GO
CREATE PROCEDURE por_TrackPageAccess 
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime,
	@IN_PAGEID int
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		MAX(TRK_D_TIMESTAMP) AS LASTDATE
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_N_PAG_N_ID = @IN_PAGEID AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY DATEPART(y,TRK_D_TIMESTAMP)
	ORDER BY MAX(TRK_D_TIMESTAMP)
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_TrackAreaAccess') IS NULL
BEGIN
	DROP PROCEDURE por_TrackAreaAccess
END
GO
CREATE PROCEDURE por_TrackAreaAccess 
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime,
	@IN_AREAID int
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		MAX(TRK_D_TIMESTAMP) AS LASTDATE
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_N_ARE_N_ID = @IN_AREAID AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY DATEPART(y,TRK_D_TIMESTAMP)
	ORDER BY MAX(TRK_D_TIMESTAMP)
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WCPLC_POLL_CONTENT') IS NULL
BEGIN
	CREATE TABLE WCPLC_POLL_CONTENT(
		PLC_N_CTT_N_ID int NOT NULL,
		PLC_N_PLL_N_ID int NOT NULL,
		CONSTRAINT PK_WCPLC_POLL_CONTENT PRIMARY KEY CLUSTERED (PLC_N_CTT_N_ID),
		CONSTRAINT FK_WCPLC_POLL_CONTENT_WCPLL_POLL FOREIGN KEY(PLC_N_PLL_N_ID) REFERENCES WCPLL_POLL (PLL_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WCPLA_POLL_ANSWER') IS NULL
BEGIN
	CREATE TABLE WCPLA_POLL_ANSWER(
		PLA_N_ID int IDENTITY(1,1) NOT NULL,
		PLA_N_PLL_N_ID int NOT NULL,
		PLA_C_ANSWER varchar(200) NOT NULL,
		PLA_C_IMAGE varchar(200) NOT NULL,
		PLA_C_ALTTEXT varchar(50) NOT NULL,
		PLA_N_VOTES int NOT NULL,
		PLA_C_MESSAGE varchar(200) NOT NULL,
		CONSTRAINT PK_WCPLA_POLL_ANSWER PRIMARY KEY CLUSTERED (PLA_N_ID),
		CONSTRAINT FK_WCPLA_POLL_ANSWER_WCPLL_POLL FOREIGN KEY(PLA_N_PLL_N_ID) REFERENCES WCPLL_POLL (PLL_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListPortalAccess') IS NULL
BEGIN
	DROP PROCEDURE por_ListPortalAccess
END
GO
CREATE PROCEDURE por_ListPortalAccess
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime
)
AS
BEGIN
	SELECT COUNT(*) AS HITCOUNT,
		TRK_C_PORTALNAME,TRK_N_POR_N_ID
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY TRK_N_POR_N_ID, TRK_C_PORTALNAME
	ORDER BY HITCOUNT DESC
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListPageAccess') IS NULL
BEGIN
	DROP PROCEDURE por_ListPageAccess
END
GO
CREATE PROCEDURE por_ListPageAccess
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime
)
AS
BEGIN
	SELECT 
		COUNT(*) AS HITCOUNT,
		TRK_C_PORTALNAME + ' / ' + TRK_C_AREANAME + ' / ' + TRK_C_PAGEALIAS AS TRK_C_PAGEALIAS,
		TRK_C_PAGEALIAS AS PAGEALIAS,
		TRK_N_PAG_N_ID
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE   AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY TRK_N_PAG_N_ID, TRK_C_PAGEALIAS, TRK_C_AREANAME, TRK_C_PORTALNAME
	ORDER BY HITCOUNT DESC
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListMenuAccess') IS NULL
BEGIN
	DROP PROCEDURE por_ListMenuAccess
END
GO
CREATE PROCEDURE por_ListMenuAccess
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime
)
AS
BEGIN
	SELECT 
		COUNT(*) AS HITCOUNT,
		TRK_C_MENUPATH,
		TRK_N_MEI_N_ID
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  TRK_N_MEI_N_ID > 0 AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY TRK_N_MEI_N_ID, TRK_C_MENUPATH
	ORDER BY HITCOUNT DESC
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListAreaAccess') IS NULL
BEGIN
	DROP PROCEDURE por_ListAreaAccess
END
GO
CREATE PROCEDURE por_ListAreaAccess
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime
)
AS
BEGIN
	SELECT 
		COUNT(*) AS HITCOUNT,
		TRK_C_PORTALNAME + ' / ' + TRK_C_AREANAME AS TRK_C_AREANAME,
		TRK_N_ARE_N_ID
	FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE AND
		  (TRK_C_PORTALNAME <> 'API' OR TRK_N_POR_N_ID <> -1)
	GROUP BY TRK_N_ARE_N_ID, TRK_C_AREANAME, TRK_C_PORTALNAME
	ORDER BY HITCOUNT DESC
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_DeleteAccessInfo') IS NULL
BEGIN
	DROP PROCEDURE por_DeleteAccessInfo
END
GO
CREATE PROCEDURE por_DeleteAccessInfo
(
	@IN_STARTDATE datetime,
	@IN_ENDDATE datetime
)
AS
BEGIN
	DELETE FROM WPTRK_TRACKING
	WHERE TRK_D_TIMESTAMP >= @IN_STARTDATE AND
		  TRK_D_TIMESTAMP <= @IN_ENDDATE
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPHFT_HEADERFOOTER') IS NULL
BEGIN
	CREATE TABLE WPHFT_HEADERFOOTER(
		HFT_N_ID int IDENTITY(1,1) NOT NULL,
		HFT_N_OWNER int NOT NULL,
		HFT_C_ALIAS varchar(50) NOT NULL,
		HFT_C_EDITORS varchar(100) NOT NULL,
		HFT_N_PAG_N_ID int NOT NULL,
		CONSTRAINT PK_WPHFT_HEADERFOOTER PRIMARY KEY CLUSTERED (HFT_N_ID),
		CONSTRAINT FK_WPHFT_HEADERFOOTER_WPPOR_PORTAL FOREIGN KEY(HFT_N_OWNER) REFERENCES WPPOR_PORTAL (POR_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPARE_AREA') IS NULL
BEGIN
	CREATE TABLE WPARE_AREA(
		ARE_N_ID int IDENTITY(1,1) NOT NULL,
		ARE_C_NAME nvarchar(50) NOT NULL,
		ARE_C_ALIAS nvarchar(50) NOT NULL,
		ARE_N_POR_N_ID int NOT NULL,
		ARE_N_ADMROLE int NOT NULL,
		ARE_C_FOLDER nvarchar(50) NOT NULL,
		ARE_N_HOMEPAGE_ID int NOT NULL,
		ARE_C_READERS nvarchar(200) NOT NULL,
		ARE_N_SYSTEMAREA bit NOT NULL,
		ARE_C_TEMPLATEFILE varchar(100) NOT NULL,
		ARE_N_MEN_N_ID int NOT NULL,
		CONSTRAINT PK_TARE_AREA PRIMARY KEY CLUSTERED (	ARE_N_ID ),
		CONSTRAINT FK_TARE_AREA_TPOR_PORTAL FOREIGN KEY(ARE_N_POR_N_ID) REFERENCES WPPOR_PORTAL (POR_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPPAG_PAGE') IS NULL
BEGIN
	CREATE TABLE WPPAG_PAGE(
		PAG_N_ID int IDENTITY(1,1) NOT NULL,
		PAG_C_TITLE varchar(120) NOT NULL,
		PAG_C_ALIAS varchar(80) NOT NULL,
		PAG_N_ARE_N_ID int NOT NULL,
		PAG_N_STATUS int NOT NULL,
		PAG_C_METATAGS varchar(1000) NOT NULL,
		PAG_C_KEYWORDS varchar(1000) NOT NULL,
		PAG_C_READERS varchar(200) NOT NULL,
		PAG_C_EDITORS varchar(100) NOT NULL,
		PAG_D_CREATION datetime NOT NULL,
		PAG_C_CREATOR varchar(200) NOT NULL,
		PAG_D_LASTPUBLISH datetime NULL,
		PAG_C_LASTPUBLISHER varchar(200) NULL,
		PAG_N_PUBLISHED bit NOT NULL,
		PAG_N_LOCALONLY bit NOT NULL,
		PAG_N_SYSTEMPAGE bit NOT NULL,
		CONSTRAINT PK_WPPAG_PAGE PRIMARY KEY CLUSTERED (PAG_N_ID),
		CONSTRAINT FK_WPPAG_PAGE_WPARE_AREA FOREIGN KEY(PAG_N_ARE_N_ID) REFERENCES WPARE_AREA (ARE_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPAPG_APPROVAL_GROUPS') IS NULL
BEGIN
	CREATE TABLE WPAPG_APPROVAL_GROUPS(
		APG_N_ID int IDENTITY(1,1) NOT NULL,
		APG_N_ARE_N_ID int NOT NULL,
		APG_N_GRP_N_ID int NOT NULL,
		APG_N_QUANTITY int NOT NULL,
		APG_N_ORDER int NOT NULL,
		CONSTRAINT PK_WPAPG_APPROVAL_GROUPS PRIMARY KEY CLUSTERED (APG_N_ID),
		CONSTRAINT FK_WPAPG_APPROVAL_GROUPS_WPARE_AREA FOREIGN KEY(APG_N_ARE_N_ID) REFERENCES WPARE_AREA (ARE_N_ID) ON DELETE CASCADE,
		CONSTRAINT FK_WPAPG_APPROVAL_GROUPS_WFROL_ROLE FOREIGN KEY(APG_N_GRP_N_ID) REFERENCES WFROL_ROLE (ROL_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WFAPF_APPROVAL_FLOW') IS NULL
BEGIN
	CREATE TABLE WFAPF_APPROVAL_FLOW(
		APF_N_PAG_N_ID int NOT NULL,
		APF_N_ARE_N_ID int NOT NULL,
		APF_N_ROL_N_ID int NOT NULL,
		APF_C_ROLENAME varchar(100) NOT NULL,
		APF_N_COUNT int NOT NULL,
		APF_D_TIMESTAMP datetime NOT NULL,
		APF_C_USERNAME varchar(200) NOT NULL,
		APF_C_APPROVALINFO text NOT NULL,
		CONSTRAINT PK_WFAPF_APPROVAL_FLOW_1 PRIMARY KEY CLUSTERED (APF_N_PAG_N_ID),
		CONSTRAINT FK_WFAPF_APPROVAL_FLOW_WPPAG_PAGE FOREIGN KEY(APF_N_PAG_N_ID) REFERENCES WPPAG_PAGE (PAG_N_ID) ON DELETE CASCADE
	)  
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPCTT_CONTENT') IS NULL
BEGIN
	CREATE TABLE WPCTT_CONTENT(
		CTT_N_ID int IDENTITY(1,1) NOT NULL,
		CTT_N_MOD_N_ID int NOT NULL,
		CTT_N_PAG_N_ID int NOT NULL,
		CTT_N_PUBLISHED bit NOT NULL,
		CONSTRAINT PK_WFCNT_CONTENT PRIMARY KEY CLUSTERED (CTT_N_ID),
		CONSTRAINT FK_WPCTT_CONTENT_WPMOD_MODULE FOREIGN KEY(CTT_N_MOD_N_ID) REFERENCES WPMOD_MODULE (MOD_N_ID) ON DELETE CASCADE,
		CONSTRAINT FK_WPCTT_CONTENT_WPPAG_PAGE FOREIGN KEY(CTT_N_PAG_N_ID) REFERENCES WPPAG_PAGE (PAG_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPAPC_APPROVAL_COMMENT') IS NULL
BEGIN
	CREATE TABLE WPAPC_APPROVAL_COMMENT(
		APC_N_ID int IDENTITY(1,1) NOT NULL,
		APC_N_PAG_N_ID int NOT NULL,
		APC_D_TIMESTAMP datetime NOT NULL,
		APC_C_COMMENT varchar(1000) NOT NULL,
		APC_N_USERID int NOT NULL,
		APC_N_ACTIVE bit NOT NULL,
		CONSTRAINT PK_WPAPC_APPROVAL_COMMENT PRIMARY KEY CLUSTERED (APC_N_ID),
		CONSTRAINT FK_WPAPC_APPROVAL_COMMENT_WPPAG_PAGE FOREIGN KEY(APC_N_PAG_N_ID) REFERENCES WPPAG_PAGE (PAG_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO

GO
IF OBJECT_ID('WPSCH_PAGE_SCHEDULE') IS NULL
BEGIN
	CREATE TABLE WPSCH_PAGE_SCHEDULE(
		SCH_N_ID int IDENTITY(1,1) NOT NULL,
		SCH_N_PAGOUT_N_ID int NOT NULL,
		SCH_N_PAGIN_N_ID int NOT NULL,
		SCH_D_SCHEDULE datetime NOT NULL,
		CONSTRAINT PK_WPSCH_PAGE_SCHEDULE PRIMARY KEY CLUSTERED (SCH_N_ID),
		CONSTRAINT FK_WPSCH_PAGE_SCHEDULE_WPPAG_PAGE1 FOREIGN KEY(SCH_N_PAGIN_N_ID) REFERENCES WPPAG_PAGE (PAG_N_ID),
		CONSTRAINT FK_WPSCH_PAGE_SCHEDULE_WPPAG_PAGE2 FOREIGN KEY(SCH_N_PAGOUT_N_ID) REFERENCES WPPAG_PAGE (PAG_N_ID) ON DELETE CASCADE
	) 
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPPSH_PAGE_SEARCH') IS NULL
BEGIN
	CREATE TABLE WPPSH_PAGE_SEARCH(
		PSH_N_CTT_N_ID int NOT NULL,
		PSH_N_PAG_N_ID int NOT NULL,
		PSH_C_SEARCHTEXT text NOT NULL,
		CONSTRAINT PK_WPPSH_PAGE_SEARCH_1 PRIMARY KEY CLUSTERED (PSH_N_CTT_N_ID),
		CONSTRAINT FK_WPPSH_PAGE_SEARCH_WPCTT_CONTENT FOREIGN KEY(PSH_N_CTT_N_ID) REFERENCES WPCTT_CONTENT (CTT_N_ID) ON DELETE CASCADE
	)  
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPPCT_PUBLISHED_CONTENT') IS NULL
BEGIN
	CREATE TABLE WPPCT_PUBLISHED_CONTENT(
		PCT_N_CTT_N_ID int NOT NULL,
		PCT_N_PAG_N_ID int NOT NULL,
		PCT_C_CONTENT text NOT NULL,
		PCT_C_PAGEAREA varchar(50) NOT NULL,
		PCT_C_PARENTAREA varchar(50) NOT NULL,
		PCT_N_ORDER int NOT NULL,
		PCT_C_METAVALUES text NOT NULL,
		PCT_C_READERS varchar(200) NOT NULL,
		PCT_D_STARTDATE datetime NULL,
		PCT_D_ENDDATE datetime NULL,
		PCT_C_INDEX varchar(1000) NULL,
		CONSTRAINT PK_WPACT_APPROVED_CONTENT PRIMARY KEY CLUSTERED (PCT_N_CTT_N_ID),
		CONSTRAINT FK_WPACT_APPROVED_CONTENT_WPCTT_CONTENT FOREIGN KEY(PCT_N_CTT_N_ID) REFERENCES WPCTT_CONTENT (CTT_N_ID) ON DELETE CASCADE
	)  
END
GO

--####################################################################################################

GO
IF OBJECT_ID('WPCCF_CONTENT_CONFIG') IS NULL
BEGIN
	CREATE TABLE WPCCF_CONTENT_CONFIG(
		CCF_N_CTT_N_ID int NOT NULL,
		CCF_N_CNT_N_ID int NOT NULL,
		CCF_C_PAGEAREA varchar(50) NOT NULL,
		CCF_C_PARENTAREA varchar(50) NOT NULL,
		CCF_N_ORDER int NOT NULL,
		CCF_C_TITLE varchar(100) NOT NULL,
		CCF_C_READERS varchar(200) NOT NULL,
		CCF_C_EDITORS varchar(100) NOT NULL,
		CCF_C_BORDERCOLOR varchar(7) NOT NULL,
		CCF_C_BGCOLOR varchar(7) NOT NULL,
		CCF_C_STARTDATE datetime NULL,
		CCF_C_ENDDATE datetime NULL,
		CCF_N_BYPASSAPPROVAL bit NOT NULL,
		CCF_N_CHANGED bit NOT NULL,
		CCF_N_LOCALONLY bit NOT NULL,
		CCF_N_DELETENEXTPUBLISH bit NOT NULL,
		CCF_N_SHOWINPRINTMODE bit NOT NULL,
		CCF_C_HEIGHT varchar(10) NOT NULL,
		CCF_C_WIDTH varchar(10) NOT NULL,
		CCF_N_COLLAPSED bit NOT NULL,
		CCF_C_METAVALUES text NOT NULL,
		CCF_C_INDEX varchar(1000) NULL,
		CCF_C_CONTENT_METADATA varchar(max) null,
		CONSTRAINT PK_WFCCF_CONTENT_CONFIG PRIMARY KEY CLUSTERED (CCF_N_CTT_N_ID),
		CONSTRAINT FK_WPCCF_CONTENT_CONFIG_WPCNT_CONTAINER FOREIGN KEY(CCF_N_CNT_N_ID) REFERENCES WPCNT_CONTAINER (CNT_N_ID),
		CONSTRAINT FK_WPCCF_CONTENT_CONFIG_WPCTT_CONTENT FOREIGN KEY(CCF_N_CTT_N_ID) REFERENCES WPCTT_CONTENT (CTT_N_ID) ON DELETE CASCADE
	)  
END
GO

IF NOT EXISTS (SELECT 1 FROM SYSCOLUMNS WHERE NAME = 'CCF_C_CONTENT_METADATA' AND ID = OBJECT_ID('WPCCF_CONTENT_CONFIG'))
BEGIN
	ALTER TABLE WPCCF_CONTENT_CONFIG ADD CCF_C_CONTENT_METADATA VARCHAR(max) NULL
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_ListLastPublished') IS NULL
BEGIN
	DROP PROCEDURE por_ListLastPublished
END
GO
CREATE PROCEDURE por_ListLastPublished
(
	@IN_PUBLISHERNAME varchar(200) = null,
	@IN_AREAID int = 0
)
AS
BEGIN
	IF @IN_PUBLISHERNAME is null and @IN_AREAID = 0
		BEGIN
		 SELECT DISTINCT TOP 200 
			PAG_N_ID,
			PAG_C_TITLE,
			ARE_N_ID,
			ARE_C_NAME, 
			PAG_C_READERS,
			ARE_C_READERS,
			POR_C_READERS,
			PAG_D_LASTPUBLISH,
			PAG_C_LASTPUBLISHER,
			APC_D_TIMESTAMP, 
			APC_C_COMMENT
		 FROM WPPAG_PAGE 
		 INNER JOIN WPARE_AREA ON ARE_N_ID = PAG_N_ARE_N_ID
		 INNER JOIN WPPOR_PORTAL  ON POR_N_ID = ARE_N_POR_N_ID 
		 LEFT JOIN WPAPC_APPROVAL_COMMENT ON APC_N_PAG_N_ID = PAG_N_ID AND APC_N_ACTIVE = 1
		 WHERE 
			PAG_N_ID not in (select HFT_N_PAG_N_ID from WPHFT_HEADERFOOTER) AND
			PAG_N_PUBLISHED = 1
		 ORDER BY PAG_D_LASTPUBLISH DESC
		END
	ELSE
	IF @IN_PUBLISHERNAME is null 
		BEGIN
		 SELECT DISTINCT TOP 200 
			PAG_N_ID,
			PAG_C_TITLE,
			ARE_N_ID,
			ARE_C_NAME, 
			PAG_C_READERS,
			ARE_C_READERS,
			POR_C_READERS,
			PAG_D_LASTPUBLISH,
			PAG_C_LASTPUBLISHER,
			APC_D_TIMESTAMP, 
			APC_C_COMMENT
		 FROM WPPAG_PAGE
		 INNER JOIN WPARE_AREA ON ARE_N_ID = PAG_N_ARE_N_ID
		 INNER JOIN WPPOR_PORTAL  ON POR_N_ID = ARE_N_POR_N_ID 
		 LEFT JOIN WPAPC_APPROVAL_COMMENT ON APC_N_PAG_N_ID = PAG_N_ID AND APC_N_ACTIVE = 1
		 WHERE 
			ARE_N_ID = @IN_AREAID AND
			PAG_N_ID not in (select HFT_N_PAG_N_ID from WPHFT_HEADERFOOTER) AND
			PAG_N_PUBLISHED = 1
		 ORDER BY PAG_D_LASTPUBLISH DESC
		END
	ELSE
		BEGIN
		 SELECT DISTINCT TOP 200 
			PAG_N_ID,
			PAG_C_TITLE,
			ARE_N_ID,
			ARE_C_NAME, 
			PAG_C_READERS,
			ARE_C_READERS,
			POR_C_READERS,
			PAG_D_LASTPUBLISH,
			PAG_C_LASTPUBLISHER,
			APC_D_TIMESTAMP, 
			APC_C_COMMENT
		 FROM WPPAG_PAGE
		 INNER JOIN WPARE_AREA ON ARE_N_ID = PAG_N_ARE_N_ID
		 INNER JOIN WPPOR_PORTAL  ON POR_N_ID = ARE_N_POR_N_ID 
		 LEFT JOIN WPAPC_APPROVAL_COMMENT ON APC_N_PAG_N_ID = PAG_N_ID AND APC_N_ACTIVE = 1
		 WHERE 
			PAG_C_LASTPUBLISHER = @IN_PUBLISHERNAME AND
			PAG_N_ID not in (select HFT_N_PAG_N_ID from WPHFT_HEADERFOOTER) AND
			PAG_N_PUBLISHED = 1
		 ORDER BY PAG_D_LASTPUBLISH DESC
		END
	END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_SimpleSearchPage') IS NULL
BEGIN
	DROP PROCEDURE por_SimpleSearchPage
END
GO
CREATE PROCEDURE por_SimpleSearchPage
	  @IN_PAGES		varchar(1500),
	  @SearchPattern varchar(200)
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SEPARATOR_POSITION int
	DECLARE @ARRAY_ITEM nvarchar(80)
	DECLARE @IDSTABLE Table (PAGNUM int)
	SET @IN_PAGES = @IN_PAGES + ','
	WHILE patindex('%,%' , @IN_PAGES) <> 0 
	BEGIN
		SELECT @SEPARATOR_POSITION =  patindex('%,%' , @IN_PAGES)
		SELECT @ARRAY_ITEM = left(@IN_PAGES, @SEPARATOR_POSITION - 1)
		SELECT @IN_PAGES = stuff(@IN_PAGES, 1, @SEPARATOR_POSITION, '')
		INSERT INTO @IDSTABLE SELECT @ARRAY_ITEM
	END
	DECLARE @TMPTABLE Table (PAGNUM int)
	SET @SearchPattern = @SearchPattern + ','
	WHILE patindex('%,%' , @SearchPattern) <> 0 
	BEGIN
		SELECT @SEPARATOR_POSITION =  patindex('%,%' , @SearchPattern)
		SELECT @ARRAY_ITEM = left(@SearchPattern, @SEPARATOR_POSITION - 1)
		SELECT @SearchPattern = stuff(@SearchPattern, 1, @SEPARATOR_POSITION, '')
		print @ARRAY_ITEM
		INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID
			FROM WPPCT_PUBLISHED_CONTENT, WPPAG_PAGE WHERE 
			(
			PAG_C_KEYWORDS LIKE '%' + @ARRAY_ITEM + '%' OR
			PAG_C_TITLE LIKE '%' + @ARRAY_ITEM + '%' OR
			PAG_C_METATAGS LIKE '%' + @ARRAY_ITEM + '%' OR
			PCT_C_CONTENT LIKE '%' + @ARRAY_ITEM + '%' 
			)
			AND 
			PAG_N_ID = PCT_N_PAG_N_ID AND 
			PAG_N_PUBLISHED = 1 AND 
			PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable) AND
			PAG_N_ID IN (SELECT PAGNUM FROM @IDSTABLE)
	END
	SELECT PAGNUM FROM @TMPTABLE
END
GO

--####################################################################################################

GO
IF NOT OBJECT_ID('por_SearchPage') IS NULL
BEGIN
	DROP PROCEDURE por_SearchPage
END
GO
CREATE PROCEDURE por_SearchPage
	  @SearchPattern varchar(150),
	  @AreaId int = 0
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE @SEPARATOR_POSITION int
	DECLARE @ARRAY_ITEM nvarchar(80)
	DECLARE @TMPTABLE Table (PAGNUM int,RANKING int)
	SET @SearchPattern = @SearchPattern + ','
		WHILE patindex('%,%' , @SearchPattern) <> 0 
	BEGIN
	  
	  SELECT @SEPARATOR_POSITION =  patindex('%,%' , @SearchPattern)
	  SELECT @ARRAY_ITEM = left(@SearchPattern, @SEPARATOR_POSITION - 1)
	  SELECT @SearchPattern = stuff(@SearchPattern, 1, @SEPARATOR_POSITION, '')
	  
	  
	  IF @AreaId = 0
		BEGIN
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 3 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_KEYWORDS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,3
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_KEYWORDS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)
		  
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 5 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_TITLE LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,5
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_TITLE LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)

		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 3 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_METATAGS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,3
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_METATAGS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)
			  
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 1 WHERE PAGNUM IN 
			  (SELECT PCT_N_PAG_N_ID FROM WPPCT_PUBLISHED_CONTENT,WPPAG_PAGE WHERE 
			  PAG_N_ID = PCT_N_PAG_N_ID AND 
			  PCT_C_CONTENT LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PCT_N_PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PCT_N_PAG_N_ID,1 
			  FROM WPPCT_PUBLISHED_CONTENT,WPPAG_PAGE WHERE 
			  PAG_N_ID = PCT_N_PAG_N_ID AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PCT_C_CONTENT LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PCT_N_PAG_N_ID NOT IN (SELECT PAGNUM FROM @TMPTABLE)
		END
	  ELSE
		BEGIN
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 3 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_KEYWORDS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,3
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_KEYWORDS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)
		  
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 5 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_TITLE LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,5
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_TITLE LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)

		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 3 WHERE PAGNUM IN
			 (SELECT PAG_N_ID FROM WPPAG_PAGE WHERE 
			  PAG_C_METATAGS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PAG_N_ID,3
			  FROM WPPAG_PAGE WHERE 
			  PAG_C_METATAGS LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ID NOT IN (SELECT PAGNUM FROM @tmpTable)
			  
		  
		  UPDATE @TMPTABLE SET RANKING = RANKING + 1 WHERE PAGNUM IN 
			  (SELECT PCT_N_PAG_N_ID FROM WPPCT_PUBLISHED_CONTENT, WPPAG_PAGE WHERE 
			  PCT_N_PAG_N_ID = PAG_N_ID AND
			  PCT_C_CONTENT LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PCT_N_PAG_N_ID IN (SELECT PAGNUM FROM @TMPTABLE))
		  INSERT INTO @TMPTABLE SELECT DISTINCT PCT_N_PAG_N_ID,1 
			  FROM WPPCT_PUBLISHED_CONTENT,WPPAG_PAGE WHERE 
			  PAG_N_ID = PCT_N_PAG_N_ID AND 
			  PAG_N_PUBLISHED = 1 AND 
			  PAG_N_ARE_N_ID = @AreaId AND
			  PCT_C_CONTENT LIKE '%' + @ARRAY_ITEM + '%' AND 
			  PCT_N_PAG_N_ID NOT IN (SELECT PAGNUM FROM @TMPTABLE)
		END
	END
	SELECT RANKING, PAG_C_TITLE, PAG_C_KEYWORDS, PAG_C_METATAGS, PAG_C_READERS, PAG_C_ALIAS, PAG_N_ID, PAG_N_ARE_N_ID
			FROM WPPAG_PAGE,@TMPTABLE
			WHERE PAGNUM = PAG_N_ID
			ORDER BY RANKING DESC
END
GO

--####################################################################################################

IF OBJECT_ID('FK_WFOWN_OWNER_TPOR_PORTAL') IS NULL
BEGIN
	ALTER TABLE WFOWN_OWNER  WITH CHECK ADD CONSTRAINT FK_WFOWN_OWNER_TPOR_PORTAL FOREIGN KEY(OWN_N_ID)
		REFERENCES WPPOR_PORTAL (POR_N_ID)
		ON DELETE CASCADE
END
GO

--####################################################################################################

IF OBJECT_ID('WCCLI_CLASSIFIEDIMAGE') IS NULL
BEGIN
CREATE TABLE WCCLI_CLASSIFIEDIMAGE(
	CLI_N_ID int IDENTITY(1,1) NOT NULL,
	CLI_CLS_N_ID int NOT NULL,
	CLI_C_IMAGE varchar(200) NOT NULL,
	CLI_N_ORDER int NOT NULL,
	CONSTRAINT PK_WCCLI_CLASSIFIEDIMAGE PRIMARY KEY CLUSTERED (CLI_N_ID),
	CONSTRAINT FK_WCCLI_CLASSIFIEDIMAGE_WCCLS_CLASSIFIEDS FOREIGN KEY(CLI_CLS_N_ID) REFERENCES WCCLS_CLASSIFIEDS (CLS_N_ID) ON DELETE CASCADE
) 
END
GO

--####################################################################################################
--EXCLUI CONTAINERS DUPLICADOS, MANTENDO APENAS A VERSÃO QUE FOI CADASTRADA PRIMEIRO. ATUALIZA
--AS REFERÊNCIAS AOS OUTROS REGISTROS DO CONTAINER PARA USAR A VERSÃO QUE VAI FICAR.

DECLARE @CNT TABLE(ID INT IDENTITY, CNT_ID INT, ORIG INT)
DECLARE @DUPS TABLE (F VARCHAR(100), ORIG INT)

--ACHA OS CONTAINERS QUE ESTÃO DUPLICADOS
INSERT @DUPS
SELECT CNT_C_FILENAME, MIN(CNT_N_ID) ID
FROM WPCNT_CONTAINER 
GROUP BY CNT_C_FILENAME
HAVING COUNT(*) > 1

--ACHA OS CONTAINERS QUE SERÃO APAGADOS E DEFINE QUAL CONTAINER VAI FICAR NO LUGAR
INSERT @CNT
SELECT CNT_N_ID, ORIG
FROM WPCNT_CONTAINER C
INNER JOIN @DUPS D ON C.CNT_C_FILENAME = D.F AND CNT_N_ID <> D.ORIG 

DECLARE @MAX INT, @I INT, @OLD INT, @NEW INT, @TOT INT
SELECT @MAX = MAX(ID), @I = MIN(ID), @TOT = COUNT(*) FROM @CNT

--ATUALIZA OS CONTEÚDOS PARA USAR OS CONTAINERS QUE FICAM E APAGA OS CONTAINERS DUPLICADOS
WHILE @TOT > 0 AND @I <= @MAX
BEGIN
	SELECT @OLD = CNT_ID, @NEW = ORIG FROM @CNT WHERE ID = @I
	UPDATE WPCCF_CONTENT_CONFIG SET CCF_N_CNT_N_ID = @NEW WHERE CCF_N_CNT_N_ID = @OLD
	DELETE WPCNT_CONTAINER WHERE CNT_N_ID = @OLD 
	SET @I = @I + 1
END
GO

--####################################################################################################

--ITEM DE MENU DE CONFIGURAÇÃO DE TEMA
IF EXISTS(SELECT 1 FROM WFMEN_MENU WHERE UPPER(MEN_C_ALIAS) ='ADMIN') AND NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_C_NAMEKEY = 'theme')
BEGIN
	DECLARE @ADMID INT
	SELECT @ADMID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'
	INSERT WFMEI_MENUITEM VALUES (1,'-4;-3;-1;-7;','Tema', '/WFAdmin/Pages/ThemeSettings.aspx', '_self', '002005', 0,0,'','','pt-BR','theme',null)
END

--CRIAÇÃO DE MENU DE LINKS RÁPIDOS NA ÁREA ADMINISTRATIVA
IF EXISTS (SELECT 1 FROM WFOWN_OWNER WHERE OWN_N_ID = -1)
BEGIN
	declare @qlink int
	select @qlink = men_n_id from WFMEN_MENU where MEN_C_ALIAS = 'admqlinks'
	IF @qlink IS NULL 
	BEGIN
		INSERT WFMEN_MENU VALUES (-1, 'admqlinks', '-1;', '-4;-3;-1;-7;', 'p-BR', NULL, 1)
		SET @qlink = @@IDENTITY 
		insert WFMEI_MENUITEM values (@qlink ,'-4;-3;-1;-7;','Gerenciamento de Páginas', '/WFAdmin/Pages/Pages.aspx', '_self', '002', 0,0,'','','pt-BR','management',null)
	END
END
--####################################################################################################
-- CREATE INDEX ON WFADL_AUDITLOG
IF NOT EXISTS(SELECT 1 FROM SYS.INDEXES WHERE NAME='IX_LOGAUDIT_TIMESTAMP' AND OBJECT_ID = OBJECT_ID('WFADL_AUDITLOG'))
	CREATE INDEX IX_LOGAUDIT_TIMESTAMP ON WFADL_AUDITLOG(ADL_D_TIMESTAMP)

IF NOT EXISTS(SELECT 1 FROM SYS.INDEXES WHERE NAME='IX_LOGAUDIT_CATEGORY' AND OBJECT_ID = OBJECT_ID('WFADL_AUDITLOG'))
	CREATE INDEX IX_LOGAUDIT_CATEGORY ON WFADL_AUDITLOG(ADL_C_CATEGORY)

--####################################################################################################

GO
--AJUSTE NO MENU ADMINISTRATIVO
IF EXISTS(SELECT MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin')
BEGIN
	DECLARE @ADMID INT
	SELECT @ADMID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'
	-- AJUSTE NO MENU DE CONFIGURACOES
	DECLARE @EXISTINGHIER VARCHAR(6)
	DECLARE @NEWHIER VARCHAR(3)
	SELECT @NEWHIER = LEFT(MEI_C_HIERARCHY,3), @EXISTINGHIER = MEI_C_HIERARCHY FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Management/Configuration.aspx' AND MEI_N_MEN_N_ID = @ADMID
	IF @NEWHIER <> @EXISTINGHIER
	BEGIN
		DELETE FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_HIERARCHY = @NEWHIER
		UPDATE WFMEI_MENUITEM SET MEI_C_HIERARCHY = @NEWHIER, MEI_C_NAME = UPPER(MEI_C_NAME) WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_HIERARCHY = @EXISTINGHIER
	END
	-- LOG DE AUDITORIA
	IF NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_C_NAMEKEY = 'logAudit')
	BEGIN
		DECLARE @LOGHIER VARCHAR(6)
		DECLARE @LOGAUDITHIER VARCHAR(6)
		DECLARE @LOGAUDITHIERNXT VARCHAR(6)
		SELECT @LOGHIER = MEI_C_HIERARCHY FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Reports/Logs.aspx' AND MEI_N_MEN_N_ID = @ADMID
		DECLARE @HINUM INT = CAST(RIGHT(@LOGHIER,3) AS INT)
		SET @LOGAUDITHIER = LEFT(@LOGHIER,3) + (SELECT RIGHT('000' + CONVERT(VARCHAR(3), (@HINUM + 1)), 3))
		SET @LOGAUDITHIERNXT = LEFT(@LOGHIER,3) + (SELECT RIGHT('000' + CONVERT(VARCHAR(3), (@HINUM + 2)), 3))

		UPDATE WFMEI_MENUITEM SET MEI_C_HIERARCHY = @LOGAUDITHIERNXT + SUBSTRING(MEI_C_HIERARCHY,7,6) WHERE LEFT(MEI_C_HIERARCHY,6) = @LOGAUDITHIER AND  MEI_N_MEN_N_ID = @ADMID

		INSERT WFMEI_MENUITEM VALUES(@ADMID,'-1','Logs Auditoria', '/WFAdmin/Reports/LogsAudit.aspx', '_self', @LOGAUDITHIER, 0,0,'','','pt-BR','logAudit',null)
	END
END
GO

DELETE FROM WPMOD_MODULE WHERE MOD_C_GUID IN (
	'965B4EAF-265D-408E-A91C-2A018006F41E', --PAGINAS PENDENTES
	'95DB7581-4BC1-4155-8A5A-274E6705A71A', --ACESSO DINÂMICO
	'2E0733DE-F8A9-4891-9D0B-A9C2D633C7FD', --SELETOR DE INDICE
	'E0CE9644-CE82-4E39-8122-BDEB1B0332AC'  --BUSCA
)	AND MOD_N_ID NOT IN (SELECT DISTINCT CTT_N_MOD_N_ID FROM WPCTT_CONTENT)
GO

UPDATE WPMOD_MODULE SET MOD_C_COMPONENT = 'Discontinued.ascx', MOD_C_NAME = MOD_C_NAME + ' (descontinuado)' WHERE MOD_C_COMPONENT <> 'Discontinued.ascx' AND MOD_C_GUID IN (
	'965B4EAF-265D-408E-A91C-2A018006F41E', --PAGINAS PENDENTES
	'95DB7581-4BC1-4155-8A5A-274E6705A71A', --ACESSO DINÂMICO
	'2E0733DE-F8A9-4891-9D0B-A9C2D633C7FD', --SELETOR DE INDICE
	'E0CE9644-CE82-4E39-8122-BDEB1B0332AC'  --BUSCA
)	
GO

UPDATE	WPMOD_MODULE SET MOD_C_NAME = 'Arquivos'
WHERE	MOD_C_GUID =	'59889CA0-02AA-404a-9B3C-626FB8811F91' --ARQUIVOS VISTA
		AND MOD_C_NAME = 'Arquivos Vista'
GO

-- CENTRAL DE NOTICIAS
--####################################################################################################################
IF OBJECT_ID('CNEDT_EDITORIA') IS NULL
BEGIN
    CREATE TABLE dbo.CNEDT_EDITORIA (
       EDT_N_ID             INT IDENTITY (1, 1) NOT NULL,
       EDT_C_NOME           NVARCHAR(200)       NOT NULL,
       EDT_C_READERS        NVARCHAR(200)       NOT NULL,
       EDT_C_EDITORS        NVARCHAR(200)       NOT NULL,
       CONSTRAINT PK_CNEDT_EDITORIA PRIMARY KEY (EDT_N_ID)
    )
END
GO

--####################################################################################################################
IF OBJECT_ID('CNNOT_NOTICIA') IS NULL
BEGIN
    CREATE TABLE dbo.CNNOT_NOTICIA (
       NOT_N_ID             INT IDENTITY (1, 1) NOT NULL,
       NOT_C_TITULO         VARCHAR (300)       NOT NULL,
       NOT_C_SUBTITULO      VARCHAR (300)       NOT NULL,
       NOT_D_CRIACAO        DATETIME            NOT NULL,
       NOT_N_CRIADOR        INT                 NOT NULL,
       NOT_D_INICIO         DATETIME            NULL,
       NOT_D_FINAL          DATETIME            NULL,
       NOT_C_IMG_BANNER     VARCHAR (300)       NULL,
       NOT_C_OLHO_NOTICIA   VARCHAR (1000)      NOT NULL,
       NOT_C_IMG_OLHO       VARCHAR (300)       NULL,
       NOT_C_FONTE          VARCHAR (100)       NOT NULL,
       NOT_N_DESTAQUE       BIT                 NOT NULL,
       NOT_C_CONTEUDO       TEXT                NOT NULL,
       NOT_C_READERS        VARCHAR (200)       NOT NULL,
       NOT_N_PAGEID         INT                 NOT NULL,
       NOT_C_INDEX          VARCHAR (1000)      NULL,
       CONSTRAINT PK_CNNOT_NOTICIA PRIMARY KEY (NOT_N_ID)
    )
END
GO

--####################################################################################################################
IF OBJECT_ID('CNNED_NOTICIA_EDITORIA') IS NULL
BEGIN
    CREATE TABLE dbo.CNNED_NOTICIA_EDITORIA (
       NED_N_ID             INT IDENTITY (1, 1) NOT NULL,
       NED_N_NOT_N_ID       INT                 NOT NULL,
       NED_N_EDT_N_ID       INT                 NOT NULL,
       CONSTRAINT PK_CNNED_NOTICIA_EDITORIA PRIMARY KEY (NED_N_ID),
       CONSTRAINT FK_CNNED_NOTICIA_EDITORIA_CNEDT_EDITORIA FOREIGN KEY (NED_N_EDT_N_ID) REFERENCES CNEDT_EDITORIA (EDT_N_ID) ON DELETE CASCADE,
       CONSTRAINT FK_CNNED_NOTICIA_EDITORIA_CNNOT_NOTICIA FOREIGN KEY (NED_N_NOT_N_ID) REFERENCES CNNOT_NOTICIA (NOT_N_ID) ON DELETE CASCADE
    )
END
GO

--####################################################################################################################
--VIEW UTILIZADA PARA BUSCAR E EXIBIR LISTAS DE NOTICIAS NA ÁREA PUBLICA
--NÃO É UTILIZADA PARA EXIBIR DETALHES.

IF NOT OBJECT_ID('CNNST_NOTICIA') IS NULL
BEGIN
	DROP VIEW dbo.CNNST_NOTICIA
END
GO

CREATE VIEW dbo.CNNST_NOTICIA
AS
	--VIEW UTILIZADA PARA LISTAR E BUSCAR NOTICIAS NA ÁREA PÚBLICA
	--NÃO RETORNA DETALHES DAS NOTICIAS
	SELECT	NOT_N_ID,
			NOT_C_TITULO,
			NOT_C_SUBTITULO,
			NOT_C_OLHO_NOTICIA,
			NOT_D_CRIACAO,
			NOT_C_IMG_OLHO,
			NOT_C_FONTE,
			NOT_N_CRIADOR,
			NOT_N_PAGEID,
			NOT_C_READERS,
			NOT_C_IMG_BANNER,
			NOT_N_DESTAQUE,
			NOT_D_INICIO,
			NOT_D_FINAL,
			NOT_C_INDEX,
			ISNULL((SELECT ',' + CAST(NED_N_EDT_N_ID AS VARCHAR(8))
					FROM CNNED_NOTICIA_EDITORIA
					WHERE NED_N_NOT_N_ID = NOT_N_ID
					FOR XML PATH('')),'') + ',' NST_C_EDITORIAS
	FROM	CNNOT_NOTICIA
GO

update WFMEI_MENUITEM
set MEI_C_NAME = 'CONTEÚDO'
WHERE MEI_C_NAME = 'CONTEUDO'
GO

update WFMEI_MENUITEM
set MEI_C_NAMEKEY = 'content'
where (MEI_C_NAMEKEY = '' or mei_c_namekey is null)
and MEI_C_NAME IN ('CONTENT', 'CONTEÚDO', 'CONTENIDO')
GO

--Criação do ítem de menu da área admnistrativa
--####################################################################################################################
DECLARE @MEI_C_NAMEKEY VARCHAR(50)
SET @MEI_C_NAMEKEY = 'newscentral'
IF EXISTS(SELECT 1FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin') AND NOT EXISTS(SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_C_NAMEKEY = @MEI_C_NAMEKEY)
BEGIN
	DECLARE @MENUID INT
	DECLARE @READERS VARCHAR(200)
	DECLARE @PARENT VARCHAR(90)
	DECLARE @HIERARQUIA VARCHAR(90)

	--obtem o id do menu da area administrativa
	SELECT @MENUID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'

	--obtem o id do submenu Conteúdo e o seu código de hierarquia
	SELECT	top 1 @READERS = MEI_C_READERS,
			@PARENT = MEI_C_HIERARCHY
	FROM	WFMEI_MENUITEM 
	WHERE	mei_n_men_n_id = 1 and MEI_C_NAMEKEY = 'content' or (MEI_C_NAME = 'conteúdo')

	--gera o próximo código de hierarquia dentro do menu selecionado
	SELECT	top 1 @HIERARQUIA = RIGHT('000' + CONVERT(VARCHAR(6), CAST(LEFT(MEI_C_HIERARCHY, 6) AS INT) + 1), 6)
	FROM	WFMEI_MENUITEM
	WHERE	LEN(MEI_C_HIERARCHY) > 3 AND  LEFT(MEI_C_HIERARCHY, 3) = @PARENT
	ORDER BY MEI_C_HIERARCHY desc

	--insere o ítem de menu para o admin
	INSERT INTO WFMEI_MENUITEM 
		(MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY,
		 MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY)
	VALUES 
		(@MENUID,  @READERS,  'Central de Noticias',  '#',  '_self', @HIERARQUIA, 0,
		 0,  '',  '',  'pt-BR',  @MEI_C_NAMEKEY)

	INSERT INTO WFMEI_MENUITEM 
		(MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY,
		 MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY)
	VALUES 
		(@MENUID,  @READERS,  'Editorias',  '/WFAdmin/Modules/CentralNoticias/Editoria.aspx',  '_self', @HIERARQUIA + '001', 0,
		 0,  '',  '',  'pt-BR',  'newstarget')

	INSERT INTO WFMEI_MENUITEM 
		(MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY,
		 MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY)
	VALUES 
		(@MENUID,  @READERS,  'Notícias',  '/WFAdmin/Modules/CentralNoticias/Noticia.aspx',  '_self', @HIERARQUIA + '002', 0,
		 0,  '',  '',  'pt-BR',  'news')

    --insere a tradução para inglês do ítem de menu
	INSERT INTO WFMET_MENUTRANSLATION (MET_C_LANGUAGE, MET_C_NAMEKEY, MET_C_MESSAGE)
	VALUES ('en-US', @MEI_C_NAMEKEY, 'News Central')

	INSERT INTO WFMET_MENUTRANSLATION (MET_C_LANGUAGE, MET_C_NAMEKEY, MET_C_MESSAGE)
	VALUES ('en-US', 'newstarget', 'Editory')

	INSERT INTO WFMET_MENUTRANSLATION (MET_C_LANGUAGE, MET_C_NAMEKEY, MET_C_MESSAGE)
	VALUES ('en-US', 'news', 'News')
END
GO

-- GALERIA
--####################################################################################################################

IF OBJECT_ID('GLGAL_GALLERY') IS NULL 
BEGIN
    CREATE TABLE dbo.GLGAL_GALLERY(
	    GAL_N_ID int IDENTITY(1,1) NOT NULL,
	    GAL_C_DESCRIPTION varchar(200) NOT NULL,
	    GAL_N_ARE_N_ID int NOT NULL,
	    GAL_C_PATH varchar(200) NULL,
	    CONSTRAINT PK_GLGAL_GALERIA PRIMARY KEY (GAL_N_ID)
    )
END
GO

IF OBJECT_ID('GLITM_GALLERY_ITEM') IS NULL 
BEGIN
CREATE TABLE dbo.GLITM_GALLERY_ITEM(
	ITM_N_ID int IDENTITY(1,1) NOT NULL,
	ITM_N_GAL_N_ID int NOT NULL,
	ITM_C_DESCRIPTION varchar(200) NOT NULL,
	ITM_C_FILENAME varchar(200) NOT NULL,
	ITM_C_TITLE varchar(100) NULL,
	ITM_N_ORDER int NULL,
	CONSTRAINT PK_GLIMG_IMAGEM PRIMARY KEY (ITM_N_ID),
    CONSTRAINT FK_GLIMG_IMAGE_GLGAL_GALLERY FOREIGN KEY(ITM_N_GAL_N_ID) REFERENCES dbo.GLGAL_GALLERY (GAL_N_ID) ON DELETE CASCADE
)
END
GO

--####################################################################################################################
--migração dos módulos de contato e agenda para o novo lista de usuários

IF NOT OBJECT_ID('WCCNT_CONTACT') IS NULL
BEGIN 
	INSERT WCPBK_PHONEBOOK (PBK_N_CTT_N_ID, PBK_C_NAME, PBK_C_AREA, PBK_C_PHONERES, PBK_C_PHONEBUS, PBK_C_MOBILE, PBK_C_EMAIL, PBK_C_JOBTITLE, PBK_C_CATEGORY, PBK_C_FREE1, PBK_C_FREE2)
	SELECT CNT_N_CTT_N_ID, CNT_C_NAME, CNT_C_AREA, CNT_C_PHONEHOM, CNT_C_PHONEWK, CNT_C_PHONEMOB, CNT_C_EMAIL, CNT_C_JOBTITLE, CNT_C_DESCRIPTION, CNT_C_FREE1, CNT_C_FREE2
	FROM WCCNT_CONTACT 

	DROP TABLE WCCNT_CONTACT
END
GO

UPDATE WPMOD_MODULE SET MOD_N_INTERACTIVE = 1 WHERE MOD_C_GUID = '26A0A56A-BAE6-45D2-A1F1-BD160B67010B'
GO
--atualiza o módulo para o novo ascx
UPDATE WPMOD_MODULE SET MOD_C_COMPONENT = 'UserBook/UserBook.ascx' WHERE MOD_C_GUID = '7C44DDE3-8893-436f-BBBF-1F88307174CD'

--muda os módulos contato e agenda em uso para o novo lista de usuários
DECLARE @ID INT
SELECT @ID = MOD_N_ID FROM WPMOD_MODULE WHERE MOD_C_GUID = '7C44DDE3-8893-436F-BBBF-1F88307174CD'

UPDATE C
SET C.CTT_N_MOD_N_ID = @ID
FROM WPCTT_CONTENT C
INNER JOIN WPMOD_MODULE ON CTT_N_MOD_N_ID = MOD_N_ID 
WHERE MOD_C_GUID IN ('F1C95B3F-DA8A-4206-8221-80D5B532C60F', '5181AC0A-4654-4D0A-9D78-5F94A161F767')

--APAGA OS MÓDULOS CONTATO E AGENDA
DELETE WPMOD_MODULE WHERE MOD_C_GUID IN ('F1C95B3F-DA8A-4206-8221-80D5B532C60F', '5181AC0A-4654-4D0A-9D78-5F94A161F767')

--Criação do ítem de menu da galeria na área administrativa
--####################################################################################################################
DECLARE @MEI_C_NAMEKEY VARCHAR(50)
SET @MEI_C_NAMEKEY = 'gallery'
IF EXISTS(SELECT 1 FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin') AND NOT EXISTS(SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_C_NAMEKEY = @MEI_C_NAMEKEY)
BEGIN
	DECLARE @MENUID INT
	DECLARE @READERS VARCHAR(200)
	DECLARE @PARENT VARCHAR(90)
	DECLARE @HIERARQUIA VARCHAR(90)

	--obtem o id do menu da area administrativa
	SELECT @MENUID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'

	--obtem o id do submenu Conteúdo e o seu código de hierarquia
	SELECT	top 1 @READERS = MEI_C_READERS,
			@PARENT = MEI_C_HIERARCHY
	FROM	WFMEI_MENUITEM 
	WHERE	mei_n_men_n_id = 1 and MEI_C_NAMEKEY = 'content' or (MEI_C_NAME = 'conteúdo')

	--gera o próximo código de hierarquia dentro do menu selecionado
	SELECT	top 1 @HIERARQUIA = RIGHT('000' + CONVERT(VARCHAR(6), CAST(LEFT(MEI_C_HIERARCHY, 6) AS INT) + 1), 6)
	FROM	WFMEI_MENUITEM
	WHERE	LEN(MEI_C_HIERARCHY) > 3 AND  LEFT(MEI_C_HIERARCHY, 3) = @PARENT
	ORDER BY MEI_C_HIERARCHY desc

	--insere o ítem de menu para o admin
	INSERT INTO WFMEI_MENUITEM 
		(MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY,
		 MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY)
	VALUES 
		(@MENUID,  @READERS,  'Galeria',  '/WFAdmin/Modules/Gallery/Galleries.aspx',  '_self', @HIERARQUIA, 0,
		 0,  '',  '',  'pt-BR',  @MEI_C_NAMEKEY)


    --insere a tradução para inglês do ítem de menu
	INSERT INTO WFMET_MENUTRANSLATION (MET_C_LANGUAGE, MET_C_NAMEKEY, MET_C_MESSAGE)
	VALUES ('en-US', @MEI_C_NAMEKEY, 'Gallery')
END
GO

update WFMEI_MENUITEM set MEI_C_LANGUAGE = 'pt-BR', MEI_C_NAMEKEY = 'portfolio' where MEI_C_URL = '/Site/Home/Portfolio.ashx' and isnull(MEI_C_NAMEKEY, '') = ''
update WFMEI_MENUITEM set MEI_C_LANGUAGE = 'pt-BR', MEI_C_NAMEKEY = 'workspaces' where MEI_C_URL = '/Site/Home/AreaTrabalho.ashx' and isnull(MEI_C_NAMEKEY, '') = ''
update WFMEI_MENUITEM set MEI_C_LANGUAGE = 'pt-BR', MEI_C_NAMEKEY = 'controlpanel' where MEI_C_URL = '/Site/Home/PainelControle.ashx' and isnull(MEI_C_NAMEKEY, '') = ''
update WFMEI_MENUITEM set MEI_C_LANGUAGE = 'pt-BR', MEI_C_NAMEKEY = 'statistics' where MEI_C_URL = '/Site/Home/Estatisticas.ashx' and isnull(MEI_C_NAMEKEY, '') = ''
update WFMEI_MENUITEM set MEI_C_LANGUAGE = 'pt-BR', MEI_C_NAMEKEY = 'mngreport' where MEI_C_URL = '/Site/Home/RelatorioGerencial.ashx' and isnull(MEI_C_NAMEKEY, '') = ''
GO

if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'logs'        ) insert WFMET_MENUTRANSLATION values ('en-US', 'logs'        , 'Log Messages')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'logAudit'    ) insert WFMET_MENUTRANSLATION values ('en-US', 'logAudit'    , 'Audit Messages')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'portfolio'   ) insert WFMET_MENUTRANSLATION values ('en-US', 'portfolio'   , 'Portfolio')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'workspaces'  ) insert WFMET_MENUTRANSLATION values ('en-US', 'workspaces'  , 'Workspace')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'controlpanel') insert WFMET_MENUTRANSLATION values ('en-US', 'controlpanel', 'Control Panel')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'statistics'  ) insert WFMET_MENUTRANSLATION values ('en-US', 'statistics'  , 'Statistics')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'en-US' and MET_C_NAMEKEY = 'mngreport'   ) insert WFMET_MENUTRANSLATION values ('en-US', 'mngreport'   , 'Management Report')


if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'registration') insert WFMET_MENUTRANSLATION values ('es-ES', 'registration', 'REGISTRO')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'menus') insert WFMET_MENUTRANSLATION values ('es-ES', 'menus', 'Menús')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'maintenance') insert WFMET_MENUTRANSLATION values ('es-ES', 'maintenance', 'MANTENIMIENTO')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'content') insert WFMET_MENUTRANSLATION values ('es-ES', 'content', 'CONTENIDO')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'subportals') insert WFMET_MENUTRANSLATION values ('es-ES', 'subportals', 'SubPortales')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'users') insert WFMET_MENUTRANSLATION values ('es-ES', 'users', 'Usuarios')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'roles') insert WFMET_MENUTRANSLATION values ('es-ES', 'roles', 'Grupos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'profiles') insert WFMET_MENUTRANSLATION values ('es-ES', 'profiles', 'Perfiles')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'files') insert WFMET_MENUTRANSLATION values ('es-ES', 'files', 'Archivos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'pages') insert WFMET_MENUTRANSLATION values ('es-ES', 'pages', 'PÁGINAS')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'headfoot') insert WFMET_MENUTRANSLATION values ('es-ES', 'headfoot', 'Encabezado / Pie de página')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'publish') insert WFMET_MENUTRANSLATION values ('es-ES', 'publish', 'Publicación')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'schedule') insert WFMET_MENUTRANSLATION values ('es-ES', 'schedule', 'Programación')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'acclog') insert WFMET_MENUTRANSLATION values ('es-ES', 'acclog', 'Registro de acceso')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'permissions') insert WFMET_MENUTRANSLATION values ('es-ES', 'permissions', 'Permisos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'modules') insert WFMET_MENUTRANSLATION values ('es-ES', 'modules', 'Módulos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'config') insert WFMET_MENUTRANSLATION values ('es-ES', 'config', 'CONFIGURACIÓN')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'containers') insert WFMET_MENUTRANSLATION values ('es-ES', 'containers', 'Contenedores')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'layouts') insert WFMET_MENUTRANSLATION values ('es-ES', 'layouts', 'Diseños')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'polls') insert WFMET_MENUTRANSLATION values ('es-ES', 'polls', 'Encuesta')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'news') insert WFMET_MENUTRANSLATION values ('es-ES', 'news', 'Noticias')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'reports') insert WFMET_MENUTRANSLATION values ('es-ES', 'reports', 'INFORMES')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'areas') insert WFMET_MENUTRANSLATION values ('es-ES', 'areas', 'Áreas')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'management') insert WFMET_MENUTRANSLATION values ('es-ES', 'management', 'Administración')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'locations') insert WFMET_MENUTRANSLATION values ('es-ES', 'locations', 'Ubicaciones')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'messages') insert WFMET_MENUTRANSLATION values ('es-ES', 'messages', 'Mensajes')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'rssfeeds') insert WFMET_MENUTRANSLATION values ('es-ES', 'rssfeeds', 'Mensajes RSS')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'vispor') insert WFMET_MENUTRANSLATION values ('es-ES', 'vispor', 'Visitas al portal')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'visare') insert WFMET_MENUTRANSLATION values ('es-ES', 'visare', 'Visitas de área')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'vismenu') insert WFMET_MENUTRANSLATION values ('es-ES', 'vismenu', 'Clics de menú')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'vispag') insert WFMET_MENUTRANSLATION values ('es-ES', 'vispag', 'Visitas de página')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'trcpor') insert WFMET_MENUTRANSLATION values ('es-ES', 'trcpor', 'Seguimiento de portal')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'trcare') insert WFMET_MENUTRANSLATION values ('es-ES', 'trcare', 'Seguimiento de área')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'trcpag') insert WFMET_MENUTRANSLATION values ('es-ES', 'trcpag', 'Seguimiento de página')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'trcusr') insert WFMET_MENUTRANSLATION values ('es-ES', 'trcusr', 'Seguimiento de usuário')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'pagdet') insert WFMET_MENUTRANSLATION values ('es-ES', 'pagdet', 'Visitas detalladas a página')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'items') insert WFMET_MENUTRANSLATION values ('es-ES', 'items', 'Artículos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'styles') insert WFMET_MENUTRANSLATION values ('es-ES', 'styles', 'Estilos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'patterns') insert WFMET_MENUTRANSLATION values ('es-ES', 'patterns', 'Patrones')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'newscentral') insert WFMET_MENUTRANSLATION values ('es-ES', 'newscentral', 'Central de noticias')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'newssection') insert WFMET_MENUTRANSLATION values ('es-ES', 'newssection', 'Sección de noticias')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'gallery') insert WFMET_MENUTRANSLATION values ('es-ES', 'gallery', 'Galería')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'processes') insert WFMET_MENUTRANSLATION values ('es-ES', 'processes', 'PROCESOS')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'configuration') insert WFMET_MENUTRANSLATION values ('es-ES', 'configuration', 'Configuración')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'defaultprocess') insert WFMET_MENUTRANSLATION values ('es-ES', 'defaultprocess', 'Proceso estándar')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'holidays') insert WFMET_MENUTRANSLATION values ('es-ES', 'holidays', 'Vacaciones')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'stepsla') insert WFMET_MENUTRANSLATION values ('es-ES', 'stepsla', 'Escala SLA')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'priorities') insert WFMET_MENUTRANSLATION values ('es-ES', 'priorities', 'Prioridades')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'presets') insert WFMET_MENUTRANSLATION values ('es-ES', 'presets', 'Configuración de PopUp')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'procdesign') insert WFMET_MENUTRANSLATION values ('es-ES', 'procdesign', 'Diseño de procesos')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'allforms') insert WFMET_MENUTRANSLATION values ('es-ES', 'allforms', 'FORMULARIOS')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'mobileforms') insert WFMET_MENUTRANSLATION values ('es-ES', 'mobileforms', 'Formularios móviles')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'webforms') insert WFMET_MENUTRANSLATION values ('es-ES', 'webforms', 'Formularios Web')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'pagemanagement') insert WFMET_MENUTRANSLATION values ('es-ES', 'pagemanagement', 'Gestión de página')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'theme') insert WFMET_MENUTRANSLATION values ('es-ES', 'theme', 'Tema')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'logs') insert WFMET_MENUTRANSLATION values ('es-ES', 'logs', 'Mensajes de registro')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'logAudit') insert WFMET_MENUTRANSLATION values ('es-ES', 'logAudit', 'Mensajes de auditoría')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'portfolio') insert WFMET_MENUTRANSLATION values ('es-ES', 'portfolio', 'Portafolio')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'workspaces') insert WFMET_MENUTRANSLATION values ('es-ES', 'workspaces', 'Espacio de trabajo')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'controlpanel') insert WFMET_MENUTRANSLATION values ('es-ES', 'controlpanel', 'Panel de control')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'statistics') insert WFMET_MENUTRANSLATION values ('es-ES', 'statistics', 'Estadística')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'mngreport') insert WFMET_MENUTRANSLATION values ('es-ES', 'mngreport', 'Informe de gestión')
if not exists (select 1 from WFMET_MENUTRANSLATION where MET_C_LANGUAGE = 'es-ES' and MET_C_NAMEKEY = 'markersupdate') insert WFMET_MENUTRANSLATION values ('es-ES', 'markersupdate', 'Actualización de Marcadores')
GO

----### 15 WFPortal Zuri ###############################################################################

IF NOT (
	SELECT COUNT(*) 
	FROM WPMOD_MODULE 
	WHERE MOD_C_OWNER = 'DFEF5AF1-1004-4EA8-87CE-D3C58011E4BD' 
		AND MOD_C_CATEGORY = 'WORKFLOW' 
		AND MOD_C_COMPONENT = 'WFWORKFLOW/WFAREATRABALHO.ASCX') > 0
BEGIN
	INSERT INTO WPMOD_MODULE 
		(MOD_C_OWNER, MOD_C_GUID, MOD_C_NAME, MOD_C_CATEGORY, MOD_C_COMPONENT, MOD_N_INTERACTIVE, MOD_N_LOCALONLY)
	VALUES 
		('DFEF5AF1-1004-4EA8-87CE-D3C58011E4BD', '17876C8B-9924-4DC0-A6CE-AF28AB250CFE', 'Zuri - Area de Trabalho', 'Workflow', 'WFWorkflow/WFAreaTrabalho.ascx', 1, 0)
END
GO

-- AJUSTE DO GUID DA AREA DE TRABALHO PARA FICAR PADRONIZADO
UPDATE WPMOD_MODULE SET MOD_C_OWNER='DFEF5AF1-1004-4EA8-87CE-D3C58011E4BD', MOD_C_GUID='17876C8B-9924-4DC0-A6CE-AF28AB250CFE' WHERE  MOD_C_COMPONENT = 'WFWorkflow/WFAreaTrabalho.ascx'
GO


--CRIAÇÃO DE MENU DE LINKS RÁPIDOS NA ÁREA ADMINISTRATIVA
DECLARE @QLINK INT
SELECT @QLINK = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admqlinks'
IF NOT @QLINK IS NULL AND NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @QLINK AND MEI_C_URL = '/WFAdmin/WFWorkflow/Processos.aspx')
BEGIN
	INSERT WFMEI_MENUITEM VALUES (@qlink ,'-4;-3;-1;-7;','Processos', '/WFAdmin/WFWorkflow/Processos.aspx', '_self', '001', 0,0,'','','pt-BR','processes',null)
END
IF NOT @QLINK IS NULL AND NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @QLINK AND MEI_C_URL = '/WFAdmin/WFForms/Formularios.aspx')
BEGIN
	INSERT WFMEI_MENUITEM VALUES (@qlink ,'-4;-3;-1;-7;','Formulários Web', '/WFAdmin/WFForms/Formularios.aspx', '_self', '002', 0,0,'','','pt-BR','forms',null)
END
IF NOT @QLINK IS NULL AND NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @QLINK AND MEI_C_URL = '/WFAdmin/Ninki/NinkiMobile.aspx')
BEGIN
	INSERT WFMEI_MENUITEM VALUES (@qlink ,'-4;-3;-1;-7;','Formulários Mobile', '/WFAdmin/Ninki/NinkiMobile.aspx', '_self', '003', 0,0,'','','pt-BR','ninki',null)
END
IF NOT @QLINK IS NULL
BEGIN
	UPDATE WFMEI_MENUITEM SET MEI_C_HIERARCHY = '004' WHERE MEI_N_MEN_N_ID = @QLINK AND MEI_C_URL = '/WFAdmin/Pages/Pages.aspx'
END
GO

DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/WFWorkflow/Modulos.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/WFWorkflow/AtualizaObservadores.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Management/Files.aspx'
GO

-- AJUSTES NO MENU ADMINISTRATIVO DO ZURI
IF EXISTS(SELECT MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin')
BEGIN
	DECLARE @ADMID INT
	SELECT @ADMID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'
	DECLARE @ZURIHIER VARCHAR(6)
	SELECT @ZURIHIER = LEFT(MEI_C_HIERARCHY,3) FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/WFWorkflow/Processos.aspx' AND MEI_N_MEN_N_ID = @ADMID
	SET @ZURIHIER = @ZURIHIER + '001'
	IF NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_URL = '/WFAdmin/WFWorkflow/EtapaSla.aspx')
	BEGIN
		INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
		VALUES(@ADMID, '-3;-1;', 'SLA', '/WFAdmin/WFWorkflow/EtapaSla.aspx','',  @ZURIHIER + '004', 0, 0, '', '', 'pt-BR', '', NULL)
	END
	IF NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_URL = '/WFAdmin/WFWorkflow/Prioridades.aspx')
	BEGIN
		INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
		VALUES(@ADMID, '-3;-1;', 'Prioridades', '/WFAdmin/WFWorkflow/Prioridades.aspx','', @ZURIHIER + '005', 0, 0, '', '', 'pt-BR', '', NULL)
	END
	IF NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_URL = '/WFAdmin/WFWorkflow/PopupPresets.aspx')
	BEGIN
		INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
		VALUES(@ADMID, '-3;-1;', 'Janelas do Item', '/WFAdmin/WFWorkflow/PopupPresets.aspx','', @ZURIHIER + '006', 0, 0, '', '', 'pt-BR', '', NULL)
	END

	IF NOT EXISTS (SELECT 1 FROM WFMEI_MENUITEM WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_URL = '/WFAdmin/WFWorkflow/Markers.aspx')
	BEGIN
		INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
		VALUES(@ADMID, '-3;-1;', 'Atualização de Marcadores', '/WFAdmin/WFWorkflow/Markers.aspx','', @ZURIHIER + '007', 0, 0, '', '', 'pt-BR', 'markersupdate', NULL)

		INSERT INTO WFMET_MENUTRANSLATION (MET_C_LANGUAGE, MET_C_NAMEKEY, MET_C_MESSAGE)
		VALUES ('en-US', 'markersupdate', 'Markers Update')
	END
END
GO


IF NOT EXISTS (SELECT * FROM WFADX_AUDITEXCEPTION WHERE ADX_C_CATEGORY = 'AddItem (WebFoundations.WFWorkflow.Objects.HistoricoItem)')
BEGIN
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.HistoricoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.HistoricoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.ItemExecucao)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.AcaoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.ItemWorkflow)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.EtapaItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.ItemProcesso)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.EtapaItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.EtapaItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.ItemWorkflowComplete)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.EstatisticaEtapa)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.ItemProcesso)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.ItemWorkflow)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('WFWorkflow AdicionaItemProcesso')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.ItemUsers)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.ItemUsers)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.AcaoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.AcaoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.EstatisticaProcesso)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.AcaoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.EtapaItemEditors)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.EtapaItemEditors)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.AnexoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.AnexoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.AnexoItem)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WebFoundations.WFWorkflow.Objects.ProcessoDependencias)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('UpdateItem (WebFoundations.WFWorkflow.Objects.ProcessoDependencias)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('DeleteItem (WebFoundations.WFWorkflow.Objects.ProcessoDependencias)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('AddItem (WF.Ninki.Zuri.Objects.FormItemWorkflow)')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('frm_ListFormItemProcesso')
	INSERT INTO WFADX_AUDITEXCEPTION(ADX_C_CATEGORY) VALUES ('frm_AddFormItemProcesso')
END
GO

--CRIA SUBPORTAL 'Mobile' para as páginas mobile.
IF EXISTS (SELECT 1 FROM WPPOR_PORTAL) AND NOT EXISTS (SELECT 1 FROM WPPOR_PORTAL WHERE POR_C_ALIAS = 'mobile' AND POR_N_ID < 0)
BEGIN 
	DECLARE @ID INT, @ADM INT, @AREA INT, @LANG VARCHAR(5)
	SELECT	@ID = POR_N_ID,
			@ADM = POR_N_ADMROLE,
			@AREA = POR_N_ROOTAREA,
			@LANG = POR_C_LANGUAGE
	FROM WPPOR_PORTAL WHERE POR_N_ID < 0
	
	SET @ID = ISNULL(@ID, -1) - 1;

	SET IDENTITY_INSERT WPPOR_PORTAL ON	
	INSERT WPPOR_PORTAL (POR_N_ID, POR_C_NAME, POR_C_ALIAS, POR_C_FOLDER, POR_N_ADMROLE, POR_N_ROOTAREA, POR_C_READERS, POR_N_SYSTEMPORTAL, POR_N_LOCALONLY, POR_C_LANGUAGE)
	VALUES (@ID, 'Mobile', 'mobile', 'Mobile/', ISNULL(@ADM, -1), ISNULL(@AREA, 1), '', 1, 0, ISNULL(@LANG, 'pt-BR'))
	SET IDENTITY_INSERT WPPOR_PORTAL OFF
END
GO

--CRIA A ÁREA "pages" no portal 'mobile' COM O TEMPLATE CORRETO PARA POSSIBLITAR CRIAÇÃO DE PÁGINAS QUE POSSAM SER EXIBIDAS NA VERSÃO MOBILE WEB
IF NOT EXISTS (SELECT 1 FROM WPARE_AREA WHERE ARE_C_TEMPLATEFILE = 'pwa-template.aspx' )
BEGIN
	DECLARE @PORTAL INT, @ADM INT
	SELECT TOP 1 @PORTAL = POR_N_ID FROM WPPOR_PORTAL ORDER BY POR_N_SYSTEMPORTAL DESC, POR_N_ID --PEGA O PORTAL DE SISTEMA MAIS ANTIGO OU O PRIMEIRO PORTAL
	SELECT @ADM = POR_N_ADMROLE FROM WPPOR_PORTAL WHERE POR_N_ID = @PORTAL

	IF NOT @PORTAL IS NULL 
	BEGIN
		INSERT WPARE_AREA (ARE_C_NAME, ARE_C_ALIAS, ARE_N_POR_N_ID, ARE_N_ADMROLE, ARE_C_FOLDER, ARE_N_HOMEPAGE_ID, ARE_C_READERS, ARE_N_SYSTEMAREA, ARE_C_TEMPLATEFILE, ARE_N_MEN_N_ID)
		VALUES ('Mobile Pages', 'pages', @PORTAL, @ADM, '', 0, '', 1, 'pwa-template.aspx', 0)
	END
END
GO

--### 17 NinkiMobile Kingu ###############################################################################
IF EXISTS(SELECT 1 FROM WFMEI_MENUITEM INNER JOIN WFMEN_MENU ON MEI_N_MEN_N_ID = MEN_N_ID WHERE MEI_C_NAME = 'NINKI' AND MEN_C_ALIAS = 'admin')
BEGIN
	DECLARE @ADMID INT
	SELECT @ADMID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'
	DELETE FROM WFMEI_MENUITEM WHERE MEI_C_NAME = 'NINKI' AND MEI_N_MEN_N_ID = @ADMID
	DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Ninki/NinkiMobile.aspx' AND MEI_N_MEN_N_ID = @ADMID
END
GO

--AJUSTE NO MENU DE CONFIGURACOES
IF EXISTS (SELECT 1 FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin') AND NOT EXISTS(SELECT 1 FROM WFMEI_MENUITEM INNER JOIN WFMEN_MENU ON MEI_N_MEN_N_ID = MEN_N_ID WHERE MEI_C_NAMEKEY = 'NINKI' AND MEN_C_ALIAS = 'admin')
BEGIN
	DECLARE @ADMID INT
	SELECT @ADMID = MEN_N_ID FROM WFMEN_MENU WHERE MEN_C_ALIAS = 'admin'
	DECLARE @EXISTINGHIER VARCHAR(6)
	SELECT @EXISTINGHIER = MEI_C_HIERARCHY FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/WFForms/Formularios.aspx' AND MEI_N_MEN_N_ID = @ADMID
	UPDATE WFMEI_MENUITEM SET MEI_C_URL = '#' WHERE MEI_N_MEN_N_ID = @ADMID AND MEI_C_HIERARCHY = @EXISTINGHIER

	INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
	VALUES(@ADMID, '-4;-3;-1;-7', 'Formulários Web', '/WFAdmin/WFForms/Formularios.aspx', '_self', (@EXISTINGHIER + '001'), 0, 1, '', '', 'pt-BR', 'forms', NULL)

	INSERT INTO WFMEI_MENUITEM (MEI_N_MEN_N_ID, MEI_C_READERS, MEI_C_NAME, MEI_C_URL, MEI_C_TARGET, MEI_C_HIERARCHY, MEI_N_LOCALONLY, MEI_N_SYSTEMMENU, MEI_C_IMAGE, MEI_C_STATUSBAR, MEI_C_LANGUAGE, MEI_C_NAMEKEY, MEI_C_CSSCLASS)
	VALUES(@ADMID, '-4;-3;-1;-7', 'Formulários Mobile', '/WFAdmin/Ninki/NinkiMobile.aspx', '_self', (@EXISTINGHIER + '002'), 0, 0, '', '', 'pt-BR', 'NINKI', NULL)
END
GO

--### 20 Zuri ########################################################################################
--#####################################################################################################################
--***** TABELAS *******************************************************************************************************
--#####################################################################################################################

IF OBJECT_ID('MWSUB_SUBPROCESS') IS NULL 
BEGIN
	CREATE TABLE MWSUB_SUBPROCESS(
		SUB_N_ATV_N_CODIGO		INT NOT NULL,
		SUB_N_PRO_N_CODIGO		INT NOT NULL,
		SUB_C_TITULO			VARCHAR(80) NOT NULL,
		SUB_N_CALL_ATIVIDADE	INT NOT NULL,
		SUB_C_PARAMS			TEXT NOT NULL,
		CONSTRAINT PK_MWSUB_SUBPROCESS PRIMARY KEY CLUSTERED (SUB_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWCET_CANCELAETAPA') IS NULL 
BEGIN
	CREATE TABLE MWCET_CANCELAETAPA(
		CET_N_ATV_N_CODIGO	INT NOT NULL,
		CET_N_ETAPAID		INT NOT NULL,
		CONSTRAINT PK_MWCET_CANCELAETAPA PRIMARY KEY CLUSTERED (CET_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWWEB_WEBSERVICE') IS NULL 
BEGIN
	CREATE TABLE MWWEB_WEBSERVICE(
		WEB_ATV_N_CODIGO	INT NOT NULL,
		WEB_C_URL			VARCHAR(300) NOT NULL,
		WEB_C_METHODNAME	VARCHAR(100) NOT NULL,
		WEB_C_PARAMETERS	TEXT NULL,
		WEB_C_OBJECTOUT		VARCHAR(50) NULL,
		WEB_C_ACCESSLIST	VARCHAR(100) NULL,
		WEB_N_EXPORTXML		BIT NOT NULL,
		CONSTRAINT PK_MWWEB_WEBSERVICE PRIMARY KEY CLUSTERED (WEB_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWMVA_MOVEANEXO') IS NULL 
BEGIN
	CREATE TABLE MWMVA_MOVEANEXO (
		MVA_N_ATV_N_CODIGO	INT NOT NULL,
		MVA_C_DESTINO		VARCHAR(200) NOT NULL,
		MVA_C_ANEXO			VARCHAR(100) NOT NULL
		CONSTRAINT PK_MWMVA_MOVEANEXO PRIMARY KEY CLUSTERED (MVA_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWPDF_PDFCREATOR') IS NULL 
BEGIN
	CREATE TABLE MWPDF_PDFCREATOR (
		PDF_N_ATV_N_CODIGO	INT NOT NULL,
		PDF_C_LISTAACESSO	VARCHAR(200) NULL,
		PDF_C_FILENAME		VARCHAR(200) NOT NULL,
		PDF_C_CONFIG		TEXT NOT NULL
		CONSTRAINT PK_MWPDF_PDFCREATOR PRIMARY KEY CLUSTERED (PDF_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WFER_FERIADO') IS NULL 
BEGIN
	CREATE TABLE WFER_FERIADO(
		FER_N_CODIGO	INT IDENTITY(1,1) NOT NULL,
		FER_N_DIA		SMALLINT NOT NULL,
		FER_N_MES		SMALLINT NOT NULL,
		FER_N_ANO		SMALLINT NULL,
		FER_N_LOC_ID	NCHAR(10) NOT NULL,
		CONSTRAINT PK_WFER_FERIADO PRIMARY KEY CLUSTERED (FER_N_CODIGO ASC)
	)
END
GO
--#####################################################################################################################

IF OBJECT_ID('MWARQ_ARQUIVO') IS NULL 
BEGIN
	CREATE TABLE MWARQ_ARQUIVO (
		ARQ_N_ATV_N_CODIGO	INT NOT NULL,
		ARQ_C_LISTAACESSO	VARCHAR(100) NOT NULL,
		ARQ_C_TEXTO			TEXT NOT NULL,
		ARQ_C_EXT			VARCHAR(20) NOT NULL,
		CONSTRAINT PK_MWARQ_ARQUIVO PRIMARY KEY CLUSTERED (ARQ_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWEXT_DADOSEXTERNOS') IS NULL 
BEGIN
	CREATE TABLE MWEXT_DADOSEXTERNOS(
		EXT_N_ATV_N_CODIGO		INT NOT NULL,
		EXT_N_PRO_N_CODIGO		INT NOT NULL,
		EXT_C_ATTACHMENTALIAS	NVARCHAR(50) NULL,
		CONSTRAINT PK_MWEXT_DADOSEXTERNOS PRIMARY KEY CLUSTERED (EXT_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWDLN_DEADLINE') IS NULL 
BEGIN
	CREATE TABLE MWDLN_DEADLINE(
		DLN_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		DLN_N_ATV_N_CODIGO	INT NOT NULL,
		DLN_N_PRZ_N_CODIGO	INT NOT NULL,
		CONSTRAINT PK_MWDLN_DEADLINE PRIMARY KEY CLUSTERED (DLN_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWEML_EMAIL') IS NULL 
BEGIN
	CREATE TABLE MWEML_EMAIL(
		EML_N_ATV_N_CODIGO				INT NOT NULL,
		EML_C_TITULO					VARCHAR(150) NOT NULL,
		EML_C_TEXTO						TEXT NOT NULL,
		EML_C_DESTINATARIOS				TEXT NOT NULL,
		EML_C_DESTINATARIOSCOPIA		TEXT,
		EML_C_DESTINATARIOSCOPIAOCULTA	VARCHAR(MAX),
		EML_C_ANEXOS					TEXT NOT NULL,
		EML_N_EDITDEST					BIT NOT NULL,
		EML_N_EDITCONTENT				BIT NOT NULL,
		EML_C_SENDER					VARCHAR(150) NOT NULL,
		CONSTRAINT PK_MWEML_EMAIL PRIMARY KEY CLUSTERED (EML_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWFIL_FILTRODINAMICO') IS NULL 
BEGIN
	CREATE TABLE MWFIL_FILTRODINAMICO(
		FIL_N_ATV_N_CODIGO	INT NOT NULL,
		FIL_N_ETA_N_CODIGO	INT NOT NULL,
		FIL_C_FILTRO		VARCHAR(250) NOT NULL,
		CONSTRAINT PK_MWFIL_FILTRODINAMICO PRIMARY KEY CLUSTERED (FIL_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWFUS_FILTROUSUARIO') IS NULL 
BEGIN
	CREATE TABLE MWFUS_FILTROUSUARIO(
		FUS_N_ATV_N_CODIGO	INT NOT NULL,
		FUS_N_ETA_N_CODIGO	INT NOT NULL,
		FUS_C_FILTRO		VARCHAR(250) NOT NULL,
		CONSTRAINT PK_MWFUS_FILTROUSUARIO PRIMARY KEY CLUSTERED (FUS_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WITA_ITEM_ARQUIVADO') IS NULL 
BEGIN
	CREATE TABLE WITA_ITEM_ARQUIVADO(
		ITA_N_CODIGO		INT NOT NULL,
		ITA_C_NOME			VARCHAR(80) NOT NULL,
		ITA_C_STATUS		VARCHAR(50) NOT NULL,
		ITA_D_DATAINICIO	DATETIME NOT NULL,
		ITA_N_USU_OWNER		INT NOT NULL,
		ITA_C_LISTAACESSO	VARCHAR(100) NOT NULL,
		ITA_N_ARE_ORIGEM	INT NOT NULL,
		ITA_N_FINALIZADO	BIT NOT NULL,
		ITA_C_PROCESSOS		TEXT NOT NULL,
		ITA_D_DATAFIM		DATETIME NULL,
		CONSTRAINT PK_WITA_ITEM_ARQUIVADO PRIMARY KEY CLUSTERED (ITA_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWPRC_PROCEDURE') IS NULL 
BEGIN
	CREATE TABLE MWPRC_PROCEDURE(
		PRC_N_ATV_N_CODIGO	INT NOT NULL,
		PRC_C_CONNECTION	VARCHAR(50) NOT NULL,
		PRC_C_PROCNAME		VARCHAR(100) NOT NULL,
		PRC_C_LISTAACESSO	VARCHAR(100) NOT NULL,
		PRC_N_EXPORTXML		BIT NOT NULL,
		PRC_C_PARAMETROS	TEXT NOT NULL,
		CONSTRAINT PK_MWPRC_PROCEDURE PRIMARY KEY CLUSTERED (PRC_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WIWF_ITEM_WORKFLOW') IS NULL 
BEGIN
	CREATE TABLE WIWF_ITEM_WORKFLOW(
		IWF_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		IWF_C_NOME			VARCHAR(80) NOT NULL,
		IWF_C_STATUS		VARCHAR(50) NOT NULL,
		IWF_D_DATAINICIO	DATETIME NOT NULL CONSTRAINT DF_WIWF_ITEM_WORKFLOW_DATAINICIO  DEFAULT (GETDATE()),
		IWF_N_READONLY		BIT NOT NULL CONSTRAINT DF_WIWF_ITEM_WORKFLOW_READONLY  DEFAULT (0),
		IWF_N_USU_OWNER		INT NOT NULL,
		IWF_N_ARE_ORIGEM	INT NOT NULL,
		IWF_N_ITE_ORIGEM	INT NOT NULL CONSTRAINT DF_WIWF_ITEM_WORKFLOW_ITE_ORIGEM  DEFAULT (0),
		IWF_N_PRO_ORIGEM	INT NOT NULL,
		IWF_D_DATAFIM		DATETIME NULL,
		IWF_C_METADATA		VARCHAR(MAX) NULL,
		CONSTRAINT PK_WIWF_ITEM_WORKFLOW PRIMARY KEY CLUSTERED (IWF_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWTXT_TEXTO') IS NULL 
BEGIN
	CREATE TABLE MWTXT_TEXTO(
		TXT_N_ATV_N_CODIGO	INT NOT NULL,
		TXT_C_TEXTO			TEXT NOT NULL,
		CONSTRAINT PK_MWTXT_TEXTO PRIMARY KEY CLUSTERED (TXT_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWREG_REGRA') IS NULL 
BEGIN
	CREATE TABLE MWREG_REGRA(
		REG_N_ATS_N_CODIGO	INT NOT NULL,
		REG_N_ATV_N_CODIGO	INT NOT NULL,
		REG_C_CONDICAO		TEXT NOT NULL,
		CONSTRAINT PK_MWREG_REGRA PRIMARY KEY CLUSTERED (REG_N_ATS_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWFXT_FLUXOEXTERNO') IS NULL 
BEGIN
	CREATE TABLE MWFXT_FLUXOEXTERNO(
		FXT_N_ATV_N_CODIGO	INT NOT NULL,
		FXT_N_PEN_N_CODIGO	INT NOT NULL,
		FXT_N_SINCRONO		BIT NOT NULL,
		FXT_N_NOVOITEM		SMALLINT NOT NULL,
		FXT_N_PROPAGAANEXO	SMALLINT,
		FXT_C_LISTAANEXOS	VARCHAR(2000),
		CONSTRAINT PK_MWFXT_FLUXOEXTERNO PRIMARY KEY CLUSTERED (FXT_N_ATV_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WMOD_MODULO') IS NULL 
BEGIN
	CREATE TABLE WMOD_MODULO(
		MOD_N_CODIGO			INT IDENTITY(1,1) NOT NULL,
		MOD_C_OWNERID			UNIQUEIDENTIFIER NULL,
		MOD_C_ITEMID			UNIQUEIDENTIFIER NOT NULL CONSTRAINT DF_WMOD_MODULO_MOD_C_ITEMID DEFAULT (NEWID()),
		MOD_C_TITULO			VARCHAR(40) NOT NULL,
		MOD_C_ASCX				VARCHAR(100) NOT NULL,
		MOD_C_ASPXADM			VARCHAR(100) NOT NULL,
		MOD_N_POPADM_HEIGHT		SMALLINT NOT NULL,
		MOD_N_POPADM_WIDTH		SMALLINT NOT NULL,
		MOD_N_TIPOSUCESSOR		SMALLINT NOT NULL,
		MOD_C_GUIDSUCESSOR		VARCHAR(36) NOT NULL,
		MOD_N_TIPOANTECESSOR	SMALLINT NOT NULL,
		MOD_C_GUIDANTECESSOR	VARCHAR(36) NOT NULL,
		MOD_C_ICONE				VARCHAR(150) NOT NULL,
		MOD_C_CATEGORIA			VARCHAR(40) NOT NULL CONSTRAINT DF_WMOD_MODULO_MOD_C_CATEGORIA DEFAULT (''),
		MOD_N_TIPO_SAIDA		SMALLINT NOT NULL,
		MOD_N_TIPO_ENTRADA		SMALLINT NOT NULL,
		MOD_N_INTERATIVO		BIT NOT NULL,
		MOD_C_ASSEMBLYINFO		VARCHAR(500) NULL,
		MOD_N_USODESENHO		BIT NULL,
		MOD_N_USOPRAZO			BIT NULL,
		MOD_N_ORDER				SMALLINT NOT NULL CONSTRAINT DF_MOD_N_ORDER DEFAULT(0),
		CONSTRAINT PK_WMOD_MODULO PRIMARY KEY CLUSTERED (MOD_N_CODIGO ASC)
	)
END
GO
--#####################################################################################################################

IF OBJECT_ID('WPRO_PROCESSO') IS NULL 
BEGIN
	CREATE TABLE WPRO_PROCESSO(
		PRO_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		PRO_C_NOME			VARCHAR(50) NOT NULL,
		PRO_C_DESCRICAO		TEXT NOT NULL CONSTRAINT DF_WPRO_PROCESSO_PRO_C_DESCRICAO DEFAULT '',
		PRO_N_ARE_N_CODIGO	INT NOT NULL,
		PRO_C_GESTORES		VARCHAR(100) NULL,
		PRO_N_ATIVO			BIT NOT NULL,
		PRO_N_EDICAO		BIT NOT NULL,
		PRO_D_CRIACAO		DATETIME NOT NULL CONSTRAINT DF_WPRO_PROCESSO_PRO_D_CRIACAO DEFAULT (GETDATE()),
		PRO_N_USU_CRIADOR	INT NOT NULL,
		PRO_D_ALTERACAO		DATETIME NULL,
		PRO_N_USU_ALTERADOR	INT NULL,
		PRO_N_ARQUIVAMENTO	SMALLINT NOT NULL,
		PRO_N_ETA_INICIAL	INT NOT NULL CONSTRAINT DF_WPRO_PROCESSO_PRO_N_ETA_INICIAL DEFAULT (-1),
		PRO_C_TITULOITEM	VARCHAR(200) NOT NULL CONSTRAINT DF_WPRO_PROCESSO_PRO_C_TITULOITEM DEFAULT '',
		PRO_C_DESIGN		TEXT NULL CONSTRAINT DF_WPRO_PROCESSO_PRO_C_DESIGN DEFAULT '',
		PRO_N_USECOUNTER	BIT NOT NULL,
		PRO_N_SKIPDUPLICATE	BIT NOT NULL,
		PRO_N_ADDCOMMENT	BIT NOT NULL,
		PRO_N_ADDFILE		BIT NOT NULL,
		PRO_C_METADATA		TEXT NULL,
		CONSTRAINT PK_WPRO_PROCESSO PRIMARY KEY CLUSTERED (PRO_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WFIL_FILTRO') IS NULL 
BEGIN
	CREATE TABLE WFIL_FILTRO(
		FIL_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		FIL_N_PART_ID		INT NOT NULL,
		FIL_N_PRO_N_CODIGO	INT NOT NULL,
		FIL_C_NOME			VARCHAR(30) NOT NULL,
		CONSTRAINT PK_WFIL_FILTRO PRIMARY KEY CLUSTERED (FIL_N_CODIGO ASC),
		CONSTRAINT FK_WFIL_FILTRO_WPRO_PROCESSO FOREIGN KEY(FIL_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WFIT_FILTRO_ITEM') IS NULL 
BEGIN
	CREATE TABLE WFIT_FILTRO_ITEM(
		FIT_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		FIT_N_FIL_N_CODIGO	INT NOT NULL,
		FIT_N_POR_ORIGEM	INT NOT NULL,
		FIT_N_ARE_ORIGEM	INT NOT NULL,
		FIT_C_FILTRO		VARCHAR(50) NOT NULL,
		CONSTRAINT PK_WFIT_FILTRO_ITEM PRIMARY KEY CLUSTERED (FIT_N_CODIGO ASC),
		CONSTRAINT FK_WFIT_FILTRO_ITEM_WFIL_FILTRO FOREIGN KEY(FIT_N_FIL_N_CODIGO)
			REFERENCES WFIL_FILTRO (FIL_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WETA_ETAPA_PROCESSO') IS NULL 
BEGIN
	CREATE TABLE WETA_ETAPA_PROCESSO(
		ETA_N_CODIGO			INT IDENTITY(1,1) NOT NULL,
		ETA_N_PART_ID			INT NOT NULL,
		ETA_N_PRO_N_CODIGO		INT NOT NULL,
		ETA_C_NOME				VARCHAR(30) NOT NULL,
		ETA_C_GRUPOPERFIL		VARCHAR(200) NOT NULL,
		ETA_C_GESTORES			VARCHAR(100) NULL,
		ETA_N_TIPOETAPA			SMALLINT NOT NULL,
		ETA_N_ATRIBUICAO		BIT NOT NULL CONSTRAINT DF_WETA_ETAPA_PROCESSO_ETA_N_ATRIBUICAO DEFAULT (0),
		ETA_N_PERFILRESTRICAO	INT NOT NULL,
		ETA_N_GRPDELEGAVEL		INT NOT NULL,
		ETA_C_METADATA			TEXT,
		ETA_C_MENSAGEM			TEXT NULL,
		CONSTRAINT PK_WETA_ETAPA_PROCESSO PRIMARY KEY CLUSTERED (ETA_N_CODIGO ASC),
		CONSTRAINT FK_WETA_ETAPA_PROCESSO_WPRO_PROCESSO FOREIGN KEY(ETA_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO
--#####################################################################################################################

IF OBJECT_ID('WETS_ETAPA_SLA') IS NULL
BEGIN
	CREATE TABLE WETS_ETAPA_SLA(
		ETS_N_CODIGO	INT IDENTITY(1,1) NOT NULL,
		ETS_C_NOME		VARCHAR(30) NOT NULL,
		ETS_C_COR		CHAR(7) NOT NULL
		CONSTRAINT PK_WETS_ETAPA_SLA PRIMARY KEY CLUSTERED (ETS_N_CODIGO ASC)
	)
END

--#####################################################################################################################

IF OBJECT_ID('WPRZ_PRAZO') IS NULL 
BEGIN
	CREATE TABLE WPRZ_PRAZO(
		PRZ_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		PRZ_N_ETA_N_CODIGO	INT NOT NULL,
		PRZ_N_PRI_N_CODIGO	INT NOT NULL,
		PRZ_N_TIPO			SMALLINT NOT NULL,
		PRZ_C_VALOR			VARCHAR(6) NOT NULL,
		PRZ_N_ACAO			SMALLINT NOT NULL,
		PRZ_C_PARAM_ACAO	VARCHAR(250) NOT NULL,
		PRZ_C_COR			VARCHAR(8) NOT NULL,
		PRZ_N_LOOP			BIT NOT NULL,
		PRZ_C_NOME			VARCHAR(50) NOT NULL,
		PRZ_C_STATUS		VARCHAR(50) NULL,
		PRZ_N_MOD_N_CODIGO	INT NULL,
		PRZ_N_CONFIGURED	BIT NULL,
		PRZ_N_ETS_N_CODIGO	INT NULL,
		CONSTRAINT PK_WPRZ_PRAZO PRIMARY KEY CLUSTERED (PRZ_N_CODIGO ASC),
		CONSTRAINT FK_WPRZ_PRAZO_WETA_ETAPA_PROCESSO FOREIGN KEY(PRZ_N_ETA_N_CODIGO)
			REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_WPRZ_PRAZO_WETS_ETAPA_SLA FOREIGN KEY(PRZ_N_ETS_N_CODIGO)
			REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WEML_EMAIL') IS NULL 
BEGIN
	CREATE TABLE WEML_EMAIL(
		EML_N_PRZ_N_CODIGO				INT NOT NULL,
		EML_C_TITULO					VARCHAR(100) NOT NULL,
		EML_C_DESTINATARIOS				VARCHAR(300) NOT NULL,
		EML_C_DESTINATARIOSCOPIA		VARCHAR(MAX) NULL,
		EML_C_DESTINATARIOSCOPIAOCULTA	VARCHAR(MAX),
		EML_C_TEXTO						TEXT NOT NULL,
		CONSTRAINT PK_WEML_EMAIL PRIMARY KEY CLUSTERED (EML_N_PRZ_N_CODIGO ASC),
		CONSTRAINT FK_WEML_EMAIL_WPRZ_PRAZO FOREIGN KEY(EML_N_PRZ_N_CODIGO)
			REFERENCES WPRZ_PRAZO (PRZ_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WATV_ATIVIDADE') IS NULL 
BEGIN
	CREATE TABLE WATV_ATIVIDADE(
		ATV_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ATV_N_PART_ID		INT NOT NULL,
		ATV_N_PRO_N_CODIGO	INT NOT NULL,
		ATV_N_MOD_N_CODIGO	INT NOT NULL,
		ATV_C_NOME			VARCHAR(100) NOT NULL,
		ATV_C_FORMATOANEXO	TEXT NULL,
		ATV_C_ALIASANEXO	VARCHAR(50) NULL,
		ATV_C_CONFIGURATION	TEXT NULL,
		CONSTRAINT PK_WATV_ATIVIDADE PRIMARY KEY CLUSTERED (ATV_N_CODIGO ASC),
		CONSTRAINT FK_WATV_ATIVIDADE_WPRO_PROCESSO FOREIGN KEY(ATV_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO
--#####################################################################################################################

IF OBJECT_ID('WATS_ATIVIDADE_SAIDA') IS NULL 
BEGIN
	CREATE TABLE WATS_ATIVIDADE_SAIDA(
		ATS_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ATS_N_ATV_N_CODIGO	INT NOT NULL,
		ATS_C_TITULO		VARCHAR(200) NOT NULL,
		ATS_C_VALOR			VARCHAR(30) NOT NULL,
		CONSTRAINT PK_WATS_ATIVIDADE_SAIDA PRIMARY KEY CLUSTERED (ATS_N_CODIGO ASC),
		CONSTRAINT FK_WATS_ATIVIDADE_SAIDA_WATV_ATIVIDADE FOREIGN KEY(ATS_N_ATV_N_CODIGO)
			REFERENCES WATV_ATIVIDADE (ATV_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WIPR_ITEM_PROCESSO') IS NULL 
BEGIN
	CREATE TABLE WIPR_ITEM_PROCESSO(
		IPR_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		IPR_N_IWF_N_CODIGO	INT NOT NULL,
		IPR_N_PRO_N_CODIGO	INT NOT NULL,
		IPR_N_COUNTERID		INT NOT NULL,
		IPR_N_PRIORIDADE	INT NOT NULL,
		IPR_D_DATAINICIO	DATETIME NOT NULL,
		IPR_C_STATUSCOLOR	VARCHAR(10) NOT NULL,
		IPR_N_FINALIZADO	BIT NOT NULL,
		IPR_C_LISTAACESSO	VARCHAR(100) NULL,
		IPR_N_LOCALIDADE	INT NOT NULL,
		IPR_C_METADATA		TEXT NULL,
		CONSTRAINT PK_WIPR_ITEM_PROCESSO PRIMARY KEY CLUSTERED (IPR_N_CODIGO ASC),
		CONSTRAINT FK_WIPR_ITEM_PROCESSO_WIWF_ITEM_WORKFLOW FOREIGN KEY(IPR_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW (IWF_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WETI_ETAPA_ITEM') IS NULL 
BEGIN
	CREATE TABLE WETI_ETAPA_ITEM(
		ETI_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ETI_N_IPR_N_CODIGO	INT NOT NULL,
		ETI_N_ETA_N_CODIGO	INT NOT NULL,
		ETI_N_USU_VINCULADO	INT NOT NULL,
		ETI_C_LISTAEDICAO	VARCHAR(200) NOT NULL,
		ETI_C_GESTORES		VARCHAR(100) NULL,
		ETI_N_USU_CRIADOR	INT NOT NULL,
		ETI_N_USERPRIORITY	SMALLINT NOT NULL CONSTRAINT DF_WETI_ETAPA_ITEM_ETI_N_USERPRIORITY DEFAULT ((0)),
		ETI_N_ENABLED		BIT NOT NULL,
		ETI_D_INICIO		DATETIME NOT NULL CONSTRAINT DF_WETI_ETAPA_ITEM_ETI_D_INICIO DEFAULT GETDATE(),
		CONSTRAINT PK_WETI_ETAPA_ITEM PRIMARY KEY CLUSTERED (ETI_N_CODIGO ASC),
		CONSTRAINT FK_WETI_ETAPA_ITEM_WETA_ETAPA_PROCESSO FOREIGN KEY(ETI_N_ETA_N_CODIGO)
			REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_WETI_ETAPA_ITEM_WIPR_ITEM_PROCESSO FOREIGN KEY(ETI_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WETE_ETAPA_ITEM_EDITORS') IS NULL 
BEGIN
	CREATE TABLE WETE_ETAPA_ITEM_EDITORS(
		ETE_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ETE_N_ETI_N_CODIGO	INT NOT NULL,
		ETE_N_USR_N_ID		INT NOT NULL,
		CONSTRAINT PK_WFETU_ETAPA_ITEM_USER PRIMARY KEY CLUSTERED (ETE_N_CODIGO ASC),
		CONSTRAINT FK_WETE_ETAPA_ITEM_EDITORS_WETI_ETAPA_ITEM FOREIGN KEY(ETE_N_ETI_N_CODIGO)
			REFERENCES WETI_ETAPA_ITEM (ETI_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WACI_ACAO_ITEM') IS NULL 
BEGIN
	CREATE TABLE WACI_ACAO_ITEM(
		ACI_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ACI_N_IPR_N_CODIGO	INT NOT NULL CONSTRAINT DF_WACI_ACAO_ITEM_ACI_N_ITE_N_CODIGO DEFAULT (0),
		ACI_N_ETI_N_CODIGO	INT NOT NULL,
		ACI_N_PRZ_N_ID		INT NOT NULL,
		ACI_D_EXECUCAO		DATETIME NOT NULL,
		ACI_N_TIPO			SMALLINT NOT NULL,
		ACI_C_PARAMETRO		TEXT NOT NULL,
		ACI_N_LOOP			BIT NOT NULL,
		ACI_C_NOME			VARCHAR(50) NOT NULL,
		ACI_N_ETA_N_CODIGO	INT NULL,
		CONSTRAINT PK_WACI_ACAO_ITEM PRIMARY KEY CLUSTERED (ACI_N_CODIGO ASC),
		CONSTRAINT FK_WACI_ACAO_ITEM_WIPR_ITEM_PROCESSO FOREIGN KEY(ACI_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('MWHIE_HIERARQUIA') IS NULL 
BEGIN
	CREATE TABLE MWHIE_HIERARQUIA(
		HIE_N_CODIGO			INT IDENTITY(1,1) NOT NULL,
		HIE_N_ATV_N_CODIGO		INT NOT NULL,
		HIE_C_NOMEHIERARQUIA	NVARCHAR(100) NOT NULL,
		HIE_N_GRP_N_CODIGO		INT NOT NULL,
		HIE_N_PRO_N_CODIGO		INT NOT NULL,
		HIE_N_PARENT			INT NOT NULL,
		CONSTRAINT PK_MWHIE PRIMARY KEY (HIE_N_CODIGO)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WANX_ANEXO_ITEM') IS NULL 
BEGIN
	CREATE TABLE WANX_ANEXO_ITEM(
		ANX_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ANX_N_IWF_N_CODIGO	INT NOT NULL,
		ANX_N_PRO_N_CODIGO	INT NOT NULL,
		ANX_N_ATV_N_CODIGO	INT NOT NULL,
		ANX_N_TIPO			INT NOT NULL,
		ANX_C_ATVALIASANEXO	VARCHAR(200) NULL,
		ANX_C_MODULO		VARCHAR(36) NULL,
		ANX_C_NOME			NVARCHAR(250) NOT NULL,
		ANX_C_DESCRICAO		TEXT NOT NULL,
		ANX_C_NOMEARQ		NVARCHAR(250) NULL,
		ANX_C_CONTENT		TEXT NOT NULL,
		ANX_USU_N_CODIGO	INT NOT NULL,
		ANX_C_LISTAACESSO	VARCHAR(100) NOT NULL,
		ANX_D_INCLUSAO		DATETIME NOT NULL CONSTRAINT DF_WANX_ANEXO_ITEM_ANX_D_INCLUSAO  DEFAULT (GETDATE()),
		ANX_N_ATIVO			BIT NOT NULL,
		CONSTRAINT PK_WANX_ANEXO_ITEM PRIMARY KEY CLUSTERED (ANX_N_CODIGO ASC),
		CONSTRAINT FK_WANX_ANEXO_ITEM_WITE_ITEM_PROCESSO FOREIGN KEY(ANX_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW (IWF_N_CODIGO) ON DELETE CASCADE
	)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANX_B_OCULTO' AND OBJECT_ID = OBJECT_ID('WANX_ANEXO_ITEM'))
BEGIN
	ALTER TABLE WANX_ANEXO_ITEM ADD ANX_B_OCULTO BIT NOT NULL CONSTRAINT DF_WANX_OCULTO DEFAULT (0)
END
GO

--MUDA O TIPO DOS CAMPOS NOME E NOMEARQ PARA NVARCHAR PARA RESOLVER PROBLEMA DE ENCODING NOS NOMES DOS ARQUIVOS ANEXOS DE ITEM
IF EXISTS (SELECT 1 
			FROM SYS.COLUMNS C
			INNER JOIN SYS.TYPES T ON C.SYSTEM_TYPE_ID  = T.SYSTEM_TYPE_ID
			WHERE OBJECT_ID = OBJECT_ID('WANX_ANEXO_ITEM') AND T.NAME = 'varchar' AND (C.NAME = 'ANX_C_NOME'  OR C.NAME = 'ANX_C_NOMEARQ'))
BEGIN
	ALTER TABLE WANX_ANEXO_ITEM ALTER COLUMN ANX_C_NOME NVARCHAR(250)
	ALTER TABLE WANX_ANEXO_ITEM ALTER COLUMN ANX_C_NOMEARQ NVARCHAR(250)
END
GO


--#####################################################################################################################

IF OBJECT_ID('WANF_ANEXO_FINALIZADO') IS NULL 
BEGIN
	CREATE TABLE WANF_ANEXO_FINALIZADO(
		ANF_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ANF_N_IWF_N_CODIGO	INT NOT NULL,
		ANF_N_PRO_N_CODIGO	INT NOT NULL,
		ANF_N_ATV_N_CODIGO	INT NOT NULL,
		ANF_N_TIPO			INT NOT NULL,
		ANF_C_ATVALIASANEXO	VARCHAR(200) NULL,
		ANF_C_MODULO		VARCHAR(36) NULL,
		ANF_C_NOME			NVARCHAR(250) NOT NULL,
		ANF_C_DESCRICAO		TEXT NOT NULL,
		ANF_C_NOMEARQ		NVARCHAR(250) NULL,
		ANF_C_CONTENT		TEXT NOT NULL,
		ANF_USU_N_CODIGO	INT NOT NULL,
		ANF_C_LISTAACESSO	VARCHAR(100) NOT NULL,
		ANF_D_INCLUSAO		DATETIME NOT NULL,
		ANF_N_ATIVO			BIT NOT NULL,
		CONSTRAINT PK_WANF_ANEXO_FINALIZADO PRIMARY KEY CLUSTERED (ANF_N_CODIGO ASC)
	)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANF_B_OCULTO' AND OBJECT_ID = OBJECT_ID('WANF_ANEXO_FINALIZADO'))
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO ADD ANF_B_OCULTO BIT NOT NULL CONSTRAINT DF_WANF_OCULTO DEFAULT (0)
END
GO

--MUDA O TIPO DOS CAMPOS NOME E NOMEARQ PARA NVARCHAR PARA RESOLVER PROBLEMA DE ENCODING NOS NOMES DOS ARQUIVOS ANEXOS DE ITEM
IF EXISTS (SELECT 1 
			FROM SYS.COLUMNS C
			INNER JOIN SYS.TYPES T ON C.SYSTEM_TYPE_ID  = T.SYSTEM_TYPE_ID
			WHERE OBJECT_ID = OBJECT_ID('WANF_ANEXO_FINALIZADO') AND T.NAME = 'varchar' AND (C.NAME = 'ANF_C_NOME'  OR C.NAME = 'ANF_C_NOMEARQ'))
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO ALTER COLUMN ANF_C_NOME NVARCHAR(250)
	ALTER TABLE WANF_ANEXO_FINALIZADO ALTER COLUMN ANF_C_NOMEARQ NVARCHAR(250)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WHIF_HISTORICO_FINALIZADO') IS NULL 
BEGIN
	CREATE TABLE WHIF_HISTORICO_FINALIZADO(
		HIF_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		HIF_N_PRO_N_CODIGO	INT NOT NULL,
		HIF_N_IWF_N_CODIGO	INT NOT NULL,
		HIF_N_USR_EXECUTOR	INT NOT NULL,
		HIF_N_ETA_N_CODIGO	INT NOT NULL,
		HIF_N_ETI_N_CODIGO	INT NOT NULL,
		HIF_C_STATUS		VARCHAR(30) NOT NULL,
		HIF_D_GRAVACAO		DATETIME NOT NULL,
		HIF_C_DESCRICAO		VARCHAR(250) NOT NULL,
		HIF_N_ACAOID		INT NOT NULL,
		HIF_N_TIPOACAO		INT NOT NULL,
		HIF_N_EVE_N_ID		INT NOT NULL,
		HIF_N_ATIVO			BIT NOT NULL,
		CONSTRAINT PK_WHIF_HISTORICO_FINALIZADO PRIMARY KEY CLUSTERED (HIF_N_CODIGO ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WHIS_HISTORICO_ITEM') IS NULL 
BEGIN
	CREATE TABLE WHIS_HISTORICO_ITEM(
		HIS_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		HIS_N_PRO_N_CODIGO	INT NOT NULL,
		HIS_N_IWF_N_CODIGO	INT NOT NULL,
		HIS_N_USR_EXECUTOR	INT NOT NULL,
		HIS_N_ETA_N_CODIGO	INT NOT NULL,
		HIS_N_ETI_N_CODIGO	INT NOT NULL CONSTRAINT DF_WHIS_HISTORICO_ITEM_HIS_N_ETI_N_CODIGO  DEFAULT (0),
		HIS_C_STATUS		VARCHAR(30) NOT NULL,
		HIS_D_GRAVACAO		DATETIME NOT NULL CONSTRAINT DF_WHIS_HISTORICO_ITEM_HIS_D_GRAVACAO  DEFAULT (GETDATE()),
		HIS_C_DESCRICAO		VARCHAR(250) NOT NULL,
		HIS_N_ACAOID		INT NOT NULL,
		HIS_N_TIPOACAO		INT NOT NULL,
		HIS_N_EVE_N_ID		INT NOT NULL,
		HIS_N_ATIVO			BIT NOT NULL,
		CONSTRAINT PK_WHIS_HISTORICO_ITEM PRIMARY KEY CLUSTERED (HIS_N_CODIGO ASC),
		CONSTRAINT FK_WHIS_HISTORICO_ITEM_WITE_ITEM_PROCESSO FOREIGN KEY(HIS_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW (IWF_N_CODIGO) ON DELETE CASCADE

	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WLNK_LINK') IS NULL 
BEGIN
	CREATE TABLE WLNK_LINK(
		LNK_N_CODIGO			INT IDENTITY(1,1) NOT NULL,
		LNK_N_PRO_N_CODIGO		INT NOT NULL,
		LNK_N_PART_ID			INT NOT NULL,
		LNK_N_DIRECAO			SMALLINT NOT NULL,
		LNK_C_NOME				VARCHAR(30) NOT NULL,
		LNK_N_PARENTID			INT NOT NULL,
		LNK_C_COR				VARCHAR(9) NULL,
		LNK_NOD_C_IDENTIFIER	VARCHAR(36) NULL,
		CONSTRAINT PK_WLNK_LINK PRIMARY KEY CLUSTERED (LNK_N_CODIGO ASC),
		CONSTRAINT FK_WLNK_LINK_WPRO_PROCESSO FOREIGN KEY(LNK_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WOBS_OBSERVADOR') IS NULL 
BEGIN
	CREATE TABLE WOBS_OBSERVADOR(
		OBS_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		OBS_N_PART_ID		INT NOT NULL,
		OBS_N_PRO_N_CODIGO	INT NOT NULL,
		OBS_C_NOME			VARCHAR(30) NOT NULL,
		OBS_C_LISTAACESSO	VARCHAR(100) NOT NULL CONSTRAINT DF_WOBS_OBSERVADOR_OBS_C_LISTAACESSO  DEFAULT (''),
		CONSTRAINT PK_WOBS_OBSERVADOR PRIMARY KEY CLUSTERED (OBS_N_CODIGO ASC),
		CONSTRAINT FK_WOBS_OBSERVADOR_WPRO_PROCESSO FOREIGN KEY(OBS_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WPDP_PROCESSO_DEPENDENCIAS') IS NULL 
BEGIN
	CREATE TABLE WPDP_PROCESSO_DEPENDENCIAS(
		PDP_N_CODIGO			INT IDENTITY(1,1) NOT NULL,
		PDP_N_PROCESSO_N_ID		INT NOT NULL,
		PDP_N_ID_DEPENDENTE		INT NOT NULL,
		PDP_N_TIPO_DEPENDENTE	INT NOT NULL,
		PDP_C_ALIAS				VARCHAR(50) NOT NULL,
		PDP_C_ID_ETAPA			INT NOT NULL,
		PDP_C_ID_ATIVIDADE		INT NOT NULL,
		CONSTRAINT PK_WPDP_PROCESSO_DEPENDENCIAS PRIMARY KEY CLUSTERED (PDP_N_CODIGO ASC),
		CONSTRAINT FK_WPDP_PROCESSO_DEPENDENCIAS_WPRO_PROCESSO FOREIGN KEY(PDP_N_PROCESSO_N_ID)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WPEN_PONTO_ENTRADA') IS NULL 
BEGIN
	CREATE TABLE WPEN_PONTO_ENTRADA(
		PEN_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		PEN_N_PART_ID		INT NOT NULL,
		PEN_N_PRO_N_CODIGO	INT NOT NULL,
		PEN_C_NOME			VARCHAR(30) NOT NULL,
		PEN_C_STATUS		VARCHAR(50) NOT NULL,
		PEN_N_ETA_N_CODIGO	INT NOT NULL CONSTRAINT DF_WPEN_PONTO_ENTRADA_PEN_N_ETA_N_CODIGO DEFAULT (-1),
		CONSTRAINT PK_WPEN_PONTO_ENTRADA PRIMARY KEY CLUSTERED (PEN_N_CODIGO ASC),
		CONSTRAINT FK_WPEN_PONTO_ENTRADA_WPRO_PROCESSO FOREIGN KEY(PEN_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WEVE_EVENTO') IS NULL 
BEGIN
	CREATE TABLE WEVE_EVENTO(
		EVE_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		EVE_N_PART_ID_LINK	INT NOT NULL,
		EVE_N_PRO_N_CODIGO	INT NOT NULL,
		EVE_N_ORIGEM_TIPO	INT NOT NULL,
		EVE_N_ORIGEM_ID		INT NOT NULL,
		EVE_N_SUCESSOR_TIPO	INT NOT NULL,
		EVE_N_SUCESSOR_ID	INT NOT NULL,
		EVE_C_STATUS		VARCHAR(50) NOT NULL,
		CONSTRAINT PK_WEVE_EVENTO PRIMARY KEY CLUSTERED (EVE_N_CODIGO ASC),
		CONSTRAINT FK_WEVE_EVENTO_WPRO_PROCESSO FOREIGN KEY(EVE_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WPRI_PRIORIDADE') IS NULL 
BEGIN
	CREATE TABLE WPRI_PRIORIDADE(
		PRI_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		PRI_N_PRO_N_CODIGO	INT NOT NULL,
		PRI_C_TITULO		VARCHAR(20) NOT NULL,
		PRI_N_VALOR			INT NOT NULL,
		CONSTRAINT PK_WPRI_PRIORIDADE PRIMARY KEY CLUSTERED (PRI_N_CODIGO ASC),
		CONSTRAINT FK_WPRI_PRIORIDADE_WPRO_PROCESSO FOREIGN KEY(PRI_N_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WITA_ITEM_ACESSO') IS NULL 
BEGIN
	CREATE TABLE WITA_ITEM_ACESSO(
		ITA_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ITA_N_IPR_N_CODIGO	INT NOT NULL,
		ITA_N_ETA_N_CODIGO	INT NOT NULL,
		ITA_C_ACESSO		VARCHAR(100) NOT NULL,
		CONSTRAINT PK_WITA_ITEM_ACESSO PRIMARY KEY CLUSTERED (ITA_N_CODIGO ASC),
		CONSTRAINT FK_WITA_ITEM_ACESSO_WETA_ETAPA_PROCESSO FOREIGN KEY(ITA_N_ETA_N_CODIGO)
			REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_WITA_ITEM_ACESSO_WIPR_ITEM_PROCESSO FOREIGN KEY(ITA_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WITX_ITEM_EXCLUSAO') IS NULL 
BEGIN
	CREATE TABLE WITX_ITEM_EXCLUSAO(
		ITX_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ITX_N_IPR_N_CODIGO	INT NOT NULL,
		ITX_N_ETA_N_CODIGO	INT NOT NULL,
		ITX_N_USERID		INT NOT NULL,
		CONSTRAINT PK_WITA_ITEM_EXCLUSAO PRIMARY KEY CLUSTERED (ITX_N_CODIGO ASC),
		CONSTRAINT FK_EXCLUSAO_ETAPA_PROCESSO FOREIGN KEY(ITX_N_ETA_N_CODIGO)
			REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_EXCLUSAO_ITEM_PROCESSO FOREIGN KEY(ITX_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WDEC_DECISAO') IS NULL 
BEGIN
CREATE TABLE WDEC_DECISAO(
	DEC_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
	DEC_N_PART_ID		INT NOT NULL,
	DEC_N_ETA_N_CODIGO	INT NOT NULL,
	DEC_C_NOME			VARCHAR(30) NOT NULL,
	DEC_C_STATUS		VARCHAR(50) NOT NULL,
	DEC_N_QTD_USERS		SMALLINT NOT NULL CONSTRAINT DF_WDEC_DECISAO_DEC_N_QTD_USERS DEFAULT (1),
	DEC_N_ASSINAR		BIT NOT NULL CONSTRAINT DF_WDEC_DECISAO_DEC_N_ASSINAR DEFAULT (0),
	DEC_N_ORDEM			SMALLINT NOT NULL CONSTRAINT DF_WDEC_DECISAO_DEC_N_ORDEM DEFAULT (0),
	CONSTRAINT PK_WDEC_DECISAO PRIMARY KEY CLUSTERED (DEC_N_CODIGO ASC),
	CONSTRAINT FK_WDEC_DECISAO_WETA_ETAPA_PROCESSO FOREIGN KEY(DEC_N_ETA_N_CODIGO)
		REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE
)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WWKD_WORKDAYS') IS NULL 
BEGIN
	CREATE TABLE WWKD_WORKDAYS(
		WKD_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		WKD_N_PRO_N_CODIGO	INT NOT NULL,
		WKD_N_ETA_N_CODIGO	INT NOT NULL CONSTRAINT DF_WWKD_WORKDAYS_WKD_N_ETA_N_CODIGO DEFAULT (-1),
		WKD_C_SEG_SEX_INI	VARCHAR(5) NOT NULL,
		WKD_C_SEG_SEX_FIM	VARCHAR(5) NOT NULL,
		WKD_C_SABADO_INI	VARCHAR(5) NULL,
		WKD_C_SABADO_FIM	VARCHAR(5) NULL,
		WKD_C_DOMINGO_INI	VARCHAR(5) NULL,
		WKD_C_DOMINGO_FIM	VARCHAR(5) NULL,
		CONSTRAINT PK_WWKD_WORKDAYS PRIMARY KEY CLUSTERED (WKD_N_CODIGO ASC),
		CONSTRAINT FK_WWKD_WORKDAYS_WETA_ETAPA_PROCESSO FOREIGN KEY(WKD_N_ETA_N_CODIGO)
			REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WAGI_AGENDAMENTO_ITEM') IS NULL 
BEGIN
	CREATE TABLE WAGI_AGENDAMENTO_ITEM(
		AGI_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		AGI_N_IPR_N_CODIGO	INT NOT NULL,
		AGI_N_PRZ_N_ID		INT NOT NULL,
		AGI_D_EXECUCAO		DATETIME NOT NULL,
		CONSTRAINT PK_WAGI_AGENDAMENTO_ITEM PRIMARY KEY CLUSTERED (AGI_N_CODIGO ASC),
		CONSTRAINT FK_WAGI_AGENDAMENTO_ITEM_WIPR_ITEM_PROCESSO FOREIGN KEY(AGI_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WITR_ITEM_READERS') IS NULL 
BEGIN
	CREATE TABLE WITR_ITEM_READERS(
		ITR_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ITR_N_IPR_N_CODIGO	INT NOT NULL,
		ITR_N_USR_N_ID		INT NOT NULL,
		CONSTRAINT PK_WITR_ITEM_READERS PRIMARY KEY CLUSTERED (ITR_N_CODIGO ASC),
		CONSTRAINT FK_WITR_ITEM_READERS_WIPR_ITEM_PROCESSO FOREIGN KEY(ITR_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WITR_ITEM_RESTRICAO') IS NULL 
BEGIN
	CREATE TABLE WITR_ITEM_RESTRICAO(
		ITR_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ITR_N_IPR_N_CODIGO	INT NOT NULL,
		ITR_N_ACAOID		INT NOT NULL,
		ITR_N_ACAOTIPO		INT NOT NULL,
		ITR_C_RESTRICAO		VARCHAR(50) NOT NULL,
		CONSTRAINT PK_WITR_ITEM_RESTRICAO PRIMARY KEY CLUSTERED (ITR_N_CODIGO ASC),
		CONSTRAINT FK_WITR_ITEM_RESTRICAO_WIPR_ITEM_PROCESSO FOREIGN KEY(ITR_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WEVP_EVENTO_PENDENTE') IS NULL 
BEGIN
CREATE TABLE WEVP_EVENTO_PENDENTE(
	EVP_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
	EVP_N_IPR_N_CODIGO	INT NOT NULL,
	EVP_N_TRIGGERID		INT NOT NULL,
	EVP_N_PENDINGID		INT NOT NULL,
	EVP_N_ETI_N_CODIGO	INT NOT NULL,
	EVP_N_ETA_N_CODIGO	INT NOT NULL,
	CONSTRAINT PK_WEVP_EVENTO_PENDENTE PRIMARY KEY CLUSTERED (EVP_N_CODIGO ASC),
	CONSTRAINT FK_WEVP_EVENTO_PENDENTE_WIPR_ITEM_PROCESSO FOREIGN KEY(EVP_N_IPR_N_CODIGO)
		REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WNOD_NODE') IS NULL
BEGIN
	CREATE TABLE WNOD_NODE(
		NOD_N_ID			INT IDENTITY(1,1),
		NOD_PRO_N_CODIGO	INT NOT NULL,
		NOD_ATV_N_CODIGO	INT NOT NULL,
		NOD_C_TITLE			VARCHAR(200) NOT NULL,
		NOD_MOD_C_ITEMID	VARCHAR(36) NOT NULL,
		NOD_N_X				INT NOT NULL,
		NOD_N_Y				INT NOT NULL,
		NOD_B_HIDEGPS		BIT NOT NULL DEFAULT 0,
		NOD_C_DESCRIPTION	VARCHAR(2000) NULL,
		NOD_B_CONFIGURED	BIT NOT NULL DEFAULT 0,
		CONSTRAINT PK_WNOD_NODE PRIMARY KEY (NOD_N_ID),
		CONSTRAINT FK_NOD_PRO_N_CODIGO FOREIGN KEY (NOD_PRO_N_CODIGO)
			REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WNOP_NODEPORT') IS NULL
BEGIN
	CREATE TABLE WNOP_NODEPORT(
		NOP_N_ID			INT IDENTITY(1,1),
		NOP_NOD_N_ID		INT NOT NULL,
		NOP_C_TITLE			VARCHAR(200) NULL,
		NOP_N_MAXLINKS		INT NOT NULL,
		NOP_B_INPUTPORT		BIT NOT NULL,
		NOP_ATS_N_CODIGO	INT NOT NULL DEFAULT 0,
		CONSTRAINT PK_WNOP_NODEPORT PRIMARY KEY (NOP_N_ID),
		CONSTRAINT FK_NOP_NOD_N_ID FOREIGN KEY (NOP_NOD_N_ID)
			REFERENCES WNOD_NODE (NOD_N_ID) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WNOL_NODELINK') IS NULL
BEGIN
	CREATE TABLE WNOL_NODELINK (
		NOL_N_ID					INT IDENTITY(1,1),
		NOL_EVE_N_CODIGO			INT NOT NULL,
		NOL_ORIGIN_NOP_N_ID			INT NOT NULL,
		NOL_DESTINATION_NOP_N_ID	INT NOT NULL,
		NOL_C_COLOR					VARCHAR(10) NULL,
		NOL_C_TITLE					VARCHAR(200) NULL,
		CONSTRAINT PK_WNOL_NODELINK PRIMARY KEY (NOL_N_ID),
		CONSTRAINT FK_NOL_ORIGIN_NOP_N_ID FOREIGN KEY (NOL_ORIGIN_NOP_N_ID)
			REFERENCES WNOP_NODEPORT (NOP_N_ID) ON DELETE CASCADE
	)

END
GO

--#####################################################################################################################

IF OBJECT_ID('WIVU_ITEM_USERS') IS NULL
BEGIN
	CREATE TABLE WIVU_ITEM_USERS(
		IVU_N_CODIGO INT IDENTITY(1,1) NOT NULL,
		IVU_N_USR_N_ID INT NOT NULL,
		IVU_N_IWF_N_CODIGO INT NOT NULL,
		CONSTRAINT PK_WIVU_ITEM_USERS PRIMARY KEY CLUSTERED (IVU_N_CODIGO ASC),
		CONSTRAINT FK_WIVU_ITEM_USERS_WIWF_ITEM_WORKFLOW FOREIGN KEY(IVU_N_IWF_N_CODIGO) 
			REFERENCES WIWF_ITEM_WORKFLOW (IWF_N_CODIGO) ON DELETE CASCADE


	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WIEX_ITEM_EXECUCAO') IS NULL
BEGIN
	CREATE TABLE WIEX_ITEM_EXECUCAO(
		IEX_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		IEX_N_IPR_N_CODIGO	INT NOT NULL,
		IEX_N_USR_N_ID		INT NOT NULL,
		IEX_N_ETI_N_CODIGO	INT NOT NULL,
		IEX_N_ETA_N_CODIGO	INT NOT NULL,
		IEX_D_EXECUCAO		DATETIME NOT NULL,
		IEX_N_ACAOID		INT NOT NULL,
		IEX_N_TIPOACAO		INT NOT NULL,
		IEX_N_EVE_N_ID		INT NOT NULL,
		IEX_C_RETURN		VARCHAR(50) NULL,
		CONSTRAINT PK_WIEX_ITEM_EXECUCAO PRIMARY KEY CLUSTERED (IEX_N_CODIGO ASC),
		CONSTRAINT FK_WIEX_ITEM_EXECUCAO_WIPR_ITEM_PROCESSO FOREIGN KEY(IEX_N_IPR_N_CODIGO) 
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WIRF_ITEM_READERS_FINALIZADO') IS NULL
BEGIN
	CREATE TABLE WIRF_ITEM_READERS_FINALIZADO(
		IRF_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		IRF_N_IPR_N_CODIGO	INT NOT NULL,
		IRF_N_USR_N_ID		INT NOT NULL,
		CONSTRAINT PK_WIRF_ITEM_READERS_FINALIZADO PRIMARY KEY CLUSTERED (IRF_N_CODIGO ASC)
	)
END

--#####################################################################################################################

IF OBJECT_ID('WFESP_ESTATISTICA_PROCESSO') IS NULL
BEGIN
	CREATE TABLE WFESP_ESTATISTICA_PROCESSO(
		ESP_N_ID			INT IDENTITY(1,1) NOT NULL,
		ESP_N_PRO_N_CODIGO	INT NOT NULL,
		ESP_N_IPR_N_CODIGO	INT NOT NULL,
		ESP_D_INICIO		DATETIME NOT NULL,
		ESP_D_FIM			DATETIME NOT NULL,
		ESP_N_PRAZOFULL		FLOAT NOT NULL,
		ESP_N_PRAZOREAL		FLOAT NOT NULL,
		ESP_N_EXECID		INT NOT NULL,
		ESP_C_EXECNAME		VARCHAR(255) NULL,
		ESP_N_ETS_CODIGO    INT NOT NULL,
		CONSTRAINT PK_WFESP_ESTATISTICA_PROCESSO PRIMARY KEY CLUSTERED (ESP_N_ID ASC),
		CONSTRAINT FK_ESP__ETS FOREIGN KEY (ESP_N_ETS_CODIGO) REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WFESE_ESTATISTICA_ETAPA') IS NULL
BEGIN
	CREATE TABLE WFESE_ESTATISTICA_ETAPA(
		ESE_N_ID			INT IDENTITY(1,1) NOT NULL,
		ESE_N_PRO_N_CODIGO	INT NOT NULL,
		ESE_N_IPR_N_CODIGO	INT NOT NULL,
		ESE_N_ETA_N_CODIGO	INT NOT NULL,
		ESE_D_INICIO		DATETIME NOT NULL,
		ESE_D_FIM			DATETIME NOT NULL,
		ESE_N_PRAZOFULL		FLOAT NOT NULL,
		ESE_N_PRAZOREAL		FLOAT NOT NULL,
		ESE_N_EXECID		INT NULL,
		ESE_C_EXECNAME		VARCHAR(80) NULL,
		ESE_N_ETS_CODIGO	INT NOT NULL,
		CONSTRAINT PK_WFESE_ESTATISTICA_ETAPA PRIMARY KEY CLUSTERED (ESE_N_ID ASC),
		CONSTRAINT FK_WFESE_ESTATISTICA_ETAPA_WETA_ETAPA_PROCESSO FOREIGN KEY(ESE_N_ETA_N_CODIGO) REFERENCES WETA_ETAPA_PROCESSO (ETA_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_ESE__ETS FOREIGN KEY (ESE_N_ETS_CODIGO) REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WETC_ETAPA_CONDENSADOR') IS NULL
BEGIN
	CREATE TABLE WETC_ETAPA_CONDENSADOR(
		ETC_N_ID			INT IDENTITY(1,1) NOT NULL,
		ETC_N_ETA_N_CODIGO	INT NULL,
		ETC_N_NOD_N_ID		INT NOT NULL,
		CONSTRAINT PK_WETC_ETAPA_CONDENSADOR PRIMARY KEY CLUSTERED (ETC_N_ID ASC),
		CONSTRAINT FK_WETC_ETAPA_CONDENSADOR_WNOD_NODE FOREIGN KEY (ETC_N_NOD_N_ID)
			REFERENCES WNOD_NODE (NOD_N_ID) ON DELETE CASCADE
	)    
END

--ADAPTACAO PARA QUE UMA ATIVIDADE TENHA MULTIPLOS ANEXOS
--#####################################################################################################################
IF OBJECT_ID('WATX_ATIVIDADE_ANEXO') IS NULL 
BEGIN
	CREATE TABLE WATX_ATIVIDADE_ANEXO(
		ATX_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		ATX_ATV_N_CODIGO    INT NOT NULL,
		ATX_C_NOME			VARCHAR(200) NOT NULL,
		ATX_C_FORMATOANEXO	VARCHAR(MAX) NULL,
		ATX_C_ALIASANEXO	VARCHAR(200) NULL,
		ATX_N_TIPOANEXO	    INT NOT NULL,
		CONSTRAINT PK_WATX_ATIVIDADE_ANEXO PRIMARY KEY CLUSTERED (ATX_N_CODIGO ASC),
		CONSTRAINT FK_ATIVIDADE_ANEXO FOREIGN KEY(ATX_ATV_N_CODIGO)
			REFERENCES WATV_ATIVIDADE (ATV_N_CODIGO) ON DELETE CASCADE
	)
END
GO

IF EXISTS (SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('WATV_ATIVIDADE') AND NAME = 'ATV_C_FORMATOANEXO')
BEGIN
	begin tran
	SET NOCOUNT ON
	DECLARE @UPDQUERY VARCHAR(450)
	SET @UPDQUERY = 'INSERT INTO WATX_ATIVIDADE_ANEXO (ATX_ATV_N_CODIGO,ATX_C_NOME,ATX_C_FORMATOANEXO,ATX_C_ALIASANEXO,ATX_N_TIPOANEXO)
					 SELECT ATV_N_CODIGO,ATV_C_NOME,ATV_C_FORMATOANEXO,ATV_C_ALIASANEXO,3 FROM WATV_ATIVIDADE  
					 WHERE CONVERT(VARCHAR,ATV_C_FORMATOANEXO) <> '''''
	EXEC (@UPDQUERY)


	UPDATE WATX_ATIVIDADE_ANEXO SET ATX_N_TIPOANEXO = 1 WHERE ATX_C_FORMATOANEXO = '<FILE/>'

	ALTER TABLE WATV_ATIVIDADE DROP COLUMN ATV_C_ALIASANEXO,ATV_C_FORMATOANEXO
	SET NOCOUNT OFF
	commit
END
GO

--#####################################################################################################################

IF OBJECT_ID('WIMG_ITEM_MESSAGE') IS NULL
BEGIN
	CREATE TABLE WIMG_ITEM_MESSAGE(
		IMG_N_ID			INT IDENTITY(1,1) NOT NULL,
		IMG_IPR_N_CODIGO	INT NULL,
		IMG_C_SUBJECT		VARCHAR(50) NOT NULL,
		IMG_C_MESSAGE		VARCHAR(MAX) NOT NULL,
		IMG_N_SENDER		INT NOT NULL,
		IMG_C_SENDERSTEP	VARCHAR(50) NOT NULL,
		IMG_C_RECIPIENT		VARCHAR(150) NOT NULL,
		IMG_C_CARBONCOPY	VARCHAR(150) NOT NULL,
		IMG_D_DATECREATED	DATETIME NOT NULL,
		IMG_IMG_N_ID		INT DEFAULT (0) NULL,
		IMG_PRO_N_CODIGO	INT NOT NULL,
		CONSTRAINT PK_WIMG_ITEM_MESSAGE PRIMARY KEY CLUSTERED (IMG_N_ID ASC),
		CONSTRAINT FK_WIMG_ITEM_MESSAGE_WIPR_ITEM_PROCESSO FOREIGN KEY (IMG_IPR_N_CODIGO) REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE,
		CONSTRAINT FK_WIMG_ITEM_MESSAGE_WPRO_PROCESSO FOREIGN KEY (IMG_PRO_N_CODIGO) REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
	)    
END
GO


--#####################################################################################################################
-- NOVA TABELA PARA ARMAZENAR INFORMACOES DO SUBPROCESSO
--#####################################################################################################################


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_FINALIZADO'))
BEGIN
	ALTER TABLE WHIF_HISTORICO_FINALIZADO ADD HIF_C_IDENTIFICADOR VARCHAR(500) NULL
END
GO


DECLARE @ISMIGRATION BIT = 0
IF OBJECT_ID('WISP_ITEM_SUBPROCESS') IS NULL
BEGIN
	SET @ISMIGRATION = 1
	CREATE TABLE WISP_ITEM_SUBPROCESS(
		ISP_N_ID INT IDENTITY(1,1) NOT NULL,
		ISP_N_IPR_N_CODIGO INT NOT NULL,
		ISP_N_PARENTISP_ID INT NOT NULL,
		ISP_ATV_N_CODIGO INT NOT NULL,
		ISP_C_IDENTIFIER VARCHAR(300) NULL,
		ISP_C_TITLE VARCHAR(200) NULL,
		ISP_C_METADATA VARCHAR(MAX) NULL,
	CONSTRAINT PK_WISP_ITEM_SUBPROCESS PRIMARY KEY CLUSTERED (ISP_N_ID ASC)
	)
END

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_APELIDOETAPA' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD
		ETI_C_APELIDOETAPA VARCHAR(150) NULL
END

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_METADATA' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD
		ETI_C_METADATA VARCHAR(MAX) NULL
END

--PARA O SCRIPT FICAR SEMPRE FUNCIONANDO TEM QUE CRIAR TODOS OS CAMPOS QUE VAI ELIMINAR NA MIGRACAO
--ISSO SO DEVE SER FEITO QUANDO AINDA NAO MIGROU
IF @ISMIGRATION = 1
BEGIN 
	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
	BEGIN
		ALTER TABLE WETI_ETAPA_ITEM ADD
			ETI_C_IDENTIFICADOR VARCHAR(500) NULL
	END


	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_SUBTITLE' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
	BEGIN
		ALTER TABLE WETI_ETAPA_ITEM ADD
			ETI_C_SUBTITLE VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANX_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WANX_ANEXO_ITEM'))
	BEGIN
		ALTER TABLE WANX_ANEXO_ITEM ADD
			ANX_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANX_C_SUBTITULO' AND OBJECT_ID = OBJECT_ID('WANX_ANEXO_ITEM'))
	BEGIN
		ALTER TABLE WANX_ANEXO_ITEM ADD
			ANX_C_SUBTITULO VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ITR_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WITR_ITEM_RESTRICAO'))
	BEGIN
		ALTER TABLE WITR_ITEM_RESTRICAO ADD
			ITR_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ITA_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WITA_ITEM_ACESSO'))
	BEGIN
		ALTER TABLE WITA_ITEM_ACESSO ADD
			ITA_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIS_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WHIS_HISTORICO_ITEM'))
	BEGIN
		ALTER TABLE WHIS_HISTORICO_ITEM ADD
			HIS_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIS_C_SUBTITULO' AND OBJECT_ID = OBJECT_ID('WHIS_HISTORICO_ITEM'))
	BEGIN
		ALTER TABLE WHIS_HISTORICO_ITEM ADD
			HIS_C_SUBTITULO VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_C_SUBTITULO' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_FINALIZADO'))
	BEGIN
		ALTER TABLE WHIF_HISTORICO_FINALIZADO ADD
			HIF_C_SUBTITULO VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IEX_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WIEX_ITEM_EXECUCAO'))
	BEGIN
		ALTER TABLE WIEX_ITEM_EXECUCAO ADD
			IEX_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANF_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WANF_ANEXO_FINALIZADO'))
	BEGIN
		ALTER TABLE WANF_ANEXO_FINALIZADO ADD
			ANF_C_IDENTIFICADOR VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANF_C_SUBTITULO' AND OBJECT_ID = OBJECT_ID('WANF_ANEXO_FINALIZADO'))
	BEGIN
		ALTER TABLE WANF_ANEXO_FINALIZADO ADD
			ANF_C_SUBTITULO VARCHAR(500) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_ANTECESSORES' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
	BEGIN
		ALTER TABLE WETI_ETAPA_ITEM ADD	ETI_C_ANTECESSORES VARCHAR(MAX) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_IWF_C_NOME' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
	BEGIN
		ALTER TABLE WETI_ETAPA_ITEM 
			ADD	
				ETI_IWF_C_NOME		VARCHAR(80) NULL,
				ETI_IWF_C_STATUS	VARCHAR(50) NULL,
				ETI_IWF_C_PARAM1	VARCHAR(MAX) NULL,
				ETI_IWF_C_PARAM2	VARCHAR(MAX) NULL,
				ETI_IWF_C_PARAM3	VARCHAR(MAX) NULL,
				ETI_IWF_C_PARAM4	VARCHAR(MAX) NULL,
				ETI_IWF_C_PARAM5	VARCHAR(MAX) NULL
	END

	IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ITX_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WITX_ITEM_EXCLUSAO'))
	BEGIN
		ALTER TABLE WITX_ITEM_EXCLUSAO ADD
			ITX_C_IDENTIFICADOR VARCHAR(500) NULL
	END
END
GO

--#####################################################################################################################

IF EXISTS (SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('WIMG_ITEM_MESSAGE') AND NAME = 'IMG_IPR_N_CODIGO' AND is_nullable = 0)
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE ALTER COLUMN IMG_IPR_N_CODIGO INT NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMG_PRO_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WIMG_ITEM_MESSAGE'))
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE ADD IMG_PRO_N_CODIGO INT NOT NULL CONSTRAINT DF_IMG_PRO DEFAULT(0)
END
GO

SET NOCOUNT ON
IF NOT OBJECT_ID('DF_IMG_PRO') IS NULL
BEGIN
	UPDATE M
	SET M.IMG_PRO_N_CODIGO = P.IPR_N_PRO_N_CODIGO
	FROM WIMG_ITEM_MESSAGE M
	INNER JOIN WIPR_ITEM_PROCESSO P ON M.IMG_IPR_N_CODIGO = P.IPR_N_CODIGO

	ALTER TABLE WIMG_ITEM_MESSAGE DROP CONSTRAINT DF_IMG_PRO
END 
SET NOCOUNT OFF
GO

IF OBJECT_ID('FK_WIMG_ITEM_MESSAGE_WPRO_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE ADD CONSTRAINT FK_WIMG_ITEM_MESSAGE_WPRO_PROCESSO FOREIGN KEY (IMG_PRO_N_CODIGO) REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
END 
GO

--#####################################################################################################################

IF OBJECT_ID('WIMR_ITEM_MESSAGE_READERS') IS NULL
BEGIN
	CREATE TABLE WIMR_ITEM_MESSAGE_READERS(
		IMR_N_ID			INT IDENTITY(1,1) NOT NULL,
		IMR_USR_N_ID		INT NOT NULL,
		IMR_IMG_N_ID		INT NOT NULL,
		IMR_B_ISRECIPIENT	BIT NOT NULL,
		IMR_B_READ			BIT NOT NULL,
		IMR_B_LIKED			BIT NOT NULL,
		IMR_B_FLAGGED		BIT NOT NULL,
		CONSTRAINT PK_WIMR_ITEM_MESSAGE_READERS PRIMARY KEY CLUSTERED (IMR_N_ID ASC)
	)    
END

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMR_IPR_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WIMR_ITEM_MESSAGE_READERS'))
BEGIN
	ALTER TABLE WIMR_ITEM_MESSAGE_READERS DROP COLUMN IMR_IPR_N_CODIGO 
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMR_B_LIKED' AND OBJECT_ID = OBJECT_ID('WIMR_ITEM_MESSAGE_READERS'))
BEGIN
	ALTER TABLE WIMR_ITEM_MESSAGE_READERS ADD 
		IMR_B_LIKED BIT NOT NULL DEFAULT (0),
		IMR_B_FLAGGED BIT NOT NULL DEFAULT (0)		
END
GO

--#####################################################################################################################

IF OBJECT_ID('WZCF_ZURI_CONFIGURATION') IS NULL 
BEGIN
	CREATE TABLE WZCF_ZURI_CONFIGURATION (
		ZCF_N_ID			INT IDENTITY(1,1) NOT NULL,
		ZCF_C_CONFIGITEM	VARCHAR(50) NOT NULL,
		ZCF_C_CONFIGALIAS	VARCHAR(50) NULL,
		ZCF_N_CONFIGID		INT NOT NULL,
		ATC_C_CONFIGURATION	TEXT NOT NULL
		CONSTRAINT PK_ZCF_ZURI_CONFIGURATION PRIMARY KEY CLUSTERED (ZCF_N_ID ASC)
	)
END
GO

--#####################################################################################################################

IF OBJECT_ID('WMKR_MARKER') IS NULL 
BEGIN
	CREATE TABLE WMKR_MARKER(
		MKR_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		MKR_NOD_N_ID		INT NOT NULL,
		MKR_C_NAME			VARCHAR(100) NOT NULL,
		MKR_C_VALUE			VARCHAR(500) NOT NULL,
		MKR_N_ITEMTYPE		INT NOT NULL,
		MKR_PRO_N_CODIGO	INT NOT NULL,
		MKR_N_ITEMID		INT NOT NULL,
		MKR_C_IDENTIFIER	VARCHAR(36) NULL,
		CONSTRAINT PK_WMKR_MARKER PRIMARY KEY CLUSTERED (MKR_N_CODIGO ASC),
		CONSTRAINT FK_WMKR_MARKER FOREIGN KEY(MKR_NOD_N_ID)
			REFERENCES WNOD_NODE (NOD_N_ID) ON DELETE CASCADE
	)
END
GO


--#####################################################################################################################
IF OBJECT_ID('WIMI_ITEM_METAINFO') IS NULL
BEGIN
	CREATE TABLE WIMI_ITEM_METAINFO(
		IMI_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		IMI_N_PROCESSID		INT NOT NULL,
		IMI_C_IDENTIFIER	VARCHAR(50) NOT NULL,
		IMI_C_FIELDNAME		VARCHAR(250) NOT NULL,
		CONSTRAINT PK_WIMI_ITEM_METAINFO PRIMARY KEY CLUSTERED (IMI_N_CODIGO ASC)
	)
END
GO


--#####################################################################################################################

IF OBJECT_ID('WPHM_PUSH_MESSAGE') IS NULL
BEGIN
CREATE TABLE WPHM_PUSH_MESSAGE(
	PHM_N_ID			INT	IDENTITY(1,1),
	PHM_ETI_N_ID		INT NOT NULL,
	PHM_USD_N_ID		INT NOT NULL,
	PHM_D_DATE_SEND		DATETIME,
	PHM_N_COUNT_RETRY	INT NOT NULL,
	PHM_C_MESSAGE		VARCHAR(4000),
	CONSTRAINT PK_WPHM_PUSH_MESSAGE PRIMARY KEY CLUSTERED (PHM_N_ID ASC),
	CONSTRAINT FK_WPHM_WETI FOREIGN KEY (PHM_ETI_N_ID)
		REFERENCES WETI_ETAPA_ITEM (ETI_N_CODIGO) ON DELETE CASCADE,
	CONSTRAINT FK_WPHM_WFUSD FOREIGN KEY(PHM_USD_N_ID)
		REFERENCES WFUSD_USERDEVICE (USD_N_ID) ON DELETE CASCADE
)
END
GO

--#####################################################################################################################
--***** ITEM FINALIZADO CREATE TABLES
--#####################################################################################################################

IF OBJECT_ID('WIWF_ITEM_WORKFLOW_FINALIZADO') IS NULL 
BEGIN
	CREATE TABLE WIWF_ITEM_WORKFLOW_FINALIZADO(
		IWF_N_CODIGO		INT NOT NULL,
		IWF_C_NOME			VARCHAR(80) NOT NULL,
		IWF_C_STATUS		VARCHAR(50) NOT NULL,
		IWF_D_DATAINICIO	DATETIME NOT NULL,
		IWF_N_READONLY		BIT NOT NULL,
		IWF_N_USU_OWNER		INT NOT NULL,
		IWF_N_ARE_ORIGEM	INT NOT NULL,
		IWF_N_ITE_ORIGEM	INT NOT NULL,
		IWF_N_PRO_ORIGEM	INT NOT NULL,
		IWF_D_DATAFIM		DATETIME NULL,
		IWF_C_PARAM1		VARCHAR(MAX) NULL,
		IWF_C_PARAM2		VARCHAR(MAX) NULL,
		IWF_C_PARAM3		VARCHAR(MAX) NULL,
		IWF_C_PARAM4		VARCHAR(MAX) NULL,
		IWF_C_PARAM5		VARCHAR(MAX) NULL,
		IWF_C_METADATA		VARCHAR(MAX) NULL,
		CONSTRAINT PK_ITEMWORKFLOW_FINALIZADO PRIMARY KEY CLUSTERED (IWF_N_CODIGO ASC)
	)
END
GO

IF OBJECT_ID('WIPR_ITEM_PROCESSO_FINALIZADO') IS NULL 
BEGIN
	CREATE TABLE WIPR_ITEM_PROCESSO_FINALIZADO(
		IPR_N_CODIGO		INT NOT NULL,
		IPR_N_IWF_N_CODIGO	INT NOT NULL,
		IPR_N_PRO_N_CODIGO	INT NOT NULL,
		IPR_N_COUNTERID		INT NOT NULL,
		IPR_N_PRIORIDADE	INT NOT NULL,
		IPR_D_DATAINICIO	DATETIME NOT NULL,
		IPR_C_STATUSCOLOR	VARCHAR(10) NOT NULL,
		IPR_N_FINALIZADO	BIT NOT NULL,
		IPR_C_LISTAACESSO	VARCHAR(100) NULL,
		IPR_N_LOCALIDADE	INT NOT NULL,
		IPR_C_METADATA		TEXT NULL,
		IPR_D_SLAFINAL		DATETIME NULL,
		IPR_N_CURRENTSLA	INT NOT NULL,
		CONSTRAINT PK_ITEMPROCESSO_FINALIZADO PRIMARY KEY CLUSTERED (IPR_N_CODIGO ASC),
		CONSTRAINT FK_ITEMPROCESSO_ITEMWORKFLOW_FINALIZADO FOREIGN KEY(IPR_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW_FINALIZADO (IWF_N_CODIGO) ON DELETE CASCADE
	)
END
GO

IF OBJECT_ID('WIMG_ITEM_MESSAGE_FINALIZADO') IS NULL
BEGIN
	CREATE TABLE WIMG_ITEM_MESSAGE_FINALIZADO(
		IMG_N_ID			INT NOT NULL,
		IMG_IPR_N_CODIGO	INT NULL,
		IMG_C_SUBJECT		VARCHAR(50) NOT NULL,
		IMG_C_MESSAGE		VARCHAR(MAX) NOT NULL,
		IMG_N_SENDER		INT NOT NULL,
		IMG_C_SENDERSTEP	VARCHAR(50) NOT NULL,
		IMG_C_RECIPIENT		VARCHAR(150) NOT NULL,
		IMG_C_CARBONCOPY	VARCHAR(150) NOT NULL,
		IMG_D_DATECREATED	DATETIME NOT NULL,
		IMG_IMG_N_ID		INT DEFAULT (0) NULL,
		IMG_PRO_N_CODIGO	INT NOT NULL,
		CONSTRAINT PK_ITEMMESSAGE_FINALIZADO PRIMARY KEY CLUSTERED (IMG_N_ID ASC)
	)    
END
GO

IF EXISTS (SELECT 1 FROM SYS.columns WHERE OBJECT_ID = OBJECT_ID('WIMG_ITEM_MESSAGE_FINALIZADO') AND NAME = 'IMG_IPR_N_CODIGO' AND is_nullable = 0)
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO ALTER COLUMN IMG_IPR_N_CODIGO INT NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMG_PRO_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WIMG_ITEM_MESSAGE_FINALIZADO'))
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO ADD IMG_PRO_N_CODIGO INT NOT NULL CONSTRAINT DF_IMG_FIN_PRO DEFAULT(0)
END
GO
SET NOCOUNT ON
IF NOT OBJECT_ID('DF_IMG_FIN_PRO') IS NULL
BEGIN
	UPDATE M
	SET M.IMG_PRO_N_CODIGO = P.IPR_N_PRO_N_CODIGO
	FROM WIMG_ITEM_MESSAGE_FINALIZADO M
	INNER JOIN WIPR_ITEM_PROCESSO P ON M.IMG_IPR_N_CODIGO = P.IPR_N_CODIGO

	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO DROP CONSTRAINT DF_IMG_FIN_PRO
END 
SET NOCOUNT OFF
GO


IF NOT OBJECT_ID('WIMR_ITEM_MESSAGE_READERS_FINALIZADO') IS NULL
BEGIN
	EXEC SP_RENAME 'WIMR_ITEM_MESSAGE_READERS_FINALIZADO', 'WIMR_ITEM_MSG_RDRS_FIM'
END
GO

IF OBJECT_ID('WIMR_ITEM_MSG_RDRS_FIM') IS NULL
BEGIN
	CREATE TABLE WIMR_ITEM_MSG_RDRS_FIM(
		IMR_N_ID			INT NOT NULL,
		IMR_USR_N_ID		INT NOT NULL,
		IMR_IMG_N_ID		INT NOT NULL,
		IMR_B_ISRECIPIENT	BIT NOT NULL,
		IMR_B_READ			BIT NOT NULL,
		IMR_B_LIKED			BIT NOT NULL,
		IMR_B_FLAGGED		BIT NOT NULL,
		CONSTRAINT PK_ITEMMESSAGE_READERS_FINALIZADO PRIMARY KEY CLUSTERED (IMR_N_ID ASC)
	)    
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMR_IPR_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WIMR_ITEM_MSG_RDRS_FIM'))
BEGIN
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM DROP COLUMN IMR_IPR_N_CODIGO 
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IMR_B_LIKED' AND OBJECT_ID = OBJECT_ID('WIMR_ITEM_MSG_RDRS_FIM'))
BEGIN
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM ADD 
		IMR_B_LIKED BIT NOT NULL DEFAULT (0),
		IMR_B_FLAGGED BIT NOT NULL DEFAULT (0)		
END
GO
--#####################################################################################################################
IF OBJECT_ID('WPVW_PROCESSGPSVIEW') IS NULL
BEGIN

CREATE TABLE WPVW_PROCESSGPSVIEW (
	PVW_N_ID INT IDENTITY,
	PVW_C_IDENTIFIER VARCHAR(36) NOT NULL CONSTRAINT DF_PVW_C_IDENTIFIER DEFAULT newid(),
	PVW_PRO_N_CODIGO INT NOT NULL,
	PVW_C_NAME VARCHAR(255) NOT NULL,
	PVW_C_ACCESSLIST VARCHAR(100) NULL,
	PVW_C_CONFIG VARCHAR(MAX) NOT NULL,
	PVW_C_PROVIDER VARCHAR(36) NOT NULL,
	PVW_N_PRIORITY INT NOT NULL,
	CONSTRAINT PK_PROCESSVIEW PRIMARY KEY (PVW_N_ID),
	CONSTRAINT FK_PVW__PRO FOREIGN KEY (PVW_PRO_N_CODIGO) REFERENCES WPRO_PROCESSO (PRO_N_CODIGO) ON DELETE CASCADE
)
END
GO


IF OBJECT_ID('WMRS_MARKER_RESULT') IS NULL 
BEGIN
	CREATE TABLE WMRS_MARKER_RESULT(
		MRS_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		MRS_IWF_N_CODIGO	INT NOT NULL,
		MRS_IPR_N_CODIGO	INT NOT NULL,
		MRS_ISP_N_ID     	INT NOT NULL,
		MRS_PRO_N_CODIGO	INT NOT NULL,
		MRS_N_USR_EXEC_ID	INT NOT NULL,
		MRS_D_EXEC_DATE		DATETIME NOT NULL,
		MRS_MKR_C_NAME	VARCHAR(100) NOT NULL,
		MRS_MKR_C_VALUE	VARCHAR(500) NOT NULL,
		CONSTRAINT PK_WMRS_MARKER_RESULT PRIMARY KEY CLUSTERED (MRS_N_CODIGO ASC),
		CONSTRAINT FK_ITEM_PROCESSO_MARKER FOREIGN KEY(MRS_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

IF OBJECT_ID('WMRS_MARKER_RESULT_FINISHED') IS NULL 
BEGIN
	CREATE TABLE WMRS_MARKER_RESULT_FINISHED(
		MRS_N_CODIGO		INT IDENTITY(1,1) NOT NULL,
		MRS_IWF_N_CODIGO	INT NOT NULL,
		MRS_IPR_N_CODIGO	INT NOT NULL,
		MRS_ISP_N_ID     	INT NOT NULL,
		MRS_PRO_N_CODIGO	INT NOT NULL,
		MRS_N_USR_EXEC_ID	INT NOT NULL,
		MRS_D_EXEC_DATE		DATETIME NOT NULL,
		MRS_MKR_C_NAME	VARCHAR(100) NOT NULL,
		MRS_MKR_C_VALUE	VARCHAR(500) NOT NULL,
		CONSTRAINT PK_WMRS_MKR_RES_FINISHED PRIMARY KEY CLUSTERED (MRS_N_CODIGO ASC),
		CONSTRAINT FK_ITEM_PROCESSO_FIN_MARKER FOREIGN KEY(MRS_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END
GO

IF OBJECT_ID('WISP_ITEM_SUBPROCESS_FINALIZADO') IS NULL
BEGIN
	CREATE TABLE WISP_ITEM_SUBPROCESS_FINALIZADO(
		ISP_N_ID INT NOT NULL,
		ISP_N_IPR_N_CODIGO INT NOT NULL,
		ISP_N_PARENTISP_ID INT NOT NULL,
		ISP_ATV_N_CODIGO INT NOT NULL,
		ISP_C_IDENTIFIER VARCHAR(300) NULL,
		ISP_C_TITLE VARCHAR(200) NULL,
		ISP_C_METADATA VARCHAR(MAX) NULL,
	CONSTRAINT PK_WISP_ITEM_SUBPROCESSFINAL PRIMARY KEY CLUSTERED (ISP_N_ID ASC),
	CONSTRAINT FK_SUBPROCESS_ITEMF FOREIGN KEY(ISP_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
	)
END


SET NOCOUNT ON
IF OBJECT_ID('WHIF_HISTORICO_ARQUIVADO') IS NULL 
BEGIN
	CREATE TABLE WHIF_HISTORICO_ARQUIVADO(
		HIF_N_CODIGO int IDENTITY(1,1) NOT NULL,
		HIF_N_PRO_N_CODIGO int NOT NULL,
		HIF_N_IWF_N_CODIGO int NOT NULL,
		HIF_N_USR_EXECUTOR int NOT NULL,
		HIF_N_ETA_N_CODIGO int NOT NULL,
		HIF_N_ETI_N_CODIGO int NOT NULL,
		HIF_C_STATUS varchar(30)   NOT NULL,
		HIF_D_GRAVACAO datetime NOT NULL,
		HIF_C_DESCRICAO varchar(250)   NOT NULL,
		HIF_N_ACAOID int NOT NULL,
		HIF_N_TIPOACAO int NOT NULL,
		HIF_N_EVE_N_ID int NOT NULL,
		HIF_N_ATIVO bit NOT NULL,
		HIF_ISP_N_ID varchar(500) NULL
		CONSTRAINT PK_HISTORICO_ARQUIVADO PRIMARY KEY CLUSTERED (HIF_N_CODIGO ASC)
	)
END
SET NOCOUNT OFF
GO 

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_ARQUIVADO'))
BEGIN
	ALTER TABLE WHIF_HISTORICO_ARQUIVADO ADD HIF_C_IDENTIFICADOR VARCHAR(500) NULL
END
GO

--#####################################################################################################################
--***** ALTER TABLES **************************************************************************************************
--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MRS_ETI_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WMRS_MARKER_RESULT'))
BEGIN
	ALTER TABLE WMRS_MARKER_RESULT ADD MRS_ETI_N_CODIGO INT NULL
	ALTER TABLE WMRS_MARKER_RESULT_FINISHED ADD MRS_ETI_N_CODIGO INT NULL
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE WMRS_MARKER_RESULT SET MRS_ETI_N_CODIGO = 0'
	EXEC (@UPDQUERY)
	SET @UPDQUERY = 'UPDATE WMRS_MARKER_RESULT_FINISHED SET MRS_ETI_N_CODIGO = 0'
	EXEC (@UPDQUERY)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ISP_N_LOOPITEM' AND OBJECT_ID = OBJECT_ID('WISP_ITEM_SUBPROCESS'))
BEGIN
	ALTER TABLE WISP_ITEM_SUBPROCESS ADD ISP_N_LOOPITEM INT NULL
	ALTER TABLE WISP_ITEM_SUBPROCESS_FINALIZADO ADD ISP_N_LOOPITEM INT NULL
END
GO

IF EXISTS (SELECT 1 FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_LOOPITEM IS NULL)
BEGIN
	UPDATE WISP_ITEM_SUBPROCESS SET ISP_N_LOOPITEM = 0 WHERE
	ISP_N_ID IN (SELECT ISP_N_ID FROM WISP_ITEM_SUBPROCESS WHERE ISP_C_METADATA LIKE '%%<SupressAttachmentContext>True</SupressAttachmentContext>%%')
	UPDATE WISP_ITEM_SUBPROCESS SET ISP_N_LOOPITEM = 1 WHERE ISP_N_LOOPITEM IS NULL

	UPDATE WISP_ITEM_SUBPROCESS_FINALIZADO SET ISP_N_LOOPITEM = 0 WHERE
	ISP_N_ID IN (SELECT ISP_N_ID FROM WISP_ITEM_SUBPROCESS_FINALIZADO WHERE ISP_C_METADATA LIKE '%%<SupressAttachmentContext>True</SupressAttachmentContext>%%')
	UPDATE WISP_ITEM_SUBPROCESS_FINALIZADO SET ISP_N_LOOPITEM = 1 WHERE ISP_N_LOOPITEM IS NULL
END
GO

-- FAZ A ALTERAÇAO DE TODAS AS TABELAS ENVOLVIDAS DE UMA VEZ
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_ISP_N_ID' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD ETI_ISP_N_ID INT NULL
	ALTER TABLE WIEX_ITEM_EXECUCAO ADD IEX_ISP_N_ID INT NULL
	ALTER TABLE WANX_ANEXO_ITEM ADD ANX_ISP_N_ID INT NULL
	ALTER TABLE WANF_ANEXO_FINALIZADO ADD ANF_ISP_N_ID INT NULL
	ALTER TABLE WHIS_HISTORICO_ITEM ADD HIS_ISP_N_ID INT NULL
	ALTER TABLE WHIF_HISTORICO_FINALIZADO ADD HIF_ISP_N_ID INT NULL
	ALTER TABLE WITA_ITEM_ACESSO ADD ITA_ISP_N_ID INT NULL
	ALTER TABLE WITR_ITEM_RESTRICAO ADD ITR_ISP_N_ID INT NULL
	ALTER TABLE WITX_ITEM_EXCLUSAO ADD ITX_ISP_N_ID INT NULL
END
GO
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_ISP_N_ID' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_ARQUIVADO'))
BEGIN
	ALTER TABLE WHIF_HISTORICO_ARQUIVADO ADD HIF_ISP_N_ID INT NULL
END

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PVW_N_PRIORITY' AND OBJECT_ID = OBJECT_ID('WPVW_PROCESSGPSVIEW'))
BEGIN
	ALTER TABLE WPVW_PROCESSGPSVIEW ADD PVW_N_PRIORITY INT NOT NULL CONSTRAINT DF_PVW_N_PRIORITY DEFAULT (0)
END    
GO

IF NOT OBJECT_ID('DF_PVW_N_PRIORITY') IS NULL
BEGIN
	ALTER TABLE WPVW_PROCESSGPSVIEW DROP CONSTRAINT DF_PVW_N_PRIORITY
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETS_N_ORDEM' AND OBJECT_ID = OBJECT_ID('WETS_ETAPA_SLA'))
BEGIN
	ALTER TABLE WETS_ETAPA_SLA ADD
		ETS_N_ORDEM			INT NULL,
		ETS_N_ATRASO		INT NULL
END    
GO

SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETS_N_PADRAO' AND OBJECT_ID = OBJECT_ID('WETS_ETAPA_SLA'))
BEGIN
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE WETS_ETAPA_SLA SET ETS_N_ORDEM = 0 WHERE ETS_N_PADRAO = 1'
	EXEC (@UPDQUERY)
	SET @UPDQUERY = 'UPDATE WETS_ETAPA_SLA SET ETS_N_ORDEM = 1 WHERE ETS_N_PADRAO <> 1'
	EXEC (@UPDQUERY)
	SET @UPDQUERY = 'UPDATE WETS_ETAPA_SLA SET ETS_N_ATRASO = 0'
	EXEC (@UPDQUERY)
	SET @UPDQUERY = 'UPDATE WETS_ETAPA_SLA SET ETS_N_ATRASO = 1 WHERE ETS_N_CODIGO IN (SELECT MAX(ETS_N_CODIGO) FROM WETS_ETAPA_SLA WHERE ETS_N_PADRAO <> 1)'
	EXEC (@UPDQUERY)
	SET @UPDQUERY = 'ALTER TABLE WETS_ETAPA_SLA DROP COLUMN	ETS_N_PADRAO'
	EXEC (@UPDQUERY)
END
SET NOCOUNT OFF
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETS_B_ACTIVE' AND OBJECT_ID = OBJECT_ID('WETS_ETAPA_SLA'))
BEGIN
	ALTER TABLE WETS_ETAPA_SLA ADD
		ETS_B_ACTIVE		BIT NOT NULL CONSTRAINT DF_SLAACTIVE DEFAULT 1
END
GO
IF NOT OBJECT_ID('DF_SLAACTIVE') IS NULL
BEGIN
	ALTER TABLE WETS_ETAPA_SLA DROP CONSTRAINT DF_SLAACTIVE
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EVP_N_ORDER' AND OBJECT_ID = OBJECT_ID('WEVP_EVENTO_PENDENTE'))
BEGIN
	ALTER TABLE WEVP_EVENTO_PENDENTE ADD
		EVP_N_ORDER				INT NULL,
		EVP_N_ORIGINTYPE		INT NULL,
		EVP_N_ORIGINID			INT NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EVP_ISP_N_ID' AND OBJECT_ID = OBJECT_ID('WEVP_EVENTO_PENDENTE'))
BEGIN
	ALTER TABLE WEVP_EVENTO_PENDENTE ADD
		EVP_ISP_N_ID			INT NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IPR_D_SLAFINAL' AND OBJECT_ID = OBJECT_ID('WIPR_ITEM_PROCESSO'))
BEGIN
	ALTER TABLE WIPR_ITEM_PROCESSO ADD
		IPR_D_SLAFINAL	DATETIME NULL
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IPR_D_SLACUSTOM' AND OBJECT_ID = OBJECT_ID('WIPR_ITEM_PROCESSO'))
BEGIN
	ALTER TABLE WIPR_ITEM_PROCESSO 
		DROP COLUMN IPR_D_SLACUSTOM
	ALTER TABLE WIPR_ITEM_PROCESSO_FINALIZADO 
		DROP COLUMN IPR_D_SLACUSTOM
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IPR_N_CURRENTSLA' AND OBJECT_ID = OBJECT_ID('WIPR_ITEM_PROCESSO'))
BEGIN
	ALTER TABLE WIPR_ITEM_PROCESSO ADD
		IPR_N_CURRENTSLA INT NULL
END

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IPR_N_CURRENTSLA' AND OBJECT_ID = OBJECT_ID('WIPR_ITEM_PROCESSO_FINALIZADO'))
BEGIN
	ALTER TABLE WIPR_ITEM_PROCESSO_FINALIZADO ADD
		IPR_N_CURRENTSLA INT NULL
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PRI_N_ABSOLUTA' AND OBJECT_ID = OBJECT_ID('WPRI_PRIORIDADE'))
BEGIN
	ALTER TABLE WPRI_PRIORIDADE 
		DROP COLUMN PRI_N_ABSOLUTA 
END
GO


--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'SUB_C_ATTACHMENT' AND OBJECT_ID = OBJECT_ID('MWSUB_SUBPROCESS'))
BEGIN
	ALTER TABLE MWSUB_SUBPROCESS ADD
		SUB_C_ATTACHMENT VARCHAR(200) NULL,
		SUB_N_PARALLEL   INT NULL
END
GO

--#####################################################################################################################


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IWF_C_PARAM1' AND OBJECT_ID = OBJECT_ID('WIWF_ITEM_WORKFLOW'))
BEGIN
	ALTER TABLE WIWF_ITEM_WORKFLOW ADD
		IWF_C_PARAM1 VARCHAR(MAX) NULL,
		IWF_C_PARAM2 VARCHAR(MAX) NULL,
		IWF_C_PARAM3 VARCHAR(MAX) NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IWF_C_PARAM4' AND OBJECT_ID = OBJECT_ID('WIWF_ITEM_WORKFLOW'))
BEGIN
	ALTER TABLE WIWF_ITEM_WORKFLOW ADD
		IWF_C_PARAM4 VARCHAR(MAX) NULL,
		IWF_C_PARAM5 VARCHAR(MAX) NULL
END
GO


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IWF_C_METADATA' AND OBJECT_ID = OBJECT_ID('WIWF_ITEM_WORKFLOW'))
BEGIN
	ALTER TABLE WIWF_ITEM_WORKFLOW ADD
		IWF_C_METADATA VARCHAR(MAX) NULL
END
GO

SET NOCOUNT ON
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MKR_D_CREATEDATE' AND OBJECT_ID = OBJECT_ID('WMKR_MARKER'))
BEGIN
	ALTER TABLE WMKR_MARKER ADD MKR_D_CREATEDATE DATETIME NOT NULL CONSTRAINT DF_MKR_D_CREATEDATE DEFAULT (GETDATE())
	--QUANDO FAZ ISSO TEM QUE LIMPAR TAMBEM OS CACHES DOS MARCADORES
	UPDATE WIWF_ITEM_WORKFLOW SET IWF_C_METADATA = NULL
	UPDATE WIWF_ITEM_WORKFLOW_FINALIZADO SET IWF_C_METADATA = NULL
END
SET NOCOUNT OFF
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'WEB_C_ALIAS' AND OBJECT_ID = OBJECT_ID('MWWEB_WEBSERVICE'))
BEGIN
	ALTER TABLE MWWEB_WEBSERVICE ADD
		WEB_C_ALIAS VARCHAR(50) NULL
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'NOD_B_MARKER' AND OBJECT_ID = OBJECT_ID('WNOD_NODE'))
BEGIN
	ALTER TABLE WNOD_NODE ADD
		NOD_B_MARKER BIT NULL
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'NOD_D_CHANGE' AND OBJECT_ID = OBJECT_ID('WNOD_NODE'))
BEGIN
	ALTER TABLE WNOD_NODE ADD
		NOD_D_CHANGE DATETIME NOT NULL CONSTRAINT DF_NOD_D_CHANGE DEFAULT GETUTCDATE(),
		NOD_USR_N_ID INT NULL
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'NOD_C_SCOPE' AND OBJECT_ID = OBJECT_ID('WNOD_NODE'))
BEGIN
	ALTER TABLE WNOD_NODE ADD NOD_C_SCOPE VARCHAR(36) NULL; 
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MKR_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WMKR_MARKER'))
BEGIN
	ALTER TABLE WMKR_MARKER ADD
		MKR_N_CODIGO INT IDENTITY(1,1) NOT NULL

	ALTER TABLE WMKR_MARKER DROP 
		CONSTRAINT PK_WMKR_MARKER 

	ALTER TABLE WMKR_MARKER ADD 
		CONSTRAINT PK_WMKR_MARKER PRIMARY KEY CLUSTERED (MKR_N_CODIGO ASC)
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_N_ETS_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD
		ETI_N_ETS_N_CODIGO INT NULL
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'FIL_B_REPLACEFILTER' AND OBJECT_ID = OBJECT_ID('MWFIL_FILTRODINAMICO'))
BEGIN
	ALTER TABLE MWFIL_FILTRODINAMICO ADD
		FIL_B_REPLACEFILTER BIT NOT NULL DEFAULT 0
END
GO


--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PRC_N_ALLOWEMPTY' AND OBJECT_ID = OBJECT_ID('MWPRC_PROCEDURE'))
BEGIN
	ALTER TABLE MWPRC_PROCEDURE ADD
		PRC_N_ALLOWEMPTY BIT NOT NULL DEFAULT 0
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_N_PLAINTEXT' AND OBJECT_ID = OBJECT_ID('MWEML_EMAIL'))
BEGIN
	ALTER TABLE MWEML_EMAIL ADD
		EML_N_PLAINTEXT BIT NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_N_PLAINTEXT' AND OBJECT_ID = OBJECT_ID('WEML_EMAIL'))
BEGIN
	ALTER TABLE WEML_EMAIL ADD
		EML_N_PLAINTEXT BIT NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_C_DESTINATARIOSCOPIA' AND OBJECT_ID = OBJECT_ID('MWEML_EMAIL'))
BEGIN
	ALTER TABLE MWEML_EMAIL ADD
		EML_C_DESTINATARIOSCOPIA TEXT
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_C_DESTINATARIOSCOPIA' AND OBJECT_ID = OBJECT_ID('WEML_EMAIL'))
BEGIN
	ALTER TABLE WEML_EMAIL ADD
		EML_C_DESTINATARIOSCOPIA TEXT
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_C_DESTINATARIOSCOPIAOCULTA' AND OBJECT_ID = OBJECT_ID('MWEML_EMAIL'))
BEGIN
	ALTER TABLE MWEML_EMAIL
	ADD EML_C_DESTINATARIOSCOPIAOCULTA VARCHAR(MAX)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EML_C_DESTINATARIOSCOPIAOCULTA' AND OBJECT_ID = OBJECT_ID('WEML_EMAIL'))
BEGIN
	ALTER TABLE WEML_EMAIL
	ADD EML_C_DESTINATARIOSCOPIAOCULTA VARCHAR(MAX)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'AGI_C_TIPO' AND OBJECT_ID = OBJECT_ID('WAGI_AGENDAMENTO_ITEM'))
BEGIN
	ALTER TABLE WAGI_AGENDAMENTO_ITEM
		ADD AGI_C_TIPO VARCHAR(5) NOT NULL DEFAULT ('PRAZO'),
		AGI_C_SLAID VARCHAR(200) NULL,
		AGI_C_AGCONFIG VARCHAR(300) NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'AGI_ISP_N_ID' AND OBJECT_ID = OBJECT_ID('WAGI_AGENDAMENTO_ITEM'))
BEGIN
	ALTER TABLE WAGI_AGENDAMENTO_ITEM ADD AGI_ISP_N_ID INT NOT NULL CONSTRAINT DF_AGI_ISP_N_ID DEFAULT (0)
END
GO

IF NOT EXISTS(SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MRS_MKR_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WMRS_MARKER_RESULT'))
BEGIN
	DELETE WMRS_MARKER_RESULT
	ALTER TABLE WMRS_MARKER_RESULT
	ADD MRS_MKR_N_CODIGO INT
END
GO

IF NOT EXISTS(SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MRS_MKR_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WMRS_MARKER_RESULT_FINISHED'))
BEGIN
	DELETE WMRS_MARKER_RESULT_FINISHED
	ALTER TABLE WMRS_MARKER_RESULT_FINISHED
	ADD MRS_MKR_N_CODIGO INT
END
GO

--#####################################################################################################################
-- NOVA TABELA PARA ARMAZENAR O CACHE DOS VALORES PARA RELATORIO
--#####################################################################################################################
IF OBJECT_ID('[WIOB_ITEM_OBSERVER]') IS NULL
BEGIN
	CREATE TABLE [dbo].[WIOB_ITEM_OBSERVER](
		[IOB_N_ID] [int] IDENTITY(1,1) NOT NULL,
		[IOB_PRO_N_ID] [int] NOT NULL,
		[IOB_C_FIELDNAME] [varchar](400) NOT NULL,
		[IOB_C_CONTENTIDS] [varchar](400) NOT NULL,
	 CONSTRAINT [PK_WIOB_ITEM_OBSERVER] PRIMARY KEY CLUSTERED ([IOB_N_ID] ASC)
	)
END
GO

IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IOB_C_FIELDNAME' AND OBJECT_ID = OBJECT_ID('WIOB_ITEM_OBSERVER')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIOB_ITEM_OBSERVER] ALTER COLUMN IOB_C_FIELDNAME VARCHAR(1000)
END
GO

IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IOB_C_CONTENTIDS' AND OBJECT_ID = OBJECT_ID('WIOB_ITEM_OBSERVER')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIOB_ITEM_OBSERVER] ALTER COLUMN IOB_C_CONTENTIDS VARCHAR(1000)
END
GO

IF OBJECT_ID('[WIVC_ITEMVALUECACHE]') IS NULL
BEGIN

	CREATE TABLE [dbo].[WIVC_ITEMVALUECACHE](
		[IVC_N_ID] [int] IDENTITY(1,1) NOT NULL,
		[IVC_IWF_N_ID] [int] NOT NULL,
		[IVC_ISP_N_ID] [int] NOT NULL,
		[IVC_IOB_N_ID] [int] NOT NULL,
		[IVC_C_ISP_IDS] [varchar](1000) NULL,
		[IVC_C_FIELDNAME] [varchar](1000) NULL,
		[IVC_C_FIELDVALUE] [varchar](MAX) NULL,
	 CONSTRAINT [PK_WIVC_ITEMVALUECACHE] PRIMARY KEY CLUSTERED ([IVC_N_ID] ASC)
	)

	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE]  WITH CHECK ADD  CONSTRAINT [FK_WIVC_ITEM_WORKFLOW] FOREIGN KEY([IVC_IWF_N_ID])
		REFERENCES [dbo].[WIWF_ITEM_WORKFLOW] ([IWF_N_CODIGO])
		ON DELETE CASCADE

	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE]  WITH CHECK ADD  CONSTRAINT [FK_WIVC_OBSERVER] FOREIGN KEY([IVC_IOB_N_ID])
		REFERENCES [dbo].[WIOB_ITEM_OBSERVER] ([IOB_N_ID])
		ON DELETE CASCADE

	CREATE NONCLUSTERED INDEX IX_IVC_ITEMWORKFLOWID ON [WIVC_ITEMVALUECACHE] ([IVC_IWF_N_ID] ASC) 

	CREATE NONCLUSTERED INDEX IX_IVC_SUBPROCESSID ON [WIVC_ITEMVALUECACHE] ([IVC_C_ISP_IDS] ASC) 

	UPDATE [WIWF_ITEM_WORKFLOW] SET IWF_C_METADATA = NULL
END
GO


IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IVC_C_ISP_IDS' AND OBJECT_ID = OBJECT_ID('WIVC_ITEMVALUECACHE')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE] ALTER COLUMN IVC_C_ISP_IDS VARCHAR(1000)
END
GO

IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IVC_C_FIELDNAME' AND OBJECT_ID = OBJECT_ID('WIVC_ITEMVALUECACHE')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE] ALTER COLUMN IVC_C_FIELDNAME VARCHAR(1000)
END
GO

ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE] ALTER COLUMN IVC_C_FIELDVALUE VARCHAR(MAX)
GO


IF OBJECT_ID('[WIVC_ITEMVALUECACHE_FINISHED]') IS NULL
BEGIN
	CREATE TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED](
		[IVC_N_ID] [int] IDENTITY(1,1) NOT NULL,
		[IVC_IWF_N_ID] [int] NOT NULL,
		[IVC_ISP_N_ID] [int] NOT NULL,
		[IVC_IOB_N_ID] [int] NOT NULL,
		[IVC_C_ISP_IDS] [varchar](1000) NULL,
		[IVC_C_FIELDNAME] [varchar](1000) NULL,
		[IVC_C_FIELDVALUE] [varchar](MAX) NULL,
	 CONSTRAINT [PK_WIVC_ITEMVALUECACHEFINISHED] PRIMARY KEY CLUSTERED ([IVC_N_ID] ASC)
	)

	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED]  WITH CHECK ADD  CONSTRAINT [FK_WIVC_ITEM_WORKFLOW_FINISHED] FOREIGN KEY([IVC_IWF_N_ID])
		REFERENCES [dbo].[WIWF_ITEM_WORKFLOW_FINALIZADO] ([IWF_N_CODIGO])
		ON DELETE CASCADE

	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED]  WITH CHECK ADD  CONSTRAINT [FK_WIVC_OBSERVER_FINISHED] FOREIGN KEY([IVC_IOB_N_ID])
		REFERENCES [dbo].[WIOB_ITEM_OBSERVER] ([IOB_N_ID])
		ON DELETE CASCADE

	CREATE NONCLUSTERED INDEX IX_IVC_ITEMWORKFLOWIDFINISHED ON [WIVC_ITEMVALUECACHE_FINISHED] ([IVC_IWF_N_ID] ASC) 

	CREATE NONCLUSTERED INDEX IX_IVC_SUBPROCESSIDFINISHED ON [WIVC_ITEMVALUECACHE_FINISHED] ([IVC_C_ISP_IDS] ASC) 

	UPDATE [WIWF_ITEM_WORKFLOW_FINALIZADO] SET IWF_C_METADATA = NULL
END
GO

IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IVC_C_ISP_IDS' AND OBJECT_ID = OBJECT_ID('WIVC_ITEMVALUECACHE_FINISHED')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED] ALTER COLUMN IVC_C_ISP_IDS VARCHAR(1000)
END
GO

IF (SELECT max_length FROM SYS.COLUMNS WHERE NAME = 'IVC_C_FIELDNAME' AND OBJECT_ID = OBJECT_ID('WIVC_ITEMVALUECACHE_FINISHED')) < 1000
BEGIN
	ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED] ALTER COLUMN IVC_C_FIELDNAME VARCHAR(1000)
END
GO

ALTER TABLE [dbo].[WIVC_ITEMVALUECACHE_FINISHED] ALTER COLUMN IVC_C_FIELDVALUE VARCHAR(MAX)
GO



IF OBJECT_ID('[WIMI_ITEM_METAINFO]') IS NOT NULL
BEGIN
	DECLARE @UPDQUERY VARCHAR(200)
	SET @UPDQUERY = 'DROP TABLE WIMI_ITEM_METAINFO'
	EXEC (@UPDQUERY)
END
GO

--#####################################################################################################################
-- ALTERACOES PARA IMPLEMENTACAO DE SUBPROCESSOS
--#####################################################################################################################
SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_N_ATIVIDADEORIGEM' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	exec ('UPDATE WETI_ETAPA_ITEM SET ETI_C_ANTECESSORES = CONVERT(VARCHAR,ETI_N_ATIVIDADEORIGEM) + ''|;'' WHERE ETI_N_ATIVIDADEORIGEM > 0')
	ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN	ETI_N_ATIVIDADEORIGEM
END
SET NOCOUNT OFF
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_N_LOGLEVEL' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_FINALIZADO'))
BEGIN
	ALTER TABLE WHIF_HISTORICO_FINALIZADO ADD
		HIF_N_LOGLEVEL INT NOT NULL CONSTRAINT DF_WHIS_HIS_FINAL_LOGLEVEL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIS_N_LOGLEVEL' AND OBJECT_ID = OBJECT_ID('WHIS_HISTORICO_ITEM'))
BEGIN
	ALTER TABLE WHIS_HISTORICO_ITEM ADD
		HIS_N_LOGLEVEL INT NOT NULL CONSTRAINT DF_WHIS_HIS_ITEM_LOGLEVEL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ANF_N_ID' AND OBJECT_ID = OBJECT_ID('WANF_ANEXO_FINALIZADO'))
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO ADD
		ANF_N_ID INT NULL
END
GO

--#####################################################################################################################

IF OBJECT_ID('FK_WETI_ETAPA_ITEM_WETS_ETAPA_SLA') IS NULL
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM  WITH CHECK ADD  CONSTRAINT FK_WETI_ETAPA_ITEM_WETS_ETAPA_SLA FOREIGN KEY(ETI_N_ETS_N_CODIGO)
		REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ATV_C_CONFIGURATION' AND OBJECT_ID = OBJECT_ID('WATV_ATIVIDADE'))
BEGIN
	ALTER TABLE WATV_ATIVIDADE ADD
		ATV_C_CONFIGURATION TEXT NULL
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MOD_N_USODESENHO' AND OBJECT_ID = OBJECT_ID('WMOD_MODULO'))
BEGIN
	ALTER TABLE WMOD_MODULO ADD
		MOD_N_USODESENHO bit NULL,
		MOD_N_USOPRAZO bit NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MOD_N_ORDER' AND OBJECT_ID = OBJECT_ID('WMOD_MODULO'))
BEGIN
	ALTER TABLE WMOD_MODULO ADD
		MOD_N_ORDER SMALLINT NOT NULL CONSTRAINT DF_MOD_N_ORDER DEFAULT (0)
END
GO
--#####################################################################################################################

IF OBJECT_ID('DF_WPRO_PROCESSO_PRO_C_DESCRICAO') IS NULL
BEGIN
	ALTER TABLE WPRO_PROCESSO ADD 
		CONSTRAINT DF_WPRO_PROCESSO_PRO_C_DESCRICAO DEFAULT '' FOR PRO_C_DESCRICAO
END
GO

--#####################################################################################################################

IF OBJECT_ID('DF_WPRO_PROCESSO_PRO_C_TITULOITEM') IS NULL
BEGIN
	ALTER TABLE WPRO_PROCESSO ADD 
		CONSTRAINT DF_WPRO_PROCESSO_PRO_C_TITULOITEM DEFAULT '' FOR PRO_C_TITULOITEM
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETA_C_MENSAGEM' AND OBJECT_ID = OBJECT_ID('WETA_ETAPA_PROCESSO'))
BEGIN
	ALTER TABLE WETA_ETAPA_PROCESSO ADD
		ETA_C_MENSAGEM text NULL
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PRZ_N_MOD_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WPRZ_PRAZO'))
BEGIN
		ALTER TABLE WPRZ_PRAZO ADD
			PRZ_N_MOD_N_CODIGO int NULL,
			PRZ_N_CONFIGURED bit NULL,
			PRZ_N_ETS_N_CODIGO int NULL,
			CONSTRAINT FK_WPRZ_PRAZO_WETS_ETAPA_SLA FOREIGN KEY(PRZ_N_ETS_N_CODIGO)	
				REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)		
END
GO
--#####################################################################################################################

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ARQ_C_EXT' AND OBJECT_ID = OBJECT_ID('MWARQ_ARQUIVO'))
BEGIN
	ALTER TABLE MWARQ_ARQUIVO 
		ALTER COLUMN ARQ_C_EXT VARCHAR(20)
END
GO


IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETA_C_GRUPOPERFIL' AND OBJECT_ID = OBJECT_ID('WETA_ETAPA_PROCESSO'))
BEGIN
	ALTER TABLE WETA_ETAPA_PROCESSO 
		ALTER COLUMN ETA_C_GRUPOPERFIL VARCHAR(200)
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_LISTAEDICAO' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM 
		ALTER COLUMN ETI_C_LISTAEDICAO VARCHAR(200)
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PRZ_C_VALOR' AND OBJECT_ID = OBJECT_ID('WPRZ_PRAZO'))
BEGIN
	ALTER TABLE WPRZ_PRAZO 
		ALTER COLUMN PRZ_C_VALOR VARCHAR(200)
END
GO


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ARQ_C_ALIAS' AND OBJECT_ID = OBJECT_ID('MWARQ_ARQUIVO'))
BEGIN
	ALTER TABLE MWARQ_ARQUIVO ADD
		ARQ_C_ALIAS VARCHAR(50) NULL
END
GO

--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'PRC_C_ALIAS' AND OBJECT_ID = OBJECT_ID('MWPRC_PROCEDURE'))
BEGIN
	ALTER TABLE MWPRC_PROCEDURE ADD
		PRC_C_ALIAS VARCHAR(50) NULL
END
GO

-- SLA DO PROCESSO - NA ESTATISTICA 
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ESP_N_ETS_CODIGO' AND OBJECT_ID = OBJECT_ID('WFESP_ESTATISTICA_PROCESSO'))
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO ADD ESP_N_ETS_CODIGO INT NOT NULL CONSTRAINT DF_SLAESPETS DEFAULT 0 
END
GO

IF NOT OBJECT_ID('DF_SLAESPETS') IS NULL
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO DROP CONSTRAINT DF_SLAESPETS 
END
GO
SET NOCOUNT ON
DECLARE @IDSLA INT
SELECT TOP 1 @IDSLA = ETS_N_CODIGO FROM WETS_ETAPA_SLA WHERE ETS_N_ATRASO = 0 ORDER BY ETS_N_ORDEM

UPDATE WFESP_ESTATISTICA_PROCESSO
SET ESP_N_ETS_CODIGO = @IDSLA
WHERE ESP_N_ETS_CODIGO = 0 AND NOT @IDSLA IS NULL

IF OBJECT_ID('FK_ESP__ETS') IS NULL AND NOT EXISTS (SELECT * FROM WFESP_ESTATISTICA_PROCESSO WHERE ESP_N_ETS_CODIGO = 0)
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO ADD CONSTRAINT FK_ESP__ETS FOREIGN KEY (ESP_N_ETS_CODIGO) REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
END
SET NOCOUNT OFF
GO

-- CRIADOR DO PROCESSO NA ESTATISTICA
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ESP_N_EXECID' AND OBJECT_ID = OBJECT_ID('WFESP_ESTATISTICA_PROCESSO'))
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO ADD 
		ESP_N_EXECID INT NOT NULL CONSTRAINT DF_ESP_EXECID DEFAULT 0,
		ESP_C_EXECNAME		VARCHAR(255) NULL	
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ESE_N_ETS_CODIGO' AND OBJECT_ID = OBJECT_ID('WFESE_ESTATISTICA_ETAPA'))
BEGIN
	ALTER TABLE WFESE_ESTATISTICA_ETAPA ADD 
		ESE_N_ETS_CODIGO INT NOT NULL CONSTRAINT DF_ESE_N_ETS_CODIGO DEFAULT 0
END
GO

IF NOT OBJECT_ID('DF_ESP_EXECID') IS NULL
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO DROP CONSTRAINT DF_ESP_EXECID 
END
GO
SET NOCOUNT ON
UPDATE EP
SET EP.ESP_N_EXECID = U.USR_N_ID, ESP_C_EXECNAME = U.USR_C_FULLNAME
FROM WFESP_ESTATISTICA_PROCESSO EP
INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO PF ON EP.ESP_N_IPR_N_CODIGO = PF.IPR_N_CODIGO
INNER JOIN WIWF_ITEM_WORKFLOW_FINALIZADO WF ON PF.IPR_N_IWF_N_CODIGO = IWF_N_CODIGO
INNER JOIN WFUSR_USER U ON WF.IWF_N_USU_OWNER = U.USR_N_ID
WHERE EP.ESP_N_EXECID = 0
SET NOCOUNT OFF
GO

SET NOCOUNT ON
DECLARE @IDSLA INT
SELECT TOP 1 @IDSLA = ETS_N_CODIGO FROM WETS_ETAPA_SLA WHERE ETS_N_ATRASO = 0 ORDER BY ETS_N_ORDEM

UPDATE WFESE_ESTATISTICA_ETAPA
SET ESE_N_ETS_CODIGO = @IDSLA
WHERE ESE_N_ETS_CODIGO = 0 AND NOT @IDSLA IS NULL

IF OBJECT_ID('FK_ESE__ETS') IS NULL AND NOT EXISTS (SELECT * FROM WFESE_ESTATISTICA_ETAPA WHERE ESE_N_ETS_CODIGO = 0)
BEGIN
	ALTER TABLE WFESE_ESTATISTICA_ETAPA ADD CONSTRAINT FK_ESE__ETS FOREIGN KEY (ESE_N_ETS_CODIGO) REFERENCES WETS_ETAPA_SLA (ETS_N_CODIGO)
END
SET NOCOUNT OFF
GO

/*
********************************************************************************************************************
AJUSTA O TAMANHO DA COLUNA DE TITULO DO E-MAIL
********************************************************************************************************************
*/

IF  EXISTS (SELECT * FROM SYSOBJECTS WHERE id = OBJECT_ID('MWEML_EMAIL'))
	ALTER TABLE MWEML_EMAIL ALTER COLUMN EML_C_TITULO VARCHAR(500)
GO

IF  EXISTS (SELECT * FROM SYSOBJECTS WHERE id = OBJECT_ID('WEML_EMAIL'))
	ALTER TABLE WEML_EMAIL ALTER COLUMN EML_C_TITULO VARCHAR(500)
GO

--#####################################################################################################################

IF  EXISTS (SELECT * FROM SYSOBJECTS WHERE id = OBJECT_ID('WETA_ETAPA_PROCESSO'))
	ALTER TABLE WETA_ETAPA_PROCESSO ALTER COLUMN ETA_C_NOME VARCHAR(100)
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'DLN_N_REQUIRED' AND OBJECT_ID = OBJECT_ID('MWDLN_DEADLINE'))
BEGIN
	ALTER TABLE MWDLN_DEADLINE ADD
		DLN_N_REQUIRED bit NOT NULL CONSTRAINT DF_MWDLN_DEADLINE_DLN_N_REQUIRED DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'DLN_C_PRESET' AND OBJECT_ID = OBJECT_ID('MWDLN_DEADLINE'))
BEGIN
	ALTER TABLE MWDLN_DEADLINE ADD
		DLN_C_PRESET VARCHAR(300) NULL 
END
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'FXT_N_PROPAGAANEXO' AND OBJECT_ID = OBJECT_ID('MWFXT_FLUXOEXTERNO'))
BEGIN
	ALTER TABLE MWFXT_FLUXOEXTERNO ADD
		FXT_N_PROPAGAANEXO SMALLINT NOT NULL DEFAULT 0
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'FXT_C_LISTAANEXOS' AND OBJECT_ID = OBJECT_ID('MWFXT_FLUXOEXTERNO'))
BEGIN
	ALTER TABLE MWFXT_FLUXOEXTERNO ADD
		FXT_C_LISTAANEXOS VARCHAR(2000) NOT NULL DEFAULT ''
END
ELSE
BEGIN
	ALTER TABLE MWFXT_FLUXOEXTERNO
		ALTER COLUMN FXT_C_LISTAANEXOS varchar(2000)
END
GO
--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ACI_N_PROCESSO' AND OBJECT_ID = OBJECT_ID('WACI_ACAO_ITEM'))
BEGIN
	ALTER TABLE WACI_ACAO_ITEM ADD
		ACI_N_PROCESSO SMALLINT NOT NULL DEFAULT 0
END
GO
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ACI_B_EXECUTING' AND OBJECT_ID = OBJECT_ID('WACI_ACAO_ITEM'))
BEGIN
	ALTER TABLE WACI_ACAO_ITEM ADD
		ACI_B_EXECUTING SMALLINT NOT NULL DEFAULT 0
END
GO
/*
********************************************************************************************************************
ALTERACAO PARA PERMITIR MULTIPLOS GESTORES DE PROCESSO E ETAPA
********************************************************************************************************************
*/

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'PRO_C_GESTORES' AND OBJECT_ID = OBJECT_ID('WPRO_PROCESSO'))
BEGIN
	ALTER TABLE WPRO_PROCESSO ADD
		PRO_C_GESTORES varchar(100) NULL
END
GO

SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'PRO_N_USU_GESTOR' AND OBJECT_ID = OBJECT_ID('WPRO_PROCESSO'))
BEGIN
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE WPRO_PROCESSO SET PRO_C_GESTORES = ''u'' + RTRIM(LTRIM(CONVERT(CHAR, PRO_N_USU_GESTOR))) + '';'''
	EXEC (@UPDQUERY)
	ALTER TABLE WPRO_PROCESSO DROP COLUMN PRO_N_USU_GESTOR
END
SET NOCOUNT OFF
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ETA_C_GESTORES' AND OBJECT_ID = OBJECT_ID('WETA_ETAPA_PROCESSO'))
BEGIN
	ALTER TABLE WETA_ETAPA_PROCESSO ADD
		ETA_C_GESTORES varchar(100) NULL
END
GO

SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ETA_N_USU_GESTOR' AND OBJECT_ID = OBJECT_ID('WETA_ETAPA_PROCESSO'))
BEGIN
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE WETA_ETAPA_PROCESSO SET ETA_C_GESTORES = ''u'' + RTRIM(LTRIM(CONVERT(CHAR,ETA_N_USU_GESTOR))) + '';'''
	EXEC (@UPDQUERY)
	ALTER TABLE WETA_ETAPA_PROCESSO DROP COLUMN ETA_N_USU_GESTOR
END
SET NOCOUNT OFF
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ETI_C_GESTORES' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD
		ETI_C_GESTORES varchar(100) NULL
END
GO

SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'ETI_N_USU_GESTOR' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE WETI_ETAPA_ITEM SET ETI_C_GESTORES = ''u'' + RTRIM(LTRIM(CONVERT(CHAR, ETI_N_USU_GESTOR))) + '';'''
	EXEC (@UPDQUERY)
	ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_N_USU_GESTOR
END
SET NOCOUNT OFF
GO

IF EXISTS (SELECT * FROM SYSOBJECTS WHERE id = OBJECT_ID('WPRO_PROCESSO'))
	ALTER TABLE WPRO_PROCESSO ALTER COLUMN PRO_C_DESIGN Text NULL
GO

/*
********************************************************************************************************************
NOVO CAMPO PARA O MODULO DE DEADLINE
********************************************************************************************************************
*/
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'DLN_N_REQUIRED' AND OBJECT_ID = OBJECT_ID('MWDLN_DEADLINE'))
BEGIN
	ALTER TABLE MWDLN_DEADLINE ADD
		DLN_N_REQUIRED bit NOT NULL CONSTRAINT DF_MWDLN_DEADLINE_DLN_N_REQUIRED DEFAULT 0
END
GO

/*
CAMPO PARA PERMITIR O UPDATE DE PROCESSOS NA IMPORTAÇÃO ENTRE AMBIENTES
*/
IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'NOD_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WNOD_NODE'))
	ALTER TABLE WNOD_NODE ADD
		NOD_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_WNOD_NODE_IDENTIFIER DEFAULT NEWID()
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'NOL_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WNOL_NODELINK'))
	ALTER TABLE WNOL_NODELINK ADD
		NOL_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_WNOL_NODELINK_IDENTIFIER DEFAULT NEWID()
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_D_DEADLINE' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	ALTER TABLE WETI_ETAPA_ITEM ADD
		ETI_D_DEADLINE	DATETIME NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ZCF_C_CONFIGALIAS' AND OBJECT_ID = OBJECT_ID('WZCF_ZURI_CONFIGURATION'))
BEGIN
	ALTER TABLE WZCF_ZURI_CONFIGURATION ADD
		ZCF_C_CONFIGALIAS	VARCHAR(50) NULL
END
GO

SET NOCOUNT ON
--********* ATUALIZA O CAMPO DE ESCOPO DOS NODES DOS PROCESSOS EXISTENTES ******
DECLARE @INI VARCHAR(36), @SUB VARCHAR(36), @FIM VARCHAR(36)
SET @INI = '36d24f1d-15de-47f8-9300-f85057d28737' --Inicio
SET @SUB = 'e673ca71-ca02-48f4-9faf-701b880e39e2' --Inicio Subprocesso
SET @FIM = 'EA6FDB27-E80F-47B0-BE22-C9D8036D8764' --Fim

UPDATE WNOD_NODE
SET NOD_C_SCOPE = NOD_C_IDENTIFIER
WHERE NOD_C_SCOPE IS NULL AND NOD_MOD_C_ITEMID = @SUB

UPDATE WNOD_NODE
SET NOD_C_SCOPE = 'main'
WHERE NOD_C_SCOPE IS NULL AND NOD_MOD_C_ITEMID IN (@INI, @FIM)

DECLARE @NODES TABLE (ID INT, SCOPE VARCHAR(36));

--ACHA OS NODES SEM ESCOPO CUJO PAI JÁ TEM ESCOPO
INSERT @NODES 
SELECT N.NOD_N_ID, N2.NOD_C_SCOPE
FROM WNOD_NODE N
INNER JOIN WNOP_NODEPORT I ON I.NOP_B_INPUTPORT = 1 AND I.NOP_NOD_N_ID = N.NOD_N_ID
INNER JOIN WNOL_NODELINK L ON L.NOL_DESTINATION_NOP_N_ID = I.NOP_N_ID
INNER JOIN WNOP_NODEPORT O ON L.NOL_ORIGIN_NOP_N_ID = O.NOP_N_ID
INNER JOIN WNOD_NODE N2 ON O.NOP_NOD_N_ID = N2.NOD_N_ID
WHERE N.NOD_C_SCOPE IS NULL AND NOT N2.NOD_C_SCOPE IS NULL
UNION --VERIFICA ATALHOS TAMBÉM
SELECT DISTINCT N.NOD_N_ID, NP.NOD_C_SCOPE
FROM WLNK_LINK LNK
INNER JOIN WNOD_NODE N ON LNK.LNK_N_PART_ID = N.NOD_N_ID AND N.NOD_ATV_N_CODIGO = LNK.LNK_N_CODIGO AND LNK.LNK_NOD_C_IDENTIFIER = N.NOD_C_IDENTIFIER 
INNER JOIN WLNK_LINK LNKP ON LNK.LNK_N_CODIGO = LNKP.LNK_N_PARENTID AND LNK.LNK_N_PRO_N_CODIGO = LNKP.LNK_N_PRO_N_CODIGO
INNER JOIN WNOD_NODE NP ON  LNKP.LNK_N_PART_ID = NP.NOD_N_ID AND NP.NOD_ATV_N_CODIGO = LNKP.LNK_N_CODIGO AND LNKP.LNK_NOD_C_IDENTIFIER = NP.NOD_C_IDENTIFIER AND NOT NP.NOD_C_SCOPE IS NULL
WHERE LNK.LNK_N_DIRECAO = 2 AND N.NOD_C_SCOPE IS NULL

WHILE  EXISTS(SELECT * FROM @NODES)
BEGIN
	UPDATE N
	SET N.NOD_C_SCOPE = CTE.SCOPE
	FROM WNOD_NODE N
	INNER JOIN @NODES CTE ON N.NOD_N_ID = CTE.ID

	DELETE @NODES

	--ACHA OS PRÓXIMOS NODES SEM ESCOPO CUJO PAI JÁ TEM ESCOPO
	INSERT @NODES 
	SELECT N.NOD_N_ID, N2.NOD_C_SCOPE
	FROM WNOD_NODE N
	INNER JOIN WNOP_NODEPORT I ON I.NOP_B_INPUTPORT = 1 AND I.NOP_NOD_N_ID = N.NOD_N_ID
	INNER JOIN WNOL_NODELINK L ON L.NOL_DESTINATION_NOP_N_ID = I.NOP_N_ID
	INNER JOIN WNOP_NODEPORT O ON L.NOL_ORIGIN_NOP_N_ID = O.NOP_N_ID
	INNER JOIN WNOD_NODE N2 ON O.NOP_NOD_N_ID = N2.NOD_N_ID
	WHERE N.NOD_C_SCOPE IS NULL AND NOT N2.NOD_C_SCOPE IS NULL
	UNION --VERIFICA ATALHOS TAMBÉM
	SELECT DISTINCT N.NOD_N_ID, NP.NOD_C_SCOPE
	FROM WLNK_LINK LNK
	INNER JOIN WNOD_NODE N ON LNK.LNK_N_PART_ID = N.NOD_N_ID AND N.NOD_ATV_N_CODIGO = LNK.LNK_N_CODIGO AND LNK.LNK_NOD_C_IDENTIFIER = N.NOD_C_IDENTIFIER 
	INNER JOIN WLNK_LINK LNKP ON LNK.LNK_N_CODIGO = LNKP.LNK_N_PARENTID AND LNK.LNK_N_PRO_N_CODIGO = LNKP.LNK_N_PRO_N_CODIGO
	INNER JOIN WNOD_NODE NP ON  LNKP.LNK_N_PART_ID = NP.NOD_N_ID AND NP.NOD_ATV_N_CODIGO = LNKP.LNK_N_CODIGO AND LNKP.LNK_NOD_C_IDENTIFIER = NP.NOD_C_IDENTIFIER AND NOT NP.NOD_C_SCOPE IS NULL
	WHERE LNK.LNK_N_DIRECAO = 2 AND N.NOD_C_SCOPE IS NULL
END

--ACHA OS NODES SEM ESCOPO CUJOS FILHOS JÁ TEM ESCOPO
INSERT @NODES 
SELECT N.NOD_N_ID, N2.NOD_C_SCOPE
FROM WNOD_NODE N
INNER JOIN WNOP_NODEPORT I ON I.NOP_B_INPUTPORT = 0 AND I.NOP_NOD_N_ID = N.NOD_N_ID
INNER JOIN WNOL_NODELINK L ON L.NOL_ORIGIN_NOP_N_ID = I.NOP_N_ID
INNER JOIN WNOP_NODEPORT O ON L.NOL_DESTINATION_NOP_N_ID = O.NOP_N_ID
INNER JOIN WNOD_NODE N2 ON O.NOP_NOD_N_ID = N2.NOD_N_ID
WHERE N.NOD_C_SCOPE IS NULL AND NOT N2.NOD_C_SCOPE IS NULL
UNION --VERIFICA ATALHOS TAMBÉM
SELECT DISTINCT N.NOD_N_ID, NP.NOD_C_SCOPE
FROM WLNK_LINK LNK
INNER JOIN WNOD_NODE N ON LNK.LNK_N_PART_ID = N.NOD_N_ID AND N.NOD_ATV_N_CODIGO = LNK.LNK_N_CODIGO AND LNK.LNK_NOD_C_IDENTIFIER = N.NOD_C_IDENTIFIER 
INNER JOIN WLNK_LINK LNKP ON LNKP.LNK_N_CODIGO = LNK.LNK_N_PARENTID AND LNK.LNK_N_PRO_N_CODIGO = LNKP.LNK_N_PRO_N_CODIGO
INNER JOIN WNOD_NODE NP ON  LNKP.LNK_N_PART_ID = NP.NOD_N_ID AND NP.NOD_ATV_N_CODIGO = LNKP.LNK_N_CODIGO AND LNKP.LNK_NOD_C_IDENTIFIER = NP.NOD_C_IDENTIFIER AND NOT NP.NOD_C_SCOPE IS NULL
WHERE LNK.LNK_N_DIRECAO = 1 AND N.NOD_C_SCOPE IS NULL

WHILE  EXISTS(SELECT * FROM @NODES)
BEGIN
	UPDATE N
	SET N.NOD_C_SCOPE = CTE.SCOPE
	FROM WNOD_NODE N
	INNER JOIN @NODES CTE ON N.NOD_N_ID = CTE.ID

	DELETE @NODES

	--ACHA OS PRÓXIMOS NODES SEM ESCOPO CUJOS FILHOS JÁ TEM ESCOPO
	INSERT @NODES 
	SELECT N.NOD_N_ID, N2.NOD_C_SCOPE
	FROM WNOD_NODE N
	INNER JOIN WNOP_NODEPORT I ON I.NOP_B_INPUTPORT = 0 AND I.NOP_NOD_N_ID = N.NOD_N_ID
	INNER JOIN WNOL_NODELINK L ON L.NOL_ORIGIN_NOP_N_ID = I.NOP_N_ID
	INNER JOIN WNOP_NODEPORT O ON L.NOL_DESTINATION_NOP_N_ID = O.NOP_N_ID
	INNER JOIN WNOD_NODE N2 ON O.NOP_NOD_N_ID = N2.NOD_N_ID
	WHERE N.NOD_C_SCOPE IS NULL AND NOT N2.NOD_C_SCOPE IS NULL
	UNION --VERIFICA ATALHOS TAMBÉM
	SELECT DISTINCT N.NOD_N_ID, NP.NOD_C_SCOPE
	FROM WLNK_LINK LNK
	INNER JOIN WNOD_NODE N ON LNK.LNK_N_PART_ID = N.NOD_N_ID AND N.NOD_ATV_N_CODIGO = LNK.LNK_N_CODIGO AND LNK.LNK_NOD_C_IDENTIFIER = N.NOD_C_IDENTIFIER 
	INNER JOIN WLNK_LINK LNKP ON LNKP.LNK_N_CODIGO = LNK.LNK_N_PARENTID AND LNK.LNK_N_PRO_N_CODIGO = LNKP.LNK_N_PRO_N_CODIGO
	INNER JOIN WNOD_NODE NP ON  LNKP.LNK_N_PART_ID = NP.NOD_N_ID AND NP.NOD_ATV_N_CODIGO = LNKP.LNK_N_CODIGO AND LNKP.LNK_NOD_C_IDENTIFIER = NP.NOD_C_IDENTIFIER AND NOT NP.NOD_C_SCOPE IS NULL
	WHERE LNK.LNK_N_DIRECAO = 1 AND N.NOD_C_SCOPE IS NULL

END
SET NOCOUNT OFF
GO


SET NOCOUNT ON
--###################################################################################################################
--Apaga os node links duplicados em procedimentos de importação de processos.
--###################################################################################################################
	DECLARE @DUPS TABLE (ID INT IDENTITY, NOL_N_ID INT, NOL_ORIGIN_NOP_N_ID INT, NOL_DESTINATION_NOP_N_ID INT)

	INSERT @DUPS (NOL_N_ID, NOL_ORIGIN_NOP_N_ID, NOL_DESTINATION_NOP_N_ID )
	SELECT MIN(NOL_N_ID), NOL_ORIGIN_NOP_N_ID, NOL_DESTINATION_NOP_N_ID
	FROM WNOL_NODELINK 
	GROUP BY NOL_ORIGIN_NOP_N_ID, NOL_DESTINATION_NOP_N_ID 
	HAVING COUNT(*) > 1

	DECLARE @I INT, @T INT
	SELECT @I=1, @T = MAX(ID) FROM @DUPS

	DECLARE @ID INT, @O INT, @D INT
	WHILE @I <= @T
	BEGIN
		SELECT @ID = NOL_N_ID, @O = NOL_ORIGIN_NOP_N_ID, @D = NOL_DESTINATION_NOP_N_ID
		FROM @DUPS
		WHERE ID = @I

		DELETE WNOL_NODELINK WHERE @ID <> NOL_N_ID AND @O = NOL_ORIGIN_NOP_N_ID AND @D = NOL_DESTINATION_NOP_N_ID
		SET @I = @I + 1
	END
SET NOCOUNT OFF
GO

--###################################################################################################################
--CRIA UMA CHAVE UNIQUE NA TABELA DE LINKS DE NODE PARA NÃO PERMITIR DUPLICIDADES
--###################################################################################################################
IF OBJECT_ID('IX_WNOL_UNIQUE_PORTS') IS NULL
BEGIN
	ALTER TABLE WNOL_NODELINK ADD
		CONSTRAINT IX_WNOL_UNIQUE_PORTS UNIQUE (NOL_ORIGIN_NOP_N_ID, NOL_DESTINATION_NOP_N_ID)
	END
GO
--###################################################################################################################


IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'NOP_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WNOP_NODEPORT'))
	ALTER TABLE WNOP_NODEPORT ADD
		NOP_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_WNOP_NODEP_IDENTIFIER DEFAULT NEWID()
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'PRO_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WPRO_PROCESSO'))
	ALTER TABLE WPRO_PROCESSO ADD
		PRO_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_WPRO_PROID_IDENTIFIER DEFAULT NEWID()
GO

IF  EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'PRO_N_EDICAO_WIDTH' and OBJECT_ID = OBJECT_ID('WPRO_PROCESSO'))
BEGIN
	ALTER TABLE WPRO_PROCESSO
		DROP COLUMN PRO_N_EDICAO_WIDTH, PRO_N_EDICAO_HEIGHT
END
GO
IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'PRO_N_DELETED' and OBJECT_ID = OBJECT_ID('WPRO_PROCESSO'))
	ALTER TABLE WPRO_PROCESSO ADD
		PRO_N_DELETED int NOT NULL CONSTRAINT DF_PRO_N_DELETED DEFAULT 0
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'ATS_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WATS_ATIVIDADE_SAIDA'))
	ALTER TABLE WATS_ATIVIDADE_SAIDA ADD
		ATS_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_WATS_C_IDENTIFIER DEFAULT NEWID()
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'PRZ_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WPRZ_PRAZO'))
	ALTER TABLE WPRZ_PRAZO ADD
		PRZ_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_PRZ_C_IDENTIFIER DEFAULT NEWID()
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'PEN_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WPEN_PONTO_ENTRADA'))
	ALTER TABLE WPEN_PONTO_ENTRADA ADD
		PEN_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_PEN_C_IDENTIFIER DEFAULT NEWID()
GO

IF  NOT EXISTS (SELECT * FROM SYS.COLUMNS WHERE name = 'ATV_C_IDENTIFIER' and OBJECT_ID = OBJECT_ID('WATV_ATIVIDADE'))
	ALTER TABLE WATV_ATIVIDADE ADD
		ATV_C_IDENTIFIER varchar(36) NOT NULL CONSTRAINT DF_ATV_C_IDENTIFIER DEFAULT NEWID()
GO

--#####################################################################################################################

/*
********************************************************************************************************************
NOVO CAMPO PARA O MODULO DE DADOS EXTERNOS
********************************************************************************************************************
*/
IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'EXT_C_ATTACHMENTALIAS' AND OBJECT_ID = OBJECT_ID('MWEXT_DADOSEXTERNOS'))
BEGIN
	ALTER TABLE MWEXT_DADOSEXTERNOS ADD
		EXT_C_ATTACHMENTALIAS varchar(50) NULL
END
GO

SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE name = 'EXT_N_EXTATV_N_CODIGO' AND OBJECT_ID = OBJECT_ID('MWEXT_DADOSEXTERNOS'))
BEGIN
	DECLARE @UPDQUERY VARCHAR(150)
	SET @UPDQUERY = 'UPDATE MWEXT_DADOSEXTERNOS SET EXT_C_ATTACHMENTALIAS = RTRIM(LTRIM(CONVERT(CHAR, EXT_N_EXTATV_N_CODIGO)))'
	EXEC (@UPDQUERY)
	ALTER TABLE MWEXT_DADOSEXTERNOS DROP COLUMN EXT_N_EXTATV_N_CODIGO
END
SET NOCOUNT OFF
GO

--#####################################################################################################################

/*
********************************************************************************************************************
AUMENTO NO CAMPO DE APELIDO DOS ANEXOS (DEVIDO A MUDANÇAS NO CONTROLE FILEUPLOAD)
********************************************************************************************************************
*/
IF EXISTS (SELECT 1 FROM SYS.OBJECTS O
INNER JOIN SYS.COLUMNS C ON C.OBJECT_ID = O.OBJECT_ID
WHERE O.NAME = 'WANX_ANEXO_ITEM' AND C.NAME = 'ANX_C_ATVALIASANEXO')
BEGIN
	ALTER TABLE WANX_ANEXO_ITEM
	ALTER COLUMN ANX_C_ATVALIASANEXO VARCHAR(200)
END
GO

IF EXISTS (SELECT 1 FROM SYS.OBJECTS O
INNER JOIN SYS.COLUMNS C ON C.OBJECT_ID = O.OBJECT_ID
WHERE O.NAME = 'WANF_ANEXO_FINALIZADO' AND C.NAME = 'ANF_C_ATVALIASANEXO')
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO
	ALTER COLUMN ANF_C_ATVALIASANEXO VARCHAR(200)
END
GO

ALTER TABLE WATV_ATIVIDADE ALTER COLUMN ATV_C_NOME VARCHAR(100)
GO

--#####################################################################################################################

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'LNK_C_COR' AND OBJECT_ID = OBJECT_ID('WLNK_LINK'))
BEGIN
	ALTER TABLE WLNK_LINK ADD
		LNK_C_COR VARCHAR(9) NOT NULL CONSTRAINT DF_LNK_C_COR DEFAULT ('#FCA90E')
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'LNK_NOD_C_IDENTIFIER' AND OBJECT_ID = OBJECT_ID('WLNK_LINK'))
BEGIN
	ALTER TABLE WLNK_LINK ADD LNK_NOD_C_IDENTIFIER VARCHAR(36) NULL 

END
GO

SET NOCOUNT ON
--ATUALIZA O IDENTIFICADOR DO NODE EM TODOS OS ATALHOS CUJO PARTID SEJA UM NODE E ONDE O ATV_N_CODIGO DESSE NODE SEJA O ID DO ATALHO.
UPDATE L
SET L.LNK_NOD_C_IDENTIFIER = NOD_C_IDENTIFIER
FROM WLNK_LINK L
INNER JOIN WNOD_NODE ON LNK_N_PART_ID = NOD_N_ID AND LNK_N_CODIGO = NOD_ATV_N_CODIGO 

--DESATIVA TODOS OS PROCESSOS QUE TENHAM ATALHOS COM IDENTIFICADOR DO NODE NULO POIS ESSES ATALHOS SERÃO EXCLUIDOS NA SEQUENCIA
UPDATE P
SET P.PRO_N_ATIVO = 0
FROM WPRO_PROCESSO P
INNER JOIN WLNK_LINK ON PRO_N_CODIGO = LNK_N_PRO_N_CODIGO 
WHERE LNK_NOD_C_IDENTIFIER IS NULL
AND P.PRO_N_ATIVO = 1

--DESATIVA OS PROCESSOS QUE TENHAM NODES DE ATALHO APONTANDO PARA ATALHOS QUE JÁ ESTÃO VINCULADOS A OUTROS NODES OU PARA ATALHOS INEXISTENTES
UPDATE P
SET P.PRO_N_ATIVO = 0
FROM WPRO_PROCESSO P
INNER JOIN WNOD_NODE N ON N.NOD_PRO_N_CODIGO = P.PRO_N_CODIGO 
LEFT JOIN WLNK_LINK L ON N.NOD_ATV_N_CODIGO = L.LNK_N_CODIGO 
WHERE NOD_MOD_C_ITEMID IN ('770201c8-9e53-43dc-815d-fd1488b80075', '37b6bbd5-491b-4bc1-9a8b-e8769a62bfda')
AND NOD_C_IDENTIFIER <> ISNULL(L.LNK_NOD_C_IDENTIFIER, '')
AND P.PRO_N_ATIVO = 1

--APAGA ATALHOS SEM VINCULO COM NODE
DELETE WLNK_LINK WHERE LNK_NOD_C_IDENTIFIER IS NULL

--APAGA NODES DE ATALHO SEM ATALHO VALIDO
DELETE N
FROM  WNOD_NODE N 
LEFT JOIN WLNK_LINK L ON N.NOD_ATV_N_CODIGO = L.LNK_N_CODIGO 
WHERE NOD_MOD_C_ITEMID IN ('770201c8-9e53-43dc-815d-fd1488b80075', '37b6bbd5-491b-4bc1-9a8b-e8769a62bfda')
AND NOD_C_IDENTIFIER <> ISNULL(L.LNK_NOD_C_IDENTIFIER, '')


--#####################################################################################################################
--***** ITEM FINALIZADO CONSTRAINTS
--#####################################################################################################################


IF NOT OBJECT_ID('FK_WANF_ANEXO_FINALIZADO_WIWF_ITEM_WORKFLOW') IS NULL
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO DROP CONSTRAINT FK_WANF_ANEXO_FINALIZADO_WIWF_ITEM_WORKFLOW
END
SET NOCOUNT OFF
GO

IF NOT OBJECT_ID('FK_WHIF_HISTORICO_FINALIZADO_WIWF_ITEM_WORKFLOW') IS NULL
BEGIN
	ALTER TABLE WHIF_HISTORICO_FINALIZADO DROP CONSTRAINT FK_WHIF_HISTORICO_FINALIZADO_WIWF_ITEM_WORKFLOW
END
GO

IF NOT OBJECT_ID('FK_WFESP_ESTATISTICA_PROCESSO_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO DROP CONSTRAINT FK_WFESP_ESTATISTICA_PROCESSO_WIPR_ITEM_PROCESSO
END
GO

IF NOT OBJECT_ID('FK_WFESE_ESTATISTICA_ETAPA_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WFESE_ESTATISTICA_ETAPA DROP CONSTRAINT FK_WFESE_ESTATISTICA_ETAPA_WIPR_ITEM_PROCESSO
END
GO

IF NOT OBJECT_ID('FK_WIRF_ITEM_READERS_FINALIZADO_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WIRF_ITEM_READERS_FINALIZADO DROP CONSTRAINT FK_WIRF_ITEM_READERS_FINALIZADO_WIPR_ITEM_PROCESSO
END
GO

--#####################################################################################################################
--***** TRIGGERS ******************************************************************************************************
--#####################################################################################################################

IF NOT OBJECT_ID('TDWNOP_NODEPORT') IS NULL
BEGIN
	DROP TRIGGER TDWNOP_NODEPORT
END
GO

CREATE TRIGGER TDWNOP_NODEPORT 
	ON WNOP_NODEPORT
	FOR DELETE 
AS
BEGIN
	SET NOCOUNT ON
	
	DELETE L 
	FROM WNOL_NODELINK AS L
	INNER JOIN deleted D ON L.NOL_DESTINATION_NOP_N_ID = D.NOP_N_ID
	
	SET NOCOUNT OFF
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('TDWNOL_NODELINK') IS NULL
BEGIN
	DROP TRIGGER TDWNOL_NODELINK
END
GO

CREATE TRIGGER TDWNOL_NODELINK 
	ON WNOL_NODELINK
	FOR DELETE 
AS
BEGIN
	SET NOCOUNT ON
	
	DELETE E
	FROM WEVE_EVENTO AS E
	INNER JOIN deleted D ON E.EVE_N_PART_ID_LINK = D.NOL_N_ID
	
	SET NOCOUNT OFF
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('AddProcessCounter') IS NULL
BEGIN
	DROP TRIGGER AddProcessCounter
END
GO

CREATE TRIGGER AddProcessCounter
ON WIPR_ITEM_PROCESSO
FOR INSERT
AS
	DECLARE @ItemId int
	DECLARE @FinishedItemId int
	DECLARE @ProcessId int
	DECLARE @InsertedId int

	SELECT @ProcessId = IPR_N_PRO_N_CODIGO, @InsertedId = IPR_N_CODIGO FROM Inserted 
	SELECT @ItemId  = MAX(IPR_N_COUNTERID) FROM WIPR_ITEM_PROCESSO WHERE IPR_N_PRO_N_CODIGO = @ProcessId
	SELECT @FinishedItemId  = MAX(IPR_N_COUNTERID) FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_PRO_N_CODIGO = @ProcessId

	IF @ItemId IS NULL
		SELECT @ItemId  = 1
	ELSE
		SELECT @ItemId  = @ItemId + 1

	IF @FinishedItemId IS NULL
		SELECT @FinishedItemId  = 1
	ELSE
		SELECT @FinishedItemId  = @FinishedItemId + 1
	
	IF @FinishedItemId > @ItemId
		UPDATE WIPR_ITEM_PROCESSO SET IPR_N_COUNTERID = @FinishedItemId WHERE IPR_N_CODIGO = @InsertedId
	ELSE
		UPDATE WIPR_ITEM_PROCESSO SET IPR_N_COUNTERID = @ItemId WHERE IPR_N_CODIGO = @InsertedId

GO

--#####################################################################################################################

IF NOT OBJECT_ID('Del_Etapa_EtapaCondensador') IS NULL
BEGIN
	DROP TRIGGER Del_Etapa_EtapaCondensador
END
GO

CREATE TRIGGER Del_Etapa_EtapaCondensador
	ON WNOD_NODE
	FOR DELETE
AS
	SET NOCOUNT ON

	DELETE L 
	FROM WETC_ETAPA_CONDENSADOR AS L
	INNER JOIN deleted D ON L.ETC_N_NOD_N_ID = D.NOD_N_ID

	SET NOCOUNT OFF
GO


--#####################################################################################################################
--***** INDICES *******************************************************************************************************
--#####################################################################################################################

--## EXECUCAO DO PROCESSO ##--
--#####################################################################################################################
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIPR_ITEM_PROCESSO') AND name = 'IX_IPR_N_IWF_N_CODIGO')
	CREATE NONCLUSTERED INDEX IX_IPR_N_IWF_N_CODIGO ON WIPR_ITEM_PROCESSO (IPR_N_IWF_N_CODIGO ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIPR_ITEM_PROCESSO') AND name = 'IX_IPR_N_PRO_N_CODIGO')
	CREATE NONCLUSTERED INDEX IX_IPR_N_PRO_N_CODIGO ON WIPR_ITEM_PROCESSO (IPR_N_PRO_N_CODIGO ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WETI_ETAPA_ITEM') AND name = 'IX_ETI_ISP_N_ID')
	CREATE NONCLUSTERED INDEX IX_ETI_ISP_N_ID ON WETI_ETAPA_ITEM (ETI_ISP_N_ID ASC) 
GO


--## ETAPA ITEM ##--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WETI_ETAPA_ITEM') AND name = 'IX_ETI_IPR_N_CODIGO')
	CREATE NONCLUSTERED INDEX IX_ETI_IPR_N_CODIGO ON WETI_ETAPA_ITEM (ETI_N_IPR_N_CODIGO ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WETI_ETAPA_ITEM') AND name = 'IX_ETI_ETA_N_CODIGO')
	CREATE NONCLUSTERED INDEX IX_ETI_ETA_N_CODIGO ON WETI_ETAPA_ITEM (ETI_N_ETA_N_CODIGO ASC) 
GO

--## ETAPA ITEM EDITORS ##--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WETE_ETAPA_ITEM_EDITORS') AND name = 'IX_ETI_ITEM')
	CREATE NONCLUSTERED INDEX IX_ETI_ITEM ON WETE_ETAPA_ITEM_EDITORS (ETE_N_ETI_N_CODIGO ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WETE_ETAPA_ITEM_EDITORS') AND name = 'IX_ETI_USERS')
	CREATE NONCLUSTERED INDEX IX_ETI_USERS ON WETE_ETAPA_ITEM_EDITORS (ETE_N_USR_N_ID ASC) 
GO

--## ITEM USERS ##--

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIVU_ITEM_USERS') AND name = 'IX_WIVU_ITEM')
	CREATE NONCLUSTERED INDEX IX_WIVU_ITEM ON WIVU_ITEM_USERS (IVU_N_IWF_N_CODIGO ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIVU_ITEM_USERS') AND name = 'IX_WIVU_ITEM_USERS')
	CREATE UNIQUE NONCLUSTERED INDEX IX_WIVU_ITEM_USERS ON WIVU_ITEM_USERS (IVU_N_USR_N_ID ASC,	IVU_N_IWF_N_CODIGO ASC)
GO
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIVU_ITEM_USERS') AND name = 'IX_WIVU_USER')
	CREATE NONCLUSTERED INDEX IX_WIVU_USER ON WIVU_ITEM_USERS (IVU_N_USR_N_ID ASC)
GO

--## ITEM EXECUCAO ##--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIEX_ITEM_EXECUCAO') AND name = 'IX_WIEX_ITEM')
	CREATE NONCLUSTERED INDEX IX_WIEX_ITEM ON WIEX_ITEM_EXECUCAO (IEX_N_IPR_N_CODIGO ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIEX_ITEM_EXECUCAO') AND name = 'IX_WIEX_USER')
	CREATE NONCLUSTERED INDEX IX_WIEX_USER ON WIEX_ITEM_EXECUCAO (IEX_N_USR_N_ID ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIEX_ITEM_EXECUCAO') AND name = 'IX_ITEM_EXECUTADO')
	CREATE NONCLUSTERED INDEX IX_ITEM_EXECUTADO ON WIEX_ITEM_EXECUCAO
	(
	IEX_N_ETI_N_CODIGO,
	IEX_N_TIPOACAO,
	IEX_N_ACAOID,
	IEX_D_EXECUCAO DESC
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

--## MODULOS ##--
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'IX_WMODULOGUID' AND object_id = OBJECT_ID('WMOD_MODULO')) 
	CREATE UNIQUE NONCLUSTERED INDEX IX_WMODULOGUID ON WMOD_MODULO (MOD_C_ITEMID) 
GO


--## ITEM READERS ##--
--#####################################################################################################################
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WITR_ITEM_READERS') AND name = 'IX_ITR_ITEM')
	CREATE NONCLUSTERED INDEX IX_ITR_ITEM ON WITR_ITEM_READERS (ITR_N_IPR_N_CODIGO ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WITR_ITEM_READERS') AND name = 'IX_ITR_USERS')
	CREATE NONCLUSTERED INDEX IX_ITR_USERS ON WITR_ITEM_READERS (ITR_N_USR_N_ID ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WITR_ITEM_READERS') AND name = 'IX_WITR_ITEM_READERS')
BEGIN
	SET NOCOUNT ON
	DELETE FROM WITR_ITEM_READERS 
	WHERE ITR_N_CODIGO NOT IN ( SELECT MIN(ITR_N_CODIGO) 
								FROM WITR_ITEM_READERS 
								GROUP BY LTRIM(RTRIM(CONVERT(CHAR,ITR_N_USR_N_ID))) + '-' +  LTRIM(RTRIM(CONVERT(CHAR,ITR_N_IPR_N_CODIGO))))
	
		--IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WITR_ITEM_READERS') AND name = 'IX_WITR_ITEM_READERS')
	CREATE UNIQUE NONCLUSTERED INDEX IX_WITR_ITEM_READERS ON WITR_ITEM_READERS (ITR_N_USR_N_ID ASC,	ITR_N_IPR_N_CODIGO ASC)
	SET NOCOUNT OFF
END
GO

--## ITEM READERS FINALIZADO##--

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIRF_ITEM_READERS_FINALIZADO') AND name = 'IX_IRF_ITEM')
	CREATE NONCLUSTERED INDEX IX_IRF_ITEM ON WIRF_ITEM_READERS_FINALIZADO (	IRF_N_IPR_N_CODIGO ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIRF_ITEM_READERS_FINALIZADO') AND name = 'IX_IRF_USERS')
	CREATE NONCLUSTERED INDEX IX_IRF_USERS ON WIRF_ITEM_READERS_FINALIZADO (IRF_N_USR_N_ID ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIRF_ITEM_READERS_FINALIZADO') AND name = 'IX_WIRF_ITEM_READERS_FINALIZADO')
	CREATE UNIQUE NONCLUSTERED INDEX IX_WIRF_ITEM_READERS_FINALIZADO ON WIRF_ITEM_READERS_FINALIZADO (IRF_N_USR_N_ID ASC, IRF_N_IPR_N_CODIGO ASC)
GO

--## HISTORICO ITEM ##--
--#####################################################################################################################

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIS_HISTORICO_ITEM') AND name = 'IX_WHIS_ETAPAITEM')
	CREATE NONCLUSTERED INDEX IX_WHIS_ETAPAITEM ON WHIS_HISTORICO_ITEM (HIS_N_ETI_N_CODIGO ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIS_HISTORICO_ITEM') AND name = 'IX_WHIS_USER')
	CREATE NONCLUSTERED INDEX IX_WHIS_USER ON WHIS_HISTORICO_ITEM (HIS_N_USR_EXECUTOR ASC)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIS_HISTORICO_ITEM') AND name = 'IX_WHIS_USERITEM')
	CREATE NONCLUSTERED INDEX IX_WHIS_USERITEM ON WHIS_HISTORICO_ITEM (HIS_N_USR_EXECUTOR ASC,	HIS_N_IWF_N_CODIGO ASC)
GO

--## HISTORICO ITEM FINALIZADO ##--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIF_HISTORICO_FINALIZADO') AND name = 'IX_WHIF_USER')
	CREATE NONCLUSTERED INDEX IX_WHIF_USER ON WHIF_HISTORICO_FINALIZADO (HIF_N_USR_EXECUTOR ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIF_HISTORICO_FINALIZADO') AND name = 'IX_WHIF_USERITEM')
	CREATE NONCLUSTERED INDEX IX_WHIF_USERITEM ON WHIF_HISTORICO_FINALIZADO (HIF_N_USR_EXECUTOR ASC, HIF_N_IWF_N_CODIGO ASC)
GO

--## ANEXO ITEM ##--
--#####################################################################################################################

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANX_ANEXO_ITEM') AND name = 'IX_WANX_ATIVIDADE')
	CREATE NONCLUSTERED INDEX IX_WANX_ATIVIDADE ON WANX_ANEXO_ITEM (ANX_N_ATV_N_CODIGO ASC) 
GO

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANX_ANEXO_ITEM') AND name = 'IX_WANX_ALIAS')
	DROP INDEX WANX_ANEXO_ITEM.IX_WANX_ALIAS
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANX_ANEXO_ITEM') AND name = 'IX_WANX_SUBPROCESS')
	CREATE NONCLUSTERED INDEX IX_WANX_SUBPROCESS ON WANX_ANEXO_ITEM (ANX_ISP_N_ID ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANX_ANEXO_ITEM') AND name = 'IX_WANX_ITEM')
	CREATE NONCLUSTERED INDEX IX_WANX_ITEM ON WANX_ANEXO_ITEM (ANX_N_IWF_N_CODIGO ASC)
GO

--## ANEXO ITEM FINALIZADO##--
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANF_ANEXO_FINALIZADO') AND name = 'IX_WANF_ATIVIDADE')
	CREATE NONCLUSTERED INDEX IX_WANF_ATIVIDADE ON WANF_ANEXO_FINALIZADO (ANF_N_ATV_N_CODIGO ASC)
GO

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANF_ANEXO_FINALIZADO') AND name = 'IX_WANF_ALIAS')
	DROP INDEX WANF_ANEXO_FINALIZADO.IX_WANF_ALIAS
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANF_ANEXO_FINALIZADO') AND name = 'IX_WANF_SUBPROCESS')
	CREATE NONCLUSTERED INDEX IX_WANF_SUBPROCESS ON WANF_ANEXO_FINALIZADO (ANF_ISP_N_ID ASC) 
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WANF_ANEXO_FINALIZADO') AND name = 'IX_WANF_ITEM')
	CREATE NONCLUSTERED INDEX IX_WANF_ITEM ON WANF_ANEXO_FINALIZADO (ANF_N_IWF_N_CODIGO ASC)
GO


--## LOG MESSAGE ##--
--#####################################################################################################################
IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WFLOG_LOGMESSAGE') AND name = 'IX_LOG_CATEGORY')
	CREATE NONCLUSTERED INDEX IX_LOG_CATEGORY ON WFLOG_LOGMESSAGE (LOG_C_CATEGORY) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WFLOG_LOGMESSAGE') AND name = 'IX_LOG_TIMESTAMP')
	CREATE NONCLUSTERED INDEX IX_LOG_TIMESTAMP ON WFLOG_LOGMESSAGE (LOG_D_TIMESTAMP) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIS_HISTORICO_ITEM') AND name = 'IX_WHIS_HISTORICO_ITEM_FULL')
	DROP INDEX WHIS_HISTORICO_ITEM.IX_WHIS_HISTORICO_ITEM_FULL
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIS_HISTORICO_ITEM') AND name = 'IX_WHIS_HISTORICOITEM_FULL')
	CREATE NONCLUSTERED INDEX IX_WHIS_HISTORICOITEM_FULL ON WHIS_HISTORICO_ITEM (HIS_N_IWF_N_CODIGO, HIS_N_ETA_N_CODIGO, HIS_N_LOGLEVEL) INCLUDE 
	(HIS_C_DESCRICAO, HIS_ISP_N_ID, HIS_C_STATUS, HIS_D_GRAVACAO, HIS_N_ACAOID, HIS_N_ATIVO, HIS_N_CODIGO, HIS_N_ETI_N_CODIGO, 
	HIS_N_EVE_N_ID, HIS_N_PRO_N_CODIGO, HIS_N_TIPOACAO, HIS_N_USR_EXECUTOR)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WHIF_HISTORICO_FINALIZADO') AND name = 'IX_WHIF_HISTORICO_FINALIZADO_FULL')
	CREATE NONCLUSTERED INDEX IX_WHIF_HISTORICO_FINALIZADO_FULL ON WHIF_HISTORICO_FINALIZADO (HIF_N_ACAOID, HIF_N_TIPOACAO) INCLUDE 
	(HIF_D_GRAVACAO, HIF_N_IWF_N_CODIGO, HIF_N_PRO_N_CODIGO, HIF_N_USR_EXECUTOR)
GO

IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID('WIEX_ITEM_EXECUCAO') AND name = 'IX_WIEX_ITEM_EXECUCAO_FULL')
	CREATE NONCLUSTERED INDEX IX_WIEX_ITEM_EXECUCAO_FULL ON WIEX_ITEM_EXECUCAO (IEX_N_ACAOID, IEX_N_TIPOACAO) INCLUDE (IEX_D_EXECUCAO, IEX_N_IPR_N_CODIGO, IEX_N_USR_N_ID)
GO


IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ISP_NOD_C_SCOPE' AND OBJECT_ID = OBJECT_ID('WISP_ITEM_SUBPROCESS'))
BEGIN
	ALTER TABLE WISP_ITEM_SUBPROCESS ADD ISP_NOD_C_SCOPE VARCHAR(36) NULL
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ISP_NOD_C_SCOPE' AND OBJECT_ID = OBJECT_ID('WISP_ITEM_SUBPROCESS_FINALIZADO'))
BEGIN
	ALTER TABLE WISP_ITEM_SUBPROCESS_FINALIZADO ADD ISP_NOD_C_SCOPE VARCHAR(36) NULL
END
GO

--#####################################################################################################################
--***** VIEWS *********************************************************************************************************
--#####################################################################################################################
IF NOT OBJECT_ID('Observadores') IS NULL
BEGIN
	DROP VIEW Observadores
END
GO
CREATE VIEW Observadores
AS
SELECT     
	IPR_C_STATUSCOLOR AS STATUSCOLOR,
	IPR_D_DATAINICIO AS INICIOITEM, 
	IPR_N_CODIGO AS ITEMPROCESSOID, 
	IPR_N_FINALIZADO AS FINALIZADO, 
	IPR_N_COUNTERID AS COUNTERID,
	IPR_N_PRIORIDADE AS PRIORIDADE, 
	IPR_C_LISTAACESSO AS LISTAACESSO, 
	IWF_N_READONLY AS READONLYFLAG, 
	IWF_C_NOME AS NOMEITEM, 
	IWF_C_STATUS AS STATUS, 
	IWF_N_CODIGO AS ITEMWORKFLOWID, 
	IWF_N_USU_OWNER AS OWNERID,
	PRO_C_NOME AS NOMEPROCESSO, 
	PRO_N_CODIGO AS PROCESSOID, 
	PRO_N_USECOUNTER AS USECOUNTER,
	PRO_C_GESTORES AS GESTORESPROCESSO,
	ETA_C_GESTORES AS GESTORETAPA, 
	ITR_N_USR_N_ID AS USERID, 
	ETI_N_CODIGO AS ETIID, 
	ETI_N_USERPRIORITY AS USERPRIORITY, 
	ETI_N_USU_VINCULADO AS RESPONSAVELID,
	ETI_D_INICIO AS INICIOETAPA,
	ETI_ISP_N_ID AS SUBPROCESSID, 
	ETI_C_APELIDOETAPA AS MACROETAPA,
	ETA_N_CODIGO AS ETAPAID, 
	ETA_C_NOME AS NOMEETAPA, 
	ETA_C_GESTORES AS GESTORESETAPA, 
	IWF_N_ITE_ORIGEM AS ITEMORIGEM,
	IWF_C_PARAM1 AS PARAM1,
	IWF_C_PARAM2 AS PARAM2,
	IWF_C_PARAM3 AS PARAM3,
	IWF_C_PARAM4 AS PARAM4,
	IWF_C_PARAM5 AS PARAM5,
	ETI_N_ETS_N_CODIGO AS SLAIDETAPA,
	ETI_D_DEADLINE AS DEADLINEETAPA,
	IPR_N_CURRENTSLA AS SLAIDPROC,
	IPR_D_SLAFINAL AS DEADLINEPROC,
	ISP_C_TITLE AS SUBTITULO, 
	ISP_C_METADATA AS SUBMETA
FROM
	WIPR_ITEM_PROCESSO 
	INNER JOIN
		WIWF_ITEM_WORKFLOW ON WIWF_ITEM_WORKFLOW.IWF_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_IWF_N_CODIGO 
	INNER JOIN
		WPRO_PROCESSO ON WPRO_PROCESSO.PRO_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
	INNER JOIN
		WITR_ITEM_READERS ON WITR_ITEM_READERS.ITR_N_IPR_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_CODIGO 
	LEFT OUTER JOIN
		WETI_ETAPA_ITEM ON WETI_ETAPA_ITEM.ETI_N_IPR_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_CODIGO 
	LEFT OUTER JOIN
		WETA_ETAPA_PROCESSO ON WETA_ETAPA_PROCESSO.ETA_N_CODIGO = WETI_ETAPA_ITEM.ETI_N_ETA_N_CODIGO
	LEFT OUTER JOIN
		WISP_ITEM_SUBPROCESS ON WISP_ITEM_SUBPROCESS.ISP_N_ID = WETI_ETAPA_ITEM.ETI_ISP_N_ID
GO                
	
--#####################################################################################################################

IF NOT OBJECT_ID('MeusProcessos') IS NULL
BEGIN
	DROP VIEW MeusProcessos
END
GO
CREATE VIEW MeusProcessos
AS
SELECT     
	IPR_C_STATUSCOLOR AS STATUSCOLOR, 
	IPR_D_DATAINICIO AS INICIOITEM, 
	IPR_N_CODIGO AS ITEMPROCESSOID, 
	IPR_N_FINALIZADO AS FINALIZADO, 
	IPR_N_COUNTERID AS COUNTERID,
	IPR_N_PRIORIDADE AS PRIORIDADE, 
	IWF_N_READONLY AS READONLYFLAG,
	IWF_C_NOME AS NOMEITEM, 
	IWF_C_STATUS AS STATUS, 
	IWF_N_CODIGO AS ITEMWORKFLOWID, 
	IWF_N_USU_OWNER AS OWNERID,
	PRO_C_NOME AS NOMEPROCESSO, 
	PRO_N_CODIGO AS PROCESSOID, 
	PRO_N_USECOUNTER AS USECOUNTER,
	PRO_C_GESTORES AS GESTORESPROCESSO,
	ISNULL(ETI_N_CODIGO,0) AS ETIID, 
	ETI_N_USERPRIORITY AS USERPRIORITY, 
	ETI_N_USU_VINCULADO AS RESPONSAVELID, 
	ETI_D_INICIO AS INICIOETAPA, 
	ETI_ISP_N_ID AS SUBPROCESSID, 
	ETI_C_APELIDOETAPA AS MACROETAPA,
	ETA_N_CODIGO AS ETAPAID,
	ETA_C_NOME AS NOMEETAPA, 
	ETA_C_GESTORES AS GESTORESETAPA, 
	IWF_N_ITE_ORIGEM AS ITEMORIGEM,
	IVU_N_USR_N_ID AS USERID,
	IWF_C_PARAM1 AS PARAM1,
	IWF_C_PARAM2 AS PARAM2,
	IWF_C_PARAM3 AS PARAM3,
	IWF_C_PARAM4 AS PARAM4,
	IWF_C_PARAM5 AS PARAM5,
	ETI_N_ETS_N_CODIGO AS SLAIDETAPA,
	ETI_D_DEADLINE AS DEADLINEETAPA,
	IPR_N_CURRENTSLA AS SLAIDPROC,
	IPR_D_SLAFINAL AS DEADLINEPROC,
	ISP_C_TITLE AS SUBTITULO, 
	ISP_C_METADATA AS SUBMETA
FROM
	WIPR_ITEM_PROCESSO 
	LEFT OUTER JOIN
		WIWF_ITEM_WORKFLOW ON WIWF_ITEM_WORKFLOW.IWF_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_IWF_N_CODIGO 
	LEFT OUTER JOIN
		WPRO_PROCESSO ON WPRO_PROCESSO.PRO_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
	INNER JOIN
		WIVU_ITEM_USERS ON WIVU_ITEM_USERS.IVU_N_IWF_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_IWF_N_CODIGO 
	LEFT OUTER JOIN
		WETI_ETAPA_ITEM ON WETI_ETAPA_ITEM.ETI_N_IPR_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_CODIGO 
	LEFT OUTER JOIN
		WETA_ETAPA_PROCESSO ON WETA_ETAPA_PROCESSO.ETA_N_CODIGO = WETI_ETAPA_ITEM.ETI_N_ETA_N_CODIGO
	LEFT OUTER JOIN
		WISP_ITEM_SUBPROCESS ON WISP_ITEM_SUBPROCESS.ISP_N_ID = WETI_ETAPA_ITEM.ETI_ISP_N_ID
GO

--#####################################################################################################################

IF NOT OBJECT_ID('CaixaEntrada') IS NULL
BEGIN
	DROP VIEW CaixaEntrada
END
GO

CREATE VIEW CaixaEntrada
AS
SELECT     
	ETI_N_CODIGO AS ETIID, 
	ETI_N_USERPRIORITY AS USERPRIORITY, 
	ETI_D_INICIO AS INICIOETAPA, 
	ETI_ISP_N_ID AS SUBPROCESSID, 
	ETI_C_APELIDOETAPA AS MACROETAPA,
	ETA_N_CODIGO AS ETAPAID,
	ETA_C_NOME AS NOMEETAPA,
	ETA_C_GESTORES AS GESTORESETAPA, 
	IPR_C_STATUSCOLOR AS STATUSCOLOR, 
	IPR_D_DATAINICIO AS INICIOITEM, 
	IPR_N_CODIGO AS ITEMPROCESSOID, 
	IWF_N_READONLY AS READONLYFLAG, 
	IWF_C_NOME AS NOMEITEM, 
	IWF_C_STATUS AS STATUS, 
	IWF_N_CODIGO AS ITEMWORKFLOWID,
	IPR_N_COUNTERID AS COUNTERID, 
	PRO_C_NOME AS NOMEPROCESSO,
	PRO_N_CODIGO AS PROCESSOID, 
	PRO_C_GESTORES AS GESTORESPROCESSO,
	IPR_N_PRIORIDADE AS PRIORIDADE,
	IWF_N_USU_OWNER AS OWNERID, 
	ETE_N_USR_N_ID AS USERID, 
	ETI_N_USU_VINCULADO AS RESPONSAVELID, 
	PRO_N_USECOUNTER AS USECOUNTER,
	IWF_N_ITE_ORIGEM AS ITEMORIGEM,
	IWF_C_PARAM1 AS PARAM1,
	IWF_C_PARAM2 AS PARAM2,
	IWF_C_PARAM3 AS PARAM3,
	IWF_C_PARAM4 AS PARAM4,
	IWF_C_PARAM5 AS PARAM5,
	ETI_N_ETS_N_CODIGO AS SLAIDETAPA,
	ETI_D_DEADLINE AS DEADLINEETAPA,
	IPR_N_CURRENTSLA AS SLAIDPROC,
	IPR_D_SLAFINAL AS DEADLINEPROC,
	ISP_C_TITLE AS SUBTITULO, 
	ISP_C_METADATA AS SUBMETA
FROM         
	WETI_ETAPA_ITEM 
	INNER JOIN
		WETE_ETAPA_ITEM_EDITORS ON WETE_ETAPA_ITEM_EDITORS.ETE_N_ETI_N_CODIGO = WETI_ETAPA_ITEM.ETI_N_CODIGO 
	INNER JOIN
		WETA_ETAPA_PROCESSO ON WETA_ETAPA_PROCESSO.ETA_N_CODIGO = WETI_ETAPA_ITEM.ETI_N_ETA_N_CODIGO 
	INNER JOIN
		WIPR_ITEM_PROCESSO ON WIPR_ITEM_PROCESSO.IPR_N_CODIGO = WETI_ETAPA_ITEM.ETI_N_IPR_N_CODIGO 
	INNER JOIN
		WIWF_ITEM_WORKFLOW ON WIWF_ITEM_WORKFLOW.IWF_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_IWF_N_CODIGO
	INNER JOIN
		WPRO_PROCESSO ON WPRO_PROCESSO.PRO_N_CODIGO = WIPR_ITEM_PROCESSO.IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
	LEFT OUTER JOIN
		WISP_ITEM_SUBPROCESS ON WISP_ITEM_SUBPROCESS.ISP_N_ID = WETI_ETAPA_ITEM.ETI_ISP_N_ID
GO
--#####################################################################################################################
IF NOT OBJECT_ID('MeusProcessosFinal') IS NULL
BEGIN
	DROP VIEW MeusProcessosFinal
END
GO
CREATE VIEW MeusProcessosFinal
AS
	SELECT 
		STATUSCOLOR, 
		INICIOITEM, 
		ITEMPROCESSOID, 
		FINALIZADO, 
		COUNTERID,
		PRIORIDADE, 
		READONLYFLAG,
		NOMEITEM, 
		STATUS, 
		ITEMWORKFLOWID, 
		OWNERID,
		NOMEPROCESSO, 
		PROCESSOID, 
		USECOUNTER,
		GESTORESPROCESSO,
		ETIID, 
		USERPRIORITY, 
		RESPONSAVELID, 
		INICIOETAPA, 
		SUBPROCESSID, 
		MACROETAPA,
		ETAPAID,
		NOMEETAPA, 
		GESTORESETAPA, 
		ITEMORIGEM,
		USERID, 
		PARAM1,
		PARAM2,
		PARAM3,
		PARAM4,
		PARAM5,
		SLAIDETAPA,
		DEADLINEETAPA,
		SLAIDPROC,
		DEADLINEPROC,
		SUBTITULO,
		SUBMETA
	FROM 
		MeusProcessos
	UNION ALL
	SELECT     
		IPR_C_STATUSCOLOR AS STATUSCOLOR, 
		IPR_D_DATAINICIO AS INICIOITEM, 
		IPR_N_CODIGO AS ITEMPROCESSOID, 
		IPR_N_FINALIZADO AS FINALIZADO, 
		IPR_N_COUNTERID AS COUNTERID,
		IPR_N_PRIORIDADE AS PRIORIDADE, 
		IWF_N_READONLY AS READONLYFLAG,
		IWF_C_NOME AS NOMEITEM, 
		IWF_C_STATUS AS STATUS, 
		IWF_N_CODIGO AS ITEMWORKFLOWID, 
		IWF_N_USU_OWNER AS OWNERID,
		PRO_C_NOME AS NOMEPROCESSO, 
		PRO_N_CODIGO AS PROCESSOID, 
		PRO_N_USECOUNTER AS USECOUNTER,
		PRO_C_GESTORES AS GESTORESPROCESSO,
		0 AS ETIID, 
		NULL AS USERPRIORITY, 
		NULL AS RESPONSAVELID, 
		NULL AS INICIOETAPA, 
		NULL AS SUBPROCESSID, 
		NULL AS MACROETAPA,
		0 AS ETAPAID,
		NULL AS NOMEETAPA, 
		NULL AS GESTORESETAPA, 
		IWF_N_ITE_ORIGEM AS ITEMORIGEM,
		EXECUTOR.EXECUTORID AS USERID, 
		IWF_C_PARAM1 AS PARAM1,
		IWF_C_PARAM2 AS PARAM2,
		IWF_C_PARAM3 AS PARAM3,
		IWF_C_PARAM4 AS PARAM4,
		IWF_C_PARAM5 AS PARAM5,
		0 AS SLAIDETAPA,
		NULL DEADLINEETAPA,
		IPR_N_CURRENTSLA AS SLAIDPROC,
		IPR_D_SLAFINAL AS DEADLINEPROC,
		'' AS SUBTITULO, 
		'' AS SUBMETA 
	FROM
		WIPR_ITEM_PROCESSO_FINALIZADO 
		INNER JOIN
			WIWF_ITEM_WORKFLOW_FINALIZADO ON WIWF_ITEM_WORKFLOW_FINALIZADO.IWF_N_CODIGO = WIPR_ITEM_PROCESSO_FINALIZADO.IPR_N_IWF_N_CODIGO 
		INNER JOIN
			WPRO_PROCESSO ON WPRO_PROCESSO.PRO_N_CODIGO = WIPR_ITEM_PROCESSO_FINALIZADO.IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
		INNER JOIN
			(	SELECT DISTINCT 
					HIF_N_USR_EXECUTOR AS EXECUTORID,
					HIF_N_IWF_N_CODIGO AS ITEMID
				FROM
					WHIF_HISTORICO_FINALIZADO
			) AS EXECUTOR ON WIWF_ITEM_WORKFLOW_FINALIZADO.IWF_N_CODIGO = EXECUTOR.ITEMID 
GO
--#####################################################################################################################
IF NOT OBJECT_ID('ObservadoresFinal') IS NULL
BEGIN
	DROP VIEW ObservadoresFinal
END
GO

CREATE VIEW ObservadoresFinal
AS
	SELECT 
		STATUSCOLOR,
		INICIOITEM, 
		ITEMPROCESSOID, 
		FINALIZADO, 
		COUNTERID,
		PRIORIDADE, 
		LISTAACESSO, 
		READONLYFLAG, 
		NOMEITEM, 
		STATUS, 
		ITEMWORKFLOWID, 
		OWNERID,
		NOMEPROCESSO, 
		PROCESSOID, 
		USECOUNTER,
		GESTORESPROCESSO,
		USERID, 
		ETIID, 
		USERPRIORITY, 
		RESPONSAVELID,
		INICIOETAPA,
		SUBPROCESSID, 
		MACROETAPA,
		ETAPAID, 
		NOMEETAPA, 
		GESTORESETAPA, 
		ITEMORIGEM,
		PARAM1,
		PARAM2,
		PARAM3,
		PARAM4,
		PARAM5,
		SLAIDETAPA,
		DEADLINEETAPA,
		SLAIDPROC,
		DEADLINEPROC,
		SUBTITULO,
		SUBMETA
	FROM
		Observadores
	UNION ALL
	SELECT     
		IPR_C_STATUSCOLOR AS STATUSCOLOR,
		IPR_D_DATAINICIO AS INICIOITEM, 
		IPR_N_CODIGO AS ITEMPROCESSOID, 
		IPR_N_FINALIZADO AS FINALIZADO, 
		IPR_N_COUNTERID AS COUNTERID,
		IPR_N_PRIORIDADE AS PRIORIDADE, 
		IPR_C_LISTAACESSO AS LISTAACESSO, 
		IWF_N_READONLY AS READONLYFLAG, 
		IWF_C_NOME AS NOMEITEM, 
		IWF_C_STATUS AS STATUS, 
		IWF_N_CODIGO AS ITEMWORKFLOWID, 
		IWF_N_USU_OWNER AS OWNERID,
		PRO_C_NOME AS NOMEPROCESSO, 
		PRO_N_CODIGO AS PROCESSOID, 
		PRO_N_USECOUNTER AS USECOUNTER,
		PRO_C_GESTORES AS GESTORESPROCESSO,
		READERS.EXECUTORID AS USERID, 
		0 AS ETIID, 
		NULL AS USERPRIORITY, 
		NULL AS RESPONSAVELID,
		NULL AS INICIOETAPA,
		NULL AS SUBPROCESSID, 
		NULL AS MACROETAPA,
		0 AS ETAPAID, 
		NULL AS NOMEETAPA, 
		NULL AS GESTORESETAPA, 
		IWF_N_ITE_ORIGEM AS ITEMORIGEM,
		IWF_C_PARAM1 AS PARAM1,
		IWF_C_PARAM2 AS PARAM2,
		IWF_C_PARAM3 AS PARAM3,
		IWF_C_PARAM4 AS PARAM4,
		IWF_C_PARAM5 AS PARAM5,
		0 AS SLAIDETAPA,
		NULL AS DEADLINEETAPA,
		IPR_N_CURRENTSLA AS SLAIDPROC,
		IPR_D_SLAFINAL AS DEADLINEPROC,
		'' AS SUBTITULO, 
		'' AS SUBMETA 
	FROM
		WIPR_ITEM_PROCESSO_FINALIZADO
		INNER JOIN
			WIWF_ITEM_WORKFLOW_FINALIZADO ON WIWF_ITEM_WORKFLOW_FINALIZADO.IWF_N_CODIGO = WIPR_ITEM_PROCESSO_FINALIZADO.IPR_N_IWF_N_CODIGO 
		INNER JOIN
			WPRO_PROCESSO ON WPRO_PROCESSO.PRO_N_CODIGO = WIPR_ITEM_PROCESSO_FINALIZADO.IPR_N_PRO_N_CODIGO  AND PRO_N_DELETED = 0
		INNER JOIN
		(
			SELECT  
				IRF_N_USR_N_ID AS EXECUTORID, 
				IRF_N_IPR_N_CODIGO AS ITEMID
			FROM	
				WIRF_ITEM_READERS_FINALIZADO
		) AS READERS ON WIPR_ITEM_PROCESSO_FINALIZADO.IPR_N_CODIGO = READERS.ITEMID 
GO

--#################################################################################################################################
-- MEXENDO EM VIEW USANDO SEMPRE ALTER GARANTE QUE NÃO VAI PERDER GRANTS E REVOKES EXPLICITOS
IF OBJECT_ID('WSST_SCOPED_STEPS') IS NULL
BEGIN
	EXEC ('CREATE VIEW WSST_SCOPED_STEPS AS SELECT GETDATE() TODAY')
END
GO
ALTER VIEW WSST_SCOPED_STEPS
AS
SELECT 
	ETA_N_CODIGO, 
	ETA_N_PRO_N_CODIGO,
	ETA_C_NOME,
	NOD_C_SCOPE 
FROM 
	WETA_ETAPA_PROCESSO
	INNER JOIN WNOD_NODE ON NOD_N_ID = ETA_N_PART_ID
GO

IF OBJECT_ID('WNDE_NODE_DEPENDENCY') IS NULL
BEGIN
	EXEC ('CREATE VIEW WNDE_NODE_DEPENDENCY AS SELECT GETDATE() TODAY')
END
GO

ALTER VIEW WNDE_NODE_DEPENDENCY
AS
	SELECT ROW_NUMBER() OVER (ORDER BY WNDE_N_DEPENDENT_NODE_ID) AS WNDE_N_ID,
		   *
	FROM (SELECT	D.LNK_N_PART_ID AS WNDE_N_DEPENDENT_NODE_ID -- MOD ATALHO DESTINO PARA ATALHOS ORIGEM
					, D.LNK_N_CODIGO AS WNDE_N_DEPENDENT_ID
					, O.LNK_N_PART_ID AS WNDE_N_DEPENDENCY_NODE_ID
					, O.LNK_N_CODIGO AS WNDE_N_DEPENDENCY_ID,
					1 as WNDE_N_DEPENDENT_POSITION,
					2 as WNDE_N_DEPENDENCY_POSITION
			FROM	WLNK_LINK D
			INNER JOIN WLNK_LINK O ON O.LNK_N_PARENTID = D.LNK_N_CODIGO 
			WHERE   D.LNK_N_DIRECAO = 2
			UNION ALL
			SELECT	O.LNK_N_PART_ID AS WNDE_N_DEPENDENT_NODE_ID  -- MOD ATALHO ORIGEM PARA ATALHO DESTINO
					, O.LNK_N_CODIGO AS WNDE_N_DEPENDENT_ID
					, D.LNK_N_PART_ID AS WNDE_N_DEPENDENCY_NODE_ID
					, D.LNK_N_CODIGO AS WNDE_N_DEPENDENCY_ID,
					2 as WNDE_N_DEPENDENT_POSITION,
					1 as WNDE_N_DEPENDENCY_POSITION
			FROM	WLNK_LINK O
			INNER JOIN WLNK_LINK D ON O.LNK_N_PARENTID = D.LNK_N_CODIGO 
			WHERE   O.LNK_N_DIRECAO = 1
			UNION ALL
			SELECT	ETC_N_NOD_N_ID AS WNDE_N_DEPENDENT_NODE_ID,  -- CONDENSADOR PARA ETAPAS QUE ELE DEPENDE
					ETC_N_NOD_N_ID AS WNDE_N_DEPENDENT_ID,
					NOD_N_ID AS WNDE_N_DEPENDENCY_NODE_ID,
					ETC_N_ETA_N_CODIGO AS WNDE_N_DEPENDENCY_ID,
					0 as WNDE_N_DEPENDENT_POSITION,
					0 as WNDE_N_DEPENDENCY_POSITION
			FROM	WETC_ETAPA_CONDENSADOR
					INNER JOIN WNOD_NODE ON ETC_N_ETA_N_CODIGO = NOD_ATV_N_CODIGO 
						AND NOD_MOD_C_ITEMID in ('CA4F303D-F89E-4B92-9D4B-D8071358C57F', '36d24f1d-15de-47f8-9300-f85057d28737')
			UNION ALL
			SELECT N1.NOD_N_ID WNDE_N_DEPENDENT_NODE_ID -- MOD SUBPROCESSO PARA INICIO DE SUBPROCESSO
				 , N1.NOD_ATV_N_CODIGO WNDE_N_DEPENDENT_ID
				 , N2.NOD_N_ID WNDE_N_DEPENDENCY_NODE_ID
				 , N2.NOD_ATV_N_CODIGO WNDE_N_DEPENDENCY_NODE_ID
				 , 2 AS WNDE_N_DEPENDENT_POSITION
				 , 1 AS WNDE_N_DEPENDENCY_POSITION
			FROM MWSUB_SUBPROCESS S
			INNER JOIN WNOD_NODE N1 ON SUB_N_ATV_N_CODIGO = N1.NOD_ATV_N_CODIGO 
			INNER JOIN WNOD_NODE N2 ON SUB_N_CALL_ATIVIDADE = N2.NOD_ATV_N_CODIGO
			WHERE N1.NOD_MOD_C_ITEMID = '1D6755CE-6FDB-423F-9DB4-897662DA1BD5' AND N2.NOD_MOD_C_ITEMID = 'E673CA71-CA02-48F4-9FAF-701B880E39E2'
			UNION ALL
			SELECT N2.NOD_N_ID WNDE_N_DEPENDENT_NODE_ID -- INICIO DE SUBPROCESSO PARA MOD SUBPROCESSO
				 , N2.NOD_ATV_N_CODIGO WNDE_N_DEPENDENT_ID
				 , N1.NOD_N_ID WNDE_N_DEPENDENCY_NODE_ID
				 , N1.NOD_ATV_N_CODIGO WNDE_N_DEPENDENCY_NODE_ID
				 , 1 AS WNDE_N_DEPENDENT_POSITION
				 , 2 AS WNDE_N_DEPENDENCY_POSITION
			FROM MWSUB_SUBPROCESS S
			INNER JOIN WNOD_NODE N1 ON SUB_N_ATV_N_CODIGO = N1.NOD_ATV_N_CODIGO 
			INNER JOIN WNOD_NODE N2 ON SUB_N_CALL_ATIVIDADE = N2.NOD_ATV_N_CODIGO
			WHERE N1.NOD_MOD_C_ITEMID = '1D6755CE-6FDB-423F-9DB4-897662DA1BD5' AND N2.NOD_MOD_C_ITEMID = 'E673CA71-CA02-48F4-9FAF-701B880E39E2'
		) AS X
GO

--#################################################################################################################################

IF NOT OBJECT_ID('NodeLinkProcess') IS NULL
BEGIN
	DROP VIEW NodeLinkProcess
END
GO

CREATE VIEW NodeLinkProcess
AS
	SELECT 
		NOL_N_ID,
		NOL_ORIGIN_NOP_N_ID,
		NOL_DESTINATION_NOP_N_ID,
		NOL_C_COLOR,
		NOL_C_TITLE,
		NOL_EVE_N_CODIGO,
		NOL_C_IDENTIFIER,
		NOD_PRO_N_CODIGO EVE_N_PRO_N_CODIGO   
	FROM 
		WNOL_NODELINK 
		INNER JOIN WNOP_NODEPORT on NOL_ORIGIN_NOP_N_ID = NOP_N_ID 
		INNER JOIN WNOD_NODE ON NOP_NOD_N_ID = NOD_N_ID
GO

--#####################################################################################################################

IF NOT OBJECT_ID('UsuariosItemProcesso') IS NULL
BEGIN
	DROP VIEW UsuariosItemProcesso
END
GO

CREATE VIEW UsuariosItemProcesso
AS
	SELECT DISTINCT	
		ETE_N_USR_N_ID USERID,
		ETI_N_IPR_N_CODIGO ITEMPROCESSOID 
	FROM 
		WETE_ETAPA_ITEM_EDITORS
		INNER JOIN WETI_ETAPA_ITEM ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO
		WHERE ETE_N_USR_N_ID > 0
	UNION
		SELECT DISTINCT
		HIS_N_USR_EXECUTOR USERID,
		IPR_N_CODIGO ITEMPROCESSOID
	FROM 
		WHIS_HISTORICO_ITEM 
		INNER JOIN WIPR_ITEM_PROCESSO ON HIS_N_IWF_N_CODIGO = IPR_N_IWF_N_CODIGO
		WHERE HIS_N_USR_EXECUTOR > 0
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelEtapasItens') IS NULL
BEGIN
	DROP VIEW PainelEtapasItens
END
GO
CREATE VIEW PainelEtapasItens
AS
SELECT
	IPR_N_CODIGO,
	IWF_N_CODIGO, 
	IWF_N_USU_OWNER, 
	ETI_N_CODIGO,
	IWF_C_NOME,
	PRO_N_CODIGO,
	PRO_C_NOME,
	ETA_N_CODIGO,
	ETA_C_NOME,
	IWF_D_DATAINICIO,
	IWF_C_STATUS,
	ETI_N_USU_VINCULADO,
	ETE_N_USR_N_ID AS USERID,
	ETI_D_DEADLINE AS ETIDEADLINE,
	ISNULL(ETSETI.ETS_N_CODIGO,0) AS ETSETI,
	ISNULL(ETSETI.ETS_C_NOME,'N/A') AS ETSETINOME,
	ISNULL(ETSETI.ETS_C_COR,'#AEAEAE') AS ETSETICOR,
	IPR_D_SLAFINAL AS IPRDEADLINE,
	ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
	ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
	ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR
FROM 
	WETI_ETAPA_ITEM
	INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_CODIGO = ETI_N_IPR_N_CODIGO
	INNER JOIN WIWF_ITEM_WORKFLOW ON IWF_N_CODIGO = IPR_N_IWF_N_CODIGO
	INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
	INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO
	INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO 
	LEFT JOIN WETS_ETAPA_SLA AS ETSETI ON ETSETI.ETS_N_CODIGO = ETI_N_ETS_N_CODIGO
	LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
GO

GO
--CHECA SE A TABELA ESTÁ CORRETA POIS JÁ HOUVE PROBLEMA AO APLICAR O PACOTE EM CLIENTE QUE JÁ TINHA A TABELA MAS ESTAVA ERRADA E NÃO FOI CORRIGIDA.
DECLARE @COLS INT
SELECT @COLS = COUNT(*) FROM SYS.all_columns WHERE OBJECT_ID = OBJECT_ID('WMUX_MARKER_UPDATE_EXECUTION')


IF (@COLS > 0 AND @COLS <> 3) OR EXISTS (SELECT 1 FROM SYS.all_columns WHERE OBJECT_ID = OBJECT_ID('WMUX_MARKER_UPDATE_EXECUTION') AND NAME <> 'MUX_C_IDENTIFIER' AND NAME <> 'MUX_C_TYPE' AND NAME <> 'MUX_D_UPDATE')
BEGIN
	--REMOVE A TABELA SE TIVER ALGUMA COLUNA QUE NÃO FOR UMA DAS 3 LISTADAS OU SE TIVER UM NÚMERO INCORRETO DE COLUNAS, PARA QUE POSSA SER CRIADA CORRETA
	DROP TABLE WMUX_MARKER_UPDATE_EXECUTION
END
GO

-- ALTERAÇÃO PARA MELHORIA DE PERFORMANCE NO RELATORIO DE MARCADORES E NA FINALIZACAO DE ITENS
IF OBJECT_ID('WMUX_MARKER_UPDATE_EXECUTION') IS NULL
BEGIN 
	CREATE TABLE WMUX_MARKER_UPDATE_EXECUTION (
		MUX_C_IDENTIFIER VARCHAR(300),
		MUX_C_TYPE VARCHAR(20),
		MUX_D_UPDATE DATETIME
		CONSTRAINT PK_WMUX_MARKER_UPDATE_EXECUTION PRIMARY KEY CLUSTERED (MUX_C_IDENTIFIER ASC)
	)
END
GO
IF OBJECT_ID('WMVL_MARKER_VALUES') IS NULL
BEGIN 
	CREATE TABLE WMVL_MARKER_VALUES(
		MVL_N_ID			INT IDENTITY(1,1) NOT NULL,
		MVL_C_FIELDNAME		VARCHAR(400) NOT NULL,
		MVL_C_VALUE			VARCHAR(400),
		CONSTRAINT PK_WMVL_MARKER_VALUES PRIMARY KEY CLUSTERED (MVL_N_ID ASC)
	)
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MVL_C_ACTIVITYID' AND OBJECT_ID = OBJECT_ID('WMVL_MARKER_VALUES'))
BEGIN
	ALTER TABLE WMVL_MARKER_VALUES add MVL_C_ACTIVITYID	INT NOT NULL constraint DF_MVL_ACTIVITY DEFAULT 0
END
GO

IF NOT OBJECT_ID('DF_MVL_ACTIVITY') IS NULL 
BEGIN
	ALTER TABLE WMVL_MARKER_VALUES DROP CONSTRAINT DF_MVL_ACTIVITY
END
GO

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'IEX_N_IWF_N_CODIGO' AND OBJECT_ID = OBJECT_ID('WIEX_ITEM_EXECUCAO'))
BEGIN
	ALTER TABLE WIEX_ITEM_EXECUCAO ADD IEX_N_IWF_N_CODIGO INTEGER NOT NULL CONSTRAINT DF_IEX_IWF DEFAULT (0)
	
	DECLARE @EXECQRY AS VARCHAR(500)
	SET @EXECQRY= 'UPDATE A
					SET A.IEX_N_IWF_N_CODIGO = P.IPR_N_IWF_N_CODIGO 
					FROM WIEX_ITEM_EXECUCAO AS A INNER JOIN WIPR_ITEM_PROCESSO P ON IEX_N_IPR_N_CODIGO = IPR_N_CODIGO'
	EXEC (@EXECQRY)

	ALTER TABLE WIEX_ITEM_EXECUCAO DROP CONSTRAINT DF_IEX_IWF

	CREATE NONCLUSTERED INDEX IX_WIEX_DATAEXEC ON dbo.WIEX_ITEM_EXECUCAO
	(
	IEX_D_EXECUCAO
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	CREATE NONCLUSTERED INDEX IX_WIEX_EXECITEMS ON dbo.WIEX_ITEM_EXECUCAO
	(
	IEX_N_IWF_N_CODIGO,
	IEX_N_TIPOACAO,
	IEX_N_ACAOID
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

	
	CREATE NONCLUSTERED INDEX IX_WHIS_EXECITEMS ON dbo.WHIS_HISTORICO_ITEM
	(
	HIS_N_IWF_N_CODIGO,
	HIS_N_TIPOACAO,
	HIS_N_ACAOID
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	
END
GO

IF OBJECT_ID('FK_WMRS_MARKER_RESULT_WMKR_MARKER') IS NULL
BEGIN
	DELETE FROM WMRS_MARKER_RESULT WHERE MRS_MKR_N_CODIGO NOT IN (SELECT MKR_N_CODIGO FROM WMKR_MARKER)
	ALTER TABLE WMRS_MARKER_RESULT ADD CONSTRAINT
		FK_WMRS_MARKER_RESULT_WMKR_MARKER FOREIGN KEY
		(MRS_MKR_N_CODIGO) REFERENCES WMKR_MARKER (MKR_N_CODIGO) ON DELETE  CASCADE
END 
GO

IF OBJECT_ID('FK_WMRS_MARKER_RESULT_FINISHED_WMKR_MARKER') IS NULL
BEGIN
	DELETE FROM WMRS_MARKER_RESULT_FINISHED WHERE MRS_MKR_N_CODIGO NOT IN (SELECT MKR_N_CODIGO FROM WMKR_MARKER)
	ALTER TABLE WMRS_MARKER_RESULT_FINISHED ADD CONSTRAINT
		FK_WMRS_MARKER_RESULT_FINISHED_WMKR_MARKER FOREIGN KEY
		(MRS_MKR_N_CODIGO) REFERENCES WMKR_MARKER (MKR_N_CODIGO) ON UPDATE  NO ACTION 
		ON DELETE  CASCADE 
END	
GO

--#####################################################################################################################
/*
********************************************************************************************************************
VIEW PARA AJUSTES DE OBSERVADORES
********************************************************************************************************************
*/
IF NOT OBJECT_ID('ItemProcessoObservadores') IS NULL
BEGIN
	DROP VIEW ItemProcessoObservadores
END
GO

CREATE VIEW ItemProcessoObservadores
AS 
	SELECT 
		  MAX(IEX_N_CODIGO) ITEMID,
		  IPR_N_CODIGO,
		  MAX(IPR_N_PRO_N_CODIGO) IPR_N_PRO_N_CODIGO,
		  IPR_N_FINALIZADO,
		  MAX(OBS_C_LISTAACESSO) OBS_C_LISTAACESSO
	FROM 
		  WIEX_ITEM_EXECUCAO
		  INNER JOIN WIPR_ITEM_PROCESSO ON IEX_N_IPR_N_CODIGO = IPR_N_CODIGO      
		  INNER JOIN WOBS_OBSERVADOR ON OBS_N_CODIGO = IEX_N_ACAOID 
	WHERE
		IEX_N_TIPOACAO = 4
		AND IEX_N_CODIGO In (
			SELECT MAX(IEX_N_CODIGO)
			FROM WIEX_ITEM_EXECUCAO
			WHERE IEX_N_TIPOACAO = 4
			GROUP BY IEX_N_IPR_N_CODIGO
		)
	GROUP BY
		  IPR_N_CODIGO,
		  IPR_N_FINALIZADO

	UNION ALL

	SELECT 
		  MAX(HIF_N_CODIGO) ITEMID,
		  IPR_N_CODIGO,
		  MAX(IPR_N_PRO_N_CODIGO) IPR_N_PRO_N_CODIGO,
		  IPR_N_FINALIZADO,
		  MAX(OBS_C_LISTAACESSO) OBS_C_LISTAACESSO
	FROM 
		  WHIF_HISTORICO_FINALIZADO
		  INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO  = HIF_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIF_N_PRO_N_CODIGO 
		  INNER JOIN WOBS_OBSERVADOR ON OBS_N_CODIGO = HIF_N_ACAOID 
	WHERE
		HIF_N_TIPOACAO  = 4
		AND HIF_N_CODIGO In (
			SELECT MAX(HIF_N_CODIGO)
			FROM WHIF_HISTORICO_FINALIZADO
			WHERE HIF_N_TIPOACAO = 4
			GROUP BY HIF_N_IWF_N_CODIGO,HIF_N_PRO_N_CODIGO
		)
	GROUP BY
		  IPR_N_CODIGO,
		  IPR_N_FINALIZADO

GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelListagemUser') IS NULL
BEGIN
	DROP VIEW PainelListagemUser
END
GO

CREATE VIEW PainelListagemUser
AS
	SELECT 
	ETI_N_CODIGO,
	ETI_D_INICIO, 
	ETI_N_USU_VINCULADO,
	ETI_C_APELIDOETAPA,
	IWF_N_CODIGO, 
	IWF_C_NOME,
	IWF_N_USU_OWNER,
	IWF_C_STATUS, 
	IWF_C_PARAM1,
	IWF_C_PARAM2,
	IWF_C_PARAM3,
	IWF_C_PARAM4,
	IWF_C_PARAM5,
	IWF_N_READONLY,
	IPR_N_COUNTERID,
	IPR_N_CODIGO,
	IPR_D_DATAINICIO,
	PRO_N_CODIGO,
	PRO_C_NOME,
	PRO_C_GESTORES,
	PRO_N_USECOUNTER, 
	ETA_N_CODIGO,
	ETA_C_NOME,
	ETA_C_GESTORES,
	ETI_D_DEADLINE AS ETIDEADLINE,
	ISNULL(ETSETI.ETS_N_CODIGO,0) AS ETSETI,
	ISNULL(ETSETI.ETS_C_NOME,'N/A') AS ETSETINOME,
	ISNULL(ETSETI.ETS_C_COR,'#AEAEAE') AS ETSETICOR,
	IPR_D_SLAFINAL AS IPRDEADLINE,
	ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
	ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
	ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR,
	ETE_N_USR_N_ID,
	ISP_C_TITLE,
	ISP_C_METADATA
FROM 
	WETI_ETAPA_ITEM
	INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO 
	INNER JOIN WIWF_ITEM_WORKFLOW ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO 
	INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO  AND PRO_N_DELETED = 0
	INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO 
	INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO  
	LEFT JOIN WETS_ETAPA_SLA AS ETSETI ON ETSETI.ETS_N_CODIGO = ETI_N_ETS_N_CODIGO
	LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
	LEFT JOIN WISP_ITEM_SUBPROCESS ON ISP_N_ID = ETI_ISP_N_ID
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelListagemStopped') IS NULL
BEGIN
	DROP VIEW PainelListagemStopped
END
GO

CREATE VIEW PainelListagemStopped
AS
	SELECT 
	IWF_N_CODIGO, 
	IWF_C_NOME,
	IWF_N_USU_OWNER,
	IWF_C_STATUS, 
	IWF_C_PARAM1,
	IWF_C_PARAM2,
	IWF_C_PARAM3,
	IWF_C_PARAM4,
	IWF_C_PARAM5,
	IWF_N_READONLY,
	IPR_N_COUNTERID,
	IPR_N_CODIGO,
	IPR_D_DATAINICIO,
	PRO_N_CODIGO,
	PRO_C_NOME,
	PRO_C_GESTORES,
	PRO_N_USECOUNTER, 
	0 ETA_N_CODIGO,
	'N/A' ETA_C_NOME,
	'-1;' ETA_C_GESTORES,
	0 AS ETSETI,
	'N/A' AS ETSETINOME,
	'#AEAEAE' AS ETSETICOR,
	IPR_D_SLAFINAL AS IPRDEADLINE,
	ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
	ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
	ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR,
	'' AS ISP_C_TITLE,
	'' AS ISP_C_METADATA
FROM 
	WIPR_ITEM_PROCESSO  
	INNER JOIN WIWF_ITEM_WORKFLOW ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO 
	INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO  AND PRO_N_DELETED = 0
	LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
WHERE
	IPR_N_FINALIZADO = 0 
	AND IPR_N_CODIGO NOT IN (SELECT ETI_N_IPR_N_CODIGO FROM WETI_ETAPA_ITEM)
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelControle') IS NULL
BEGIN
	DROP VIEW PainelControle
END
GO

CREATE VIEW PainelControle
AS
	SELECT
		'P' + LTRIM(RTRIM(ISNULL(CONVERT(varchar,PRO_N_CODIGO), '0'))) +
		'E' + LTRIM(RTRIM(ISNULL(CONVERT(varchar,ETA_N_CODIGO), '0'))) +
		'S' + LTRIM(RTRIM(ISNULL(CONVERT(varchar,ETS_N_CODIGO), '0'))) ITEMKEY, 
		COUNT(ETI_N_CODIGO) ITEMCOUNT, 
		MAX(PRO_C_NOME) PRO_C_NOME,
		PRO_N_CODIGO,
		MAX(PRO_C_GESTORES) PRO_C_GESTORES, 
		ETA_N_CODIGO,  
		MAX(ETA_C_NOME) ETA_C_NOME,
		MAX(ETA_C_GESTORES) ETA_C_GESTORES,
		ISNULL(ETS_N_CODIGO,0) AS ETS_N_CODIGO,
		MAX(ISNULL(ETS_C_NOME,'N/A')) ETS_C_NOME,
		MAX(ISNULL(ETS_C_COR,'#AEAEAE')) ETS_C_COR
	FROM 
		WETI_ETAPA_ITEM
		INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO 
		INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = ETA_N_PRO_N_CODIGO  AND PRO_N_DELETED = 0
		LEFT JOIN WETS_ETAPA_SLA ON ETS_N_CODIGO = ETI_N_ETS_N_CODIGO 
	GROUP BY PRO_N_CODIGO,ETA_N_CODIGO,ETS_N_CODIGO 
	UNION
	SELECT
		'P' + LTRIM(RTRIM(ISNULL(CONVERT(varchar,PRO_N_CODIGO), '0'))) +	'E0'  +
		'S' + LTRIM(RTRIM(ISNULL(CONVERT(varchar,ETS_N_CODIGO), '0'))) ITEMKEY, 
		COUNT(IPR_N_CODIGO) ITEMCOUNT, 
		MAX(PRO_C_NOME) PRO_C_NOME,
		-1 * PRO_N_CODIGO,
		MAX(PRO_C_GESTORES) PRO_C_GESTORES, 
		0 ETA_N_CODIGO,  
		'N/A' ETA_C_NOME,
		'-1;' ETA_C_GESTORES,
		ISNULL(ETS_N_CODIGO,0) AS ETS_N_CODIGO,
		MAX(ISNULL(ETS_C_NOME,'N/A')) ETS_C_NOME,
		MAX(ISNULL(ETS_C_COR,'#AEAEAE')) ETS_C_COR
	FROM
		WIPR_ITEM_PROCESSO 
		INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO  AND PRO_N_DELETED = 0
		LEFT JOIN WETS_ETAPA_SLA ON ETS_N_CODIGO = IPR_N_CURRENTSLA 
	WHERE 
		IPR_N_FINALIZADO = 0 
		AND IPR_N_CODIGO NOT IN (SELECT ETI_N_IPR_N_CODIGO FROM WETI_ETAPA_ITEM )
	GROUP BY PRO_N_CODIGO, ETS_N_CODIGO
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelUsers') IS NULL
BEGIN
	DROP VIEW PainelUsers
END
GO

CREATE VIEW PainelUsers
AS
	SELECT
		'P' + LTRIM(RTRIM(CONVERT(varchar,PRO_N_CODIGO))) +
		'E' + LTRIM(RTRIM(CONVERT(varchar,ETA_N_CODIGO))) +
		'U' + LTRIM(RTRIM(CONVERT(varchar,ETE_N_USR_N_ID))) + 
		'V' + cast(ETI_N_USU_VINCULADO as varchar) ITEMKEY, 
		ETE_N_USR_N_ID AS USERID,
		PRO_N_CODIGO,  
		MAX(PRO_C_GESTORES) PRO_C_GESTORES,
		ETA_N_CODIGO, 
		MAX(ETA_C_GESTORES) ETA_C_GESTORES,
		COUNT(1) AS ITEMCOUNT,
		ETI_N_USU_VINCULADO
	FROM
		WETE_ETAPA_ITEM_EDITORS 
		INNER JOIN WETI_ETAPA_ITEM ON ETI_N_CODIGO = ETE_N_ETI_N_CODIGO 
		INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO
		INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = ETA_N_PRO_N_CODIGO AND PRO_N_DELETED = 0
	GROUP BY 
		ETE_N_USR_N_ID,
		PRO_N_CODIGO,
		ETA_N_CODIGO,
		ETI_N_USU_VINCULADO
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelSLA') IS NULL
BEGIN
	DROP VIEW PainelSLA
END
GO

CREATE VIEW PainelSLA
AS
	SELECT
		ETI_N_CODIGO,
		IPR_N_CODIGO,
		IPR_D_DATAINICIO,
		PRO_N_CODIGO,
		PRO_C_GESTORES,
		ETA_N_CODIGO,
		ETA_C_GESTORES,
		ETI_D_DEADLINE AS ETIDEADLINE,
		ISNULL(ETSETI.ETS_N_CODIGO,0) AS ETSETI,
		ISNULL(ETSETI.ETS_C_NOME,'N/A') AS ETSETINOME,
		ISNULL(ETSETI.ETS_C_COR,'#AEAEAE') AS ETSETICOR,
		IPR_D_SLAFINAL AS IPRDEADLINE,
		ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
		ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
		ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR
	FROM
		WETI_ETAPA_ITEM  
		INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_CODIGO = ETI_N_IPR_N_CODIGO
		INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0 
		INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO 
		LEFT JOIN WETS_ETAPA_SLA AS ETSETI ON ETSETI.ETS_N_CODIGO = ETI_N_ETS_N_CODIGO
		LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
GO

IF NOT OBJECT_ID('PainelSLAEtapa') IS NULL
BEGIN
	DROP VIEW PainelSLAEtapa
END
GO

CREATE VIEW PainelSLAEtapa
AS
	SELECT
		CONVERT(VARCHAR,ETA_N_CODIGO) + '_' + CONVERT(VARCHAR,ETSETI.ETS_N_CODIGO) AS IDENTIFIER,
		PRO_N_CODIGO,
		MAX(PRO_C_GESTORES) AS PRO_C_GESTORES,
		ETA_N_CODIGO,
		MAX(ETA_C_NOME) AS ETA_C_NOME,
		MAX(ETA_C_GESTORES) AS ETA_C_GESTORES,
		ISNULL(ETSETI.ETS_N_CODIGO,0) AS ETSETI,
		ISNULL(ETSETI.ETS_C_NOME,'N/A') AS ETSETINOME,
		ISNULL(ETSETI.ETS_C_COR,'#AEAEAE') AS ETSETICOR,
		ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
		ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
		ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR,
		COUNT (*) AS ITENS
	FROM
		WETI_ETAPA_ITEM  
		INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_CODIGO = ETI_N_IPR_N_CODIGO
		INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0  
		INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO 
		LEFT JOIN WETS_ETAPA_SLA AS ETSETI ON ETSETI.ETS_N_CODIGO = ETI_N_ETS_N_CODIGO
		LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
	GROUP BY 
		ETA_N_CODIGO,
		ETSETI.ETS_N_CODIGO,
		ETSETI.ETS_C_NOME,
		ETSETI.ETS_C_COR,
		ETSIPR.ETS_N_CODIGO,
		ETSIPR.ETS_C_NOME,
		ETSIPR.ETS_C_COR,
		PRO_N_CODIGO
GO

--#####################################################################################################################

IF NOT OBJECT_ID('PainelListagem') IS NULL
BEGIN
	DROP VIEW PainelListagem
END
GO

CREATE VIEW PainelListagem
AS
	SELECT 
	ETI_N_CODIGO,
	ETI_D_INICIO, 
	ETI_N_USU_VINCULADO,
	ETI_C_APELIDOETAPA,
	IWF_N_CODIGO, 
	IWF_C_NOME,
	IWF_N_USU_OWNER,
	IWF_C_STATUS, 
	IWF_C_PARAM1,
	IWF_C_PARAM2,
	IWF_C_PARAM3,
	IWF_C_PARAM4,
	IWF_C_PARAM5,
	IWF_N_READONLY,
	IPR_N_COUNTERID,
	IPR_N_CODIGO,
	IPR_D_DATAINICIO,
	PRO_N_CODIGO,
	PRO_C_NOME,
	PRO_C_GESTORES,
	PRO_N_USECOUNTER, 
	ETA_N_CODIGO,
	ETA_C_NOME, 
	ETA_C_GESTORES,
	ETI_D_DEADLINE AS ETIDEADLINE,
	ISNULL(ETSETI.ETS_N_CODIGO,0) AS ETSETI,
	ISNULL(ETSETI.ETS_C_NOME,'N/A') AS ETSETINOME,
	ISNULL(ETSETI.ETS_C_COR,'#AEAEAE') AS ETSETICOR,
	IPR_D_SLAFINAL AS IPRDEADLINE,
	ISNULL(ETSIPR.ETS_N_CODIGO,0) AS ETSIPR,
	ISNULL(ETSIPR.ETS_C_NOME,'N/A') AS ETSIPRNOME,
	ISNULL(ETSIPR.ETS_C_COR,'#AEAEAE') AS ETSIPRCOR,
	ISP_C_TITLE,
	ISP_C_METADATA
FROM 
	WETI_ETAPA_ITEM
	INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO 
	INNER JOIN WIWF_ITEM_WORKFLOW ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO 
	INNER JOIN WPRO_PROCESSO ON PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND PRO_N_DELETED = 0 
	INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = ETI_N_ETA_N_CODIGO 
	LEFT JOIN WETS_ETAPA_SLA AS ETSETI ON ETSETI.ETS_N_CODIGO = ETI_N_ETS_N_CODIGO
	LEFT JOIN WETS_ETAPA_SLA AS ETSIPR ON ETSIPR.ETS_N_CODIGO = IPR_N_CURRENTSLA
	LEFT JOIN WISP_ITEM_SUBPROCESS ON ISP_N_ID = ETI_ISP_N_ID
GO

--#####################################################################################################################

IF NOT OBJECT_ID('ZuriEtapasItem') IS NULL
BEGIN
	DROP VIEW ZuriEtapasItem
END
GO

IF NOT OBJECT_ID('ZuriMarkerEvents') IS NULL
BEGIN
	DROP VIEW ZuriMarkerEvents
END
GO
IF NOT OBJECT_ID('ZuriMarkersDetailActive') IS NULL
BEGIN
	DROP VIEW ZuriMarkersDetailActive
END
GO

IF NOT OBJECT_ID('ZuriMarkersDetailClosed') IS NULL
BEGIN
	DROP VIEW ZuriMarkersDetailClosed
END
GO

IF NOT OBJECT_ID('ZuriMarkersDetail') IS NULL
BEGIN
	DROP VIEW ZuriMarkersDetail
END
GO

IF NOT OBJECT_ID('ZuriMarkerStepItems') IS NULL
BEGIN
	DROP VIEW ZuriMarkerStepItems
END
GO

CREATE VIEW ZuriMarkerStepItems
AS
	SELECT
		ETI_N_IPR_N_CODIGO AS ITEMPROCESSID,
		ETI_ISP_N_ID AS SUBPROCESSID,
		'<steps>' + STUFF((
			SELECT '<step name="' + ISNULL(ETA_C_NOME, '') + '" etiid="' + CAST(EI2.ETI_N_CODIGO AS VARCHAR(15)) + 
				'" stepalias="' + CAST(ISNULL(EI2.ETI_C_APELIDOETAPA, '') AS VARCHAR(100)) + 
				'" stepid="' + CAST(EI2.ETI_N_ETA_N_CODIGO AS VARCHAR(15)) + 
				'" userid="' + CAST(EI2.ETI_N_USU_VINCULADO AS VARCHAR(15)) + 
				'" stepstart="' + ISNULL(CONVERT(NVARCHAR(30), EI2.ETI_D_INICIO , 120), '') + '" />'
			FROM  WETI_ETAPA_ITEM EI2
			INNER JOIN WETA_ETAPA_PROCESSO ON ETA_N_CODIGO = EI2.ETI_N_ETA_N_CODIGO
			WHERE EI2.ETI_N_IPR_N_CODIGO = EI1.ETI_N_IPR_N_CODIGO AND EI2.ETI_ISP_N_ID = EI1.ETI_ISP_N_ID
			ORDER BY ETI_N_CODIGO
			FOR XML PATH(''), TYPE).value('.', 'varchar(max)'), 1, 0, '') + '</steps>' AS ITEMSTEPS
	FROM WETI_ETAPA_ITEM EI1
	GROUP BY ETI_N_IPR_N_CODIGO, ETI_ISP_N_ID 
GO

IF EXISTS(SELECT TOP 1 1 FROM WETI_ETAPA_ITEM WHERE ETI_ISP_N_ID IS NULL)
BEGIN
	UPDATE WETI_ETAPA_ITEM
	SET ETI_ISP_N_ID = 0
	WHERE ETI_ISP_N_ID IS NULL
	 
	DELETE WMRS_MARKER_RESULT
	DELETE WMRS_MARKER_RESULT_FINISHED
END
GO


IF NOT OBJECT_ID('ZuriMarkersListActive') IS NULL
BEGIN
	DROP VIEW ZuriMarkersListActive
END
GO

CREATE VIEW [ZuriMarkersListActive]
AS
	SELECT 
		MRS_N_CODIGO AS ID,
		MRS_IWF_N_CODIGO AS ITEMWORKFLOWID,
		MRS_IPR_N_CODIGO AS ITEMPROCESSID,
		MRS_ISP_N_ID AS SUBPROCESSID,
		MRS_PRO_N_CODIGO AS PROCESSID,
		MRS_N_USR_EXEC_ID AS EXECUTORID,
		MRS_D_EXEC_DATE AS EXECDATE,
		MRS_MKR_C_NAME AS MARKERNAME,
		MRS_MKR_C_VALUE AS MARKERVALUE,
		0 AS FINISHED,
		IWF_D_DATAINICIO AS ITEMSTART,
		IWF_D_DATAFIM AS ITEMEND,
		IWF_C_NOME AS ITEMNAME,
		IWF_C_STATUS AS ITEMSTATUS,
		IWF_N_USU_OWNER AS ITEMOWNER,
		IWF_C_PARAM1 AS ITEMPARAM1,
		IWF_C_PARAM2 AS ITEMPARAM2,
		IWF_C_PARAM3 AS ITEMPARAM3,
		IWF_C_PARAM4 AS ITEMPARAM4,
		IWF_C_PARAM5 AS ITEMPARAM5,
		PRO_C_NOME AS PROCESSNAME,
		ISNULL(ISP_C_TITLE,ISP_C_IDENTIFIER) AS SUBPROCESSTITLE,
		ISP_N_LOOPITEM AS LOOPITEM,
		ITEMSTEPS AS ITEMSTEPS,
		IWF_C_METADATA AS ITEMMETADATA
	FROM WMRS_MARKER_RESULT
	INNER JOIN WIWF_ITEM_WORKFLOW On IWF_N_CODIGO = MRS_IWF_N_CODIGO
	INNER JOIN WPRO_PROCESSO On PRO_N_CODIGO = MRS_PRO_N_CODIGO AND PRO_N_DELETED = 0
	LEFT JOIN WISP_ITEM_SUBPROCESS ON ISP_N_ID = MRS_ISP_N_ID
	LEFT JOIN ZuriMarkerStepItems ON ITEMPROCESSID = MRS_IPR_N_CODIGO AND SUBPROCESSID = MRS_ISP_N_ID 
GO

IF NOT OBJECT_ID('ZuriMarkersListClosed') IS NULL
BEGIN
	DROP VIEW ZuriMarkersListClosed
END
GO

CREATE VIEW ZuriMarkersListClosed
AS
	SELECT 
		MRS_N_CODIGO AS ID,
		MRS_IWF_N_CODIGO AS ITEMWORKFLOWID,
		MRS_IPR_N_CODIGO AS ITEMPROCESSID,
		MRS_ISP_N_ID AS SUBPROCESSID,
		MRS_PRO_N_CODIGO AS PROCESSID,
		MRS_N_USR_EXEC_ID AS EXECUTORID,
		MRS_D_EXEC_DATE AS EXECDATE,
		MRS_MKR_C_NAME AS MARKERNAME,
		MRS_MKR_C_VALUE AS MARKERVALUE,
		1 AS FINISHED,
		IWF_D_DATAINICIO AS ITEMSTART,
		IWF_D_DATAFIM AS ITEMEND,
		IWF_C_NOME AS ITEMNAME,
		IWF_C_STATUS AS ITEMSTATUS,
		IWF_N_USU_OWNER AS ITEMOWNER,
		IWF_C_PARAM1 AS ITEMPARAM1,
		IWF_C_PARAM2 AS ITEMPARAM2,
		IWF_C_PARAM3 AS ITEMPARAM3,
		IWF_C_PARAM4 AS ITEMPARAM4,
		IWF_C_PARAM5 AS ITEMPARAM5,
		PRO_C_NOME AS PROCESSNAME,
		ISNULL(ISP_C_TITLE,ISP_C_IDENTIFIER) AS SUBPROCESSTITLE,
		ISNULL(ISP_N_LOOPITEM,0) AS LOOPITEM,
		'' AS ITEMSTEPS,
		IWF_C_METADATA AS ITEMMETADATA
	FROM WMRS_MARKER_RESULT_FINISHED
	INNER JOIN WIWF_ITEM_WORKFLOW_FINALIZADO On IWF_N_CODIGO = MRS_IWF_N_CODIGO
	INNER JOIN WPRO_PROCESSO On PRO_N_CODIGO = MRS_PRO_N_CODIGO AND PRO_N_DELETED = 0
	LEFT JOIN WISP_ITEM_SUBPROCESS_FINALIZADO ON ISP_N_ID = MRS_ISP_N_ID
GO

IF NOT OBJECT_ID('ZuriMarkersList') IS NULL
BEGIN
	DROP VIEW ZuriMarkersList
END
GO
CREATE VIEW [ZuriMarkersList]
AS
	Select 
		ID, 
		ITEMWORKFLOWID,	
		ITEMPROCESSID,
		SUBPROCESSID,
		PROCESSID,
		EXECUTORID,
		EXECDATE,
		MARKERNAME,
		MARKERVALUE,
		FINISHED,
		ITEMSTART,
		ITEMEND,
		ITEMNAME,
		ITEMSTATUS,
		ITEMOWNER,
		ITEMPARAM1,
		ITEMPARAM2,
		ITEMPARAM3,
		ITEMPARAM4,
		ITEMPARAM5,
		PROCESSNAME,
		SUBPROCESSTITLE,
		LOOPITEM,
		ITEMSTEPS,
		ITEMMETADATA
	FROM ZuriMarkersListActive
	UNION ALL
	Select
		-1 * ID, 
		ITEMWORKFLOWID,	
		ITEMPROCESSID,
		SUBPROCESSID,
		PROCESSID,
		EXECUTORID,
		EXECDATE,
		MARKERNAME,
		MARKERVALUE,
		FINISHED,
		ITEMSTART,
		ITEMEND,
		ITEMNAME,
		ITEMSTATUS,
		ITEMOWNER,
		ITEMPARAM1,
		ITEMPARAM2,
		ITEMPARAM3,
		ITEMPARAM4,
		ITEMPARAM5,
		PROCESSNAME,
		SUBPROCESSTITLE,
		LOOPITEM,
		ITEMSTEPS,
		ITEMMETADATA
	from ZuriMarkersListClosed
GO

--#####################################################################################################################

IF NOT OBJECT_ID('SlaItemProcesso') IS NULL
BEGIN
	DROP VIEW SlaItemProcesso
END
GO

IF NOT OBJECT_ID('PainelProcessosAtivos') IS NULL
BEGIN
	DROP VIEW PainelProcessosAtivos
END
GO

IF NOT OBJECT_ID('PainelProcessosProdutividade') IS NULL
BEGIN
	DROP VIEW PainelProcessosProdutividade
END
GO

IF NOT OBJECT_ID('PainelProcessosSlaEtapa') IS NULL
BEGIN
	DROP VIEW PainelProcessosSlaEtapa
END
GO

IF NOT OBJECT_ID('PainelSLAItem') IS NULL
BEGIN
	DROP VIEW PainelSLAItem
END
GO

IF NOT OBJECT_ID('PainelEtapasProcessos') IS NULL
BEGIN
	DROP VIEW PainelEtapasProcessos
END
GO

IF NOT OBJECT_ID('PainelProcessos') IS NULL
BEGIN
	DROP VIEW PainelProcessos
END
GO

--#####################################################################################################################
--***** PROCEDURES ****************************************************************************************************
--#####################################################################################################################

IF OBJECT_ID('wpr_CloseItemProcess') IS NULL
	EXEC('CREATE PROCEDURE wpr_CloseItemProcess AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE [dbo].[wpr_CloseItemProcess] (
	@ITEMPROCESSID int
)
AS
BEGIN TRY
	SET NOCOUNT ON
	/* CRIAÇÃO DAS TABELAS TEMPORARIAS */
	 CREATE TABLE #WIPR_ITEM_PROCESSO(
		[IPR_N_CODIGO] [int] NOT NULL,
		[IPR_N_IWF_N_CODIGO] [int] NOT NULL,
		[IPR_N_PRO_N_CODIGO] [int] NOT NULL,
		[IPR_N_COUNTERID] [int] NOT NULL,
		[IPR_N_PRIORIDADE] [int] NOT NULL,
		[IPR_D_DATAINICIO] [datetime] NOT NULL,
		[IPR_C_STATUSCOLOR] [varchar](10) NOT NULL,
		[IPR_N_FINALIZADO] [bit] NOT NULL,
		[IPR_C_LISTAACESSO] [varchar](100) NULL,
		[IPR_N_LOCALIDADE] [int] NOT NULL,
		[IPR_C_METADATA] [text] NULL,
		[IPR_D_SLAFINAL] [datetime] NULL,
		[IPR_N_CURRENTSLA] [int] NULL)
	CREATE TABLE #WIMG_ITEM_MESSAGE(
		[IMG_N_ID] [int] NOT NULL,
		[IMG_IPR_N_CODIGO] [int] NULL,
		[IMG_C_SUBJECT] [varchar](50) NOT NULL,
		[IMG_C_MESSAGE] [varchar](max) NOT NULL,
		[IMG_N_SENDER] [int] NOT NULL,
		[IMG_C_SENDERSTEP] [varchar](50) NOT NULL,
		[IMG_C_RECIPIENT] [varchar](150) NOT NULL,
		[IMG_C_CARBONCOPY] [varchar](150) NOT NULL,
		[IMG_D_DATECREATED] [datetime] NOT NULL,
		[IMG_IMG_N_ID] [int] NULL,
		[IMG_PRO_N_CODIGO] [int] NOT NULL)
	CREATE TABLE #WIMR_ITEM_MESSAGE_READERS(
		[IMR_N_ID] [int] NOT NULL,
		[IMR_USR_N_ID] [int] NOT NULL,
		[IMR_IMG_N_ID] [int] NOT NULL,
		[IMR_B_ISRECIPIENT] [bit] NOT NULL,
		[IMR_B_READ] [bit] NOT NULL,
		[IMR_B_LIKED] [bit] NOT NULL,
		[IMR_B_FLAGGED] [bit] NOT NULL)
	CREATE TABLE #WITR_ITEM_READERS(
		[ITR_N_CODIGO] [int] NOT NULL,
		[ITR_N_IPR_N_CODIGO] [int] NOT NULL,
		[ITR_N_USR_N_ID] [int] NOT NULL)
	CREATE TABLE #WIEX_ITEM_EXECUCAO(
		[IEX_N_CODIGO] [int] NOT NULL,
		[IEX_N_IPR_N_CODIGO] [int] NOT NULL,
		[IEX_N_USR_N_ID] [int] NOT NULL,
		[IEX_N_ETI_N_CODIGO] [int] NOT NULL,
		[IEX_N_ETA_N_CODIGO] [int] NOT NULL,
		[IEX_D_EXECUCAO] [datetime] NOT NULL,
		[IEX_N_ACAOID] [int] NOT NULL,
		[IEX_N_TIPOACAO] [int] NOT NULL,
		[IEX_N_EVE_N_ID] [int] NOT NULL,
		[IEX_C_RETURN] [varchar](50) NULL,
		[IEX_ISP_N_ID] [int] NULL,
		[IEX_N_IWF_N_CODIGO] [int] NOT NULL)
	CREATE TABLE #WMRS_MARKER_RESULT(
		[MRS_N_CODIGO] [int] NOT NULL,
		[MRS_IWF_N_CODIGO] [int] NOT NULL,
		[MRS_IPR_N_CODIGO] [int] NOT NULL,
		[MRS_ISP_N_ID] [int] NOT NULL,
		[MRS_PRO_N_CODIGO] [int] NOT NULL,
		[MRS_N_USR_EXEC_ID] [int] NOT NULL,
		[MRS_D_EXEC_DATE] [datetime] NOT NULL,
		[MRS_MKR_C_NAME] [varchar](100) NOT NULL,
		[MRS_MKR_C_VALUE] [varchar](500) NOT NULL,
		[MRS_MKR_N_CODIGO] [int] NULL,
		[MRS_ETI_N_CODIGO] [int] NULL)		


	/* RECUPERA O ID DO ITEM WORKFLOW RELACIONADO */
	DECLARE @ITEMWORKFLOWID INT
	DECLARE @PROCESSOID INT
	SELECT @ITEMWORKFLOWID = IPR_N_IWF_N_CODIGO, @PROCESSOID = IPR_N_PRO_N_CODIGO FROM WIPR_ITEM_PROCESSO WHERE IPR_N_CODIGO = @ITEMPROCESSID
	
	/* INSERE O ITEM WORKFLOW FINALIZADO SE FOR NECESSARIO */
	IF NOT EXISTS(SELECT 1 FROM WIWF_ITEM_WORKFLOW_FINALIZADO WHERE IWF_N_CODIGO = @ITEMWORKFLOWID)
	INSERT INTO WIWF_ITEM_WORKFLOW_FINALIZADO (IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,
				IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA)
	SELECT IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,
				IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID
				
	/* INSERE O ITEM PROCESSO FINALIZADO */
	INSERT INTO WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,
				IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA)
	SELECT IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,
		   IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA FROM WIPR_ITEM_PROCESSO WHERE IPR_N_CODIGO = @ITEMPROCESSID
		   
	/* MOVE AS MENSAGENS ASSOCIADAS AO ITEM PROCESSO */	
	INSERT INTO WIMG_ITEM_MESSAGE_FINALIZADO (IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_N_ID,IMG_IMG_N_ID,IMG_IPR_N_CODIGO,IMG_D_DATECREATED, IMG_PRO_N_CODIGO) 
	SELECT IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_N_ID,IMG_IMG_N_ID,IMG_IPR_N_CODIGO,IMG_D_DATECREATED, IMG_PRO_N_CODIGO FROM WIMG_ITEM_MESSAGE WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WIMG_ITEM_MESSAGE (IMG_IPR_N_CODIGO,IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_D_DATECREATED,IMG_IMG_N_ID,IMG_PRO_N_CODIGO,IMG_N_ID)
	SELECT IMG_IPR_N_CODIGO,IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_D_DATECREATED,IMG_IMG_N_ID,IMG_PRO_N_CODIGO,IMG_N_ID FROM WIMG_ITEM_MESSAGE WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
	
	/* MOVE OS LEITORES DE MENSAGENS */	
	INSERT INTO WIMR_ITEM_MSG_RDRS_FIM (IMR_N_ID,IMR_IMG_N_ID,IMR_USR_N_ID,IMR_B_READ,IMR_B_ISRECIPIENT, IMR_B_LIKED, IMR_B_FLAGGED)
	SELECT IMR_N_ID,IMR_IMG_N_ID,IMR_USR_N_ID,IMR_B_READ,IMR_B_ISRECIPIENT, IMR_B_LIKED, IMR_B_FLAGGED 
	FROM WIMR_ITEM_MESSAGE_READERS 
	INNER JOIN WIMG_ITEM_MESSAGE ON IMR_IMG_N_ID = IMG_N_ID
	WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WIMR_ITEM_MESSAGE_READERS (IMR_N_ID,IMR_USR_N_ID,IMR_IMG_N_ID,IMR_B_ISRECIPIENT,IMR_B_READ,IMR_B_LIKED,IMR_B_FLAGGED) 
	SELECT IMR_N_ID,IMR_USR_N_ID,IMR_IMG_N_ID,IMR_B_ISRECIPIENT,IMR_B_READ,IMR_B_LIKED,IMR_B_FLAGGED FROM WIMR_ITEM_MESSAGE_READERS INNER JOIN WIMG_ITEM_MESSAGE ON IMR_IMG_N_ID = IMG_N_ID	WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
		
	/* MOVE OS OBSERVADORES DO ITEM */
	INSERT  INTO WIRF_ITEM_READERS_FINALIZADO (IRF_N_IPR_N_CODIGO, IRF_N_USR_N_ID)
	SELECT  ITR_N_IPR_N_CODIGO, ITR_N_USR_N_ID	FROM WITR_ITEM_READERS WHERE ITR_N_IPR_N_CODIGO = @ITEMPROCESSID
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT  INTO #WITR_ITEM_READERS	(ITR_N_CODIGO,ITR_N_IPR_N_CODIGO,ITR_N_USR_N_ID)
	SELECT ITR_N_CODIGO,ITR_N_IPR_N_CODIGO,ITR_N_USR_N_ID FROM WITR_ITEM_READERS WHERE ITR_N_IPR_N_CODIGO = @ITEMPROCESSID

	/* EXCLUI AS INFORMAÇÔES DE ITENS ATIVOS */
	DELETE FROM WITR_ITEM_READERS WHERE ITR_N_IPR_N_CODIGO = @ITEMPROCESSID

	/* MOVE OS INDICADORES DE SUBPROCESSO */
	INSERT INTO WISP_ITEM_SUBPROCESS_FINALIZADO(ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,
												ISP_C_TITLE,ISP_C_METADATA,ISP_N_LOOPITEM, ISP_NOD_C_SCOPE)
	SELECT ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER, 
					   ISP_C_TITLE, ISP_C_METADATA,ISP_N_LOOPITEM, ISP_NOD_C_SCOPE FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_IPR_N_CODIGO = @ITEMPROCESSID
	
	/* TRATA AS INFORMAÇÕES DE EXECUÇÃO PARA FUNCIONAMENTO DOS MARCADORES */
	DECLARE @IEX_IDS TABLE(MARKERID INT)
	/* BUSCA OS MARCADORES QUE NAO SAO REPETIDOS */
	INSERT INTO @IEX_IDS 
		SELECT 
			MAX(IEX_N_CODIGO)
		FROM WIEX_ITEM_EXECUCAO  
		WHERE 
			IEX_N_IPR_N_CODIGO = @ITEMPROCESSID AND 
			(IEX_N_EVE_N_ID = 0 OR IEX_N_EVE_N_ID NOT IN (SELECT HIS_N_EVE_N_ID FROM 
				WHIS_HISTORICO_ITEM WHERE HIS_N_IWF_N_CODIGO = @ITEMWORKFLOWID AND HIS_N_PRO_N_CODIGO = @PROCESSOID))
		GROUP BY 
			IEX_N_IPR_N_CODIGO,  IEX_N_EVE_N_ID, IEX_N_TIPOACAO, IEX_N_ACAOID

	/* MOVE OS MARCADORES NÃO DUPLICADOS PARA A TABELA DE HISTORICO FINALIZADO */
	INSERT INTO WHIF_HISTORICO_FINALIZADO (
		HIF_N_PRO_N_CODIGO,
		HIF_N_IWF_N_CODIGO,
		HIF_N_USR_EXECUTOR,
		HIF_N_ETA_N_CODIGO,
		HIF_N_ETI_N_CODIGO,
		HIF_C_STATUS,
		HIF_D_GRAVACAO,
		HIF_C_DESCRICAO,
		HIF_N_ACAOID,
		HIF_N_TIPOACAO,
		HIF_N_EVE_N_ID,
		HIF_ISP_N_ID,
		HIF_N_LOGLEVEL,
		HIF_N_ATIVO
	)
	SELECT
		@PROCESSOID,
		@ITEMWORKFLOWID,
		IEX_N_USR_N_ID,
		IEX_N_ETA_N_CODIGO,
		IEX_N_ETI_N_CODIGO,
		'',
		IEX_D_EXECUCAO,
		ISNULL(IEX_C_RETURN,''),
		 IEX_N_ACAOID,
		 IEX_N_TIPOACAO,
		 IEX_N_EVE_N_ID,
		 IEX_ISP_N_ID,
		 6,
		 1   
	FROM WIEX_ITEM_EXECUCAO 
	WHERE 
		IEX_N_IPR_N_CODIGO = @ITEMPROCESSID AND
		IEX_N_CODIGO IN (SELECT MARKERID FROM @IEX_IDS)
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WIEX_ITEM_EXECUCAO (IEX_N_CODIGO,IEX_N_IPR_N_CODIGO,IEX_N_USR_N_ID,IEX_N_ETI_N_CODIGO,IEX_N_ETA_N_CODIGO,IEX_D_EXECUCAO,IEX_N_ACAOID,IEX_N_TIPOACAO,IEX_N_EVE_N_ID,IEX_C_RETURN,IEX_ISP_N_ID,IEX_N_IWF_N_CODIGO) 
	SELECT IEX_N_CODIGO,IEX_N_IPR_N_CODIGO,IEX_N_USR_N_ID,IEX_N_ETI_N_CODIGO,IEX_N_ETA_N_CODIGO,IEX_D_EXECUCAO,IEX_N_ACAOID,IEX_N_TIPOACAO,IEX_N_EVE_N_ID,IEX_C_RETURN,IEX_ISP_N_ID,IEX_N_IWF_N_CODIGO FROM WIEX_ITEM_EXECUCAO WHERE IEX_N_IPR_N_CODIGO = @ITEMPROCESSID 

	/* EXCLUI OS MARCADORES DE EXECUCAO DA TABELA ATIVA */
	DELETE FROM WIEX_ITEM_EXECUCAO WHERE IEX_N_IPR_N_CODIGO = @ITEMPROCESSID

	/*MOVE AS INFORMACOES DE RELATORIOS DE MARCADORES PARA A TABELA DE FINALIZADOS */
	INSERT INTO WMRS_MARKER_RESULT_FINISHED(MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO, MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_ETI_N_CODIGO,MRS_MKR_N_CODIGO)
		SELECT MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE, MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_ETI_N_CODIGO,MRS_MKR_N_CODIGO 
		   FROM WMRS_MARKER_RESULT WHERE MRS_IPR_N_CODIGO = @ITEMPROCESSID
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WMRS_MARKER_RESULT (MRS_N_CODIGO,MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_MKR_N_CODIGO,MRS_ETI_N_CODIGO)
	SELECT MRS_N_CODIGO,MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_MKR_N_CODIGO,MRS_ETI_N_CODIGO FROM WMRS_MARKER_RESULT WHERE MRS_IPR_N_CODIGO = @ITEMPROCESSID

	/* EXCLUI OS DADOS DE RELATORIOS DE MARCADORES DA TABELA ATIVA */
	DELETE FROM WMRS_MARKER_RESULT WHERE MRS_IPR_N_CODIGO = @ITEMPROCESSID

	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WIPR_ITEM_PROCESSO (IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA)
	SELECT IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA FROM WIPR_ITEM_PROCESSO WHERE IPR_N_CODIGO = @ITEMPROCESSID

	/* FAZ UMA VERIFICACAO FINAL E EXCLUI O ITEM PROCESSO */
	IF EXISTS(SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_CODIGO = @ITEMPROCESSID)
	DELETE FROM WIPR_ITEM_PROCESSO WHERE IPR_N_CODIGO = @ITEMPROCESSID
	
	DROP TABLE #WIMR_ITEM_MESSAGE_READERS
	DROP TABLE #WIMG_ITEM_MESSAGE 
	DROP TABLE #WMRS_MARKER_RESULT
	DROP TABLE #WIEX_ITEM_EXECUCAO
	DROP TABLE #WITR_ITEM_READERS
	DROP TABLE #WIPR_ITEM_PROCESSO
	SET NOCOUNT OFF

END TRY
BEGIN CATCH
	DECLARE @NEWMSG VARCHAR(MAX)
	SELECT @NEWMSG = 'Error Executing Procedure: ' + 
					 ERROR_PROCEDURE() + ' / Line: ' + 
					 CONVERT(VARCHAR,ERROR_LINE()) + ' / ' + 
					 ERROR_MESSAGE() 
	INSERT INTO WFLOG_LOGMESSAGE
	(LOG_C_CATEGORY, LOG_D_TIMESTAMP, LOG_C_MESSAGE, LOG_N_TYPE, LOG_N_EVENTCODE,
	LOG_N_EVENTDETAIL, LOG_C_USER, LOG_C_URL, LOG_C_USERADDRESS, LOG_C_AUTHTYPE) VALUES 
	('CloseItemProcess', GETDATE(), @NEWMSG, 3, 9999, 1, 1, 'sqlexec', 'sqlserver', 'Forms')
	
	SET IDENTITY_INSERT WIPR_ITEM_PROCESSO ON
	INSERT INTO WIPR_ITEM_PROCESSO (IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA)
	SELECT IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA FROM #WIPR_ITEM_PROCESSO
	SET IDENTITY_INSERT WIPR_ITEM_PROCESSO OFF
	
	SET IDENTITY_INSERT WITR_ITEM_READERS ON
	INSERT  INTO WITR_ITEM_READERS	(ITR_N_CODIGO,ITR_N_IPR_N_CODIGO,ITR_N_USR_N_ID)
	SELECT ITR_N_CODIGO,ITR_N_IPR_N_CODIGO,ITR_N_USR_N_ID FROM #WITR_ITEM_READERS
	SET IDENTITY_INSERT WITR_ITEM_READERS OFF

	SET IDENTITY_INSERT WIEX_ITEM_EXECUCAO ON
	INSERT INTO WIEX_ITEM_EXECUCAO (IEX_N_CODIGO,IEX_N_IPR_N_CODIGO,IEX_N_USR_N_ID,IEX_N_ETI_N_CODIGO,IEX_N_ETA_N_CODIGO,IEX_D_EXECUCAO,IEX_N_ACAOID,IEX_N_TIPOACAO,IEX_N_EVE_N_ID,IEX_C_RETURN,IEX_ISP_N_ID,IEX_N_IWF_N_CODIGO) 
	SELECT IEX_N_CODIGO,IEX_N_IPR_N_CODIGO,IEX_N_USR_N_ID,IEX_N_ETI_N_CODIGO,IEX_N_ETA_N_CODIGO,IEX_D_EXECUCAO,IEX_N_ACAOID,IEX_N_TIPOACAO,IEX_N_EVE_N_ID,IEX_C_RETURN,IEX_ISP_N_ID,IEX_N_IWF_N_CODIGO FROM #WIEX_ITEM_EXECUCAO 
	SET IDENTITY_INSERT WIEX_ITEM_EXECUCAO OFF

	SET IDENTITY_INSERT WMRS_MARKER_RESULT ON
	INSERT INTO WMRS_MARKER_RESULT (MRS_N_CODIGO,MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_MKR_N_CODIGO,MRS_ETI_N_CODIGO)
	SELECT MRS_N_CODIGO,MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE,MRS_MKR_N_CODIGO,MRS_ETI_N_CODIGO FROM #WMRS_MARKER_RESULT
	SET IDENTITY_INSERT WMRS_MARKER_RESULT OFF
	
	SET IDENTITY_INSERT WIMG_ITEM_MESSAGE ON
	INSERT INTO WIMG_ITEM_MESSAGE (IMG_IPR_N_CODIGO,IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_D_DATECREATED,IMG_IMG_N_ID,IMG_PRO_N_CODIGO,IMG_N_ID)
	SELECT IMG_IPR_N_CODIGO,IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_D_DATECREATED,IMG_IMG_N_ID,IMG_PRO_N_CODIGO,IMG_N_ID FROM #WIMG_ITEM_MESSAGE 
	SET IDENTITY_INSERT WIMG_ITEM_MESSAGE OFF

	SET IDENTITY_INSERT WIMR_ITEM_MESSAGE_READERS ON
	INSERT INTO WIMR_ITEM_MESSAGE_READERS (IMR_N_ID,IMR_USR_N_ID,IMR_IMG_N_ID,IMR_B_ISRECIPIENT,IMR_B_READ,IMR_B_LIKED,IMR_B_FLAGGED) 
	SELECT IMR_N_ID,IMR_USR_N_ID,IMR_IMG_N_ID,IMR_B_ISRECIPIENT,IMR_B_READ,IMR_B_LIKED,IMR_B_FLAGGED FROM #WIMR_ITEM_MESSAGE_READERS
	SET IDENTITY_INSERT WIMR_ITEM_MESSAGE_READERS OFF

	DROP TABLE #WIMR_ITEM_MESSAGE_READERS
	DROP TABLE #WIMG_ITEM_MESSAGE 
	DROP TABLE #WMRS_MARKER_RESULT
	DROP TABLE #WIEX_ITEM_EXECUCAO
	DROP TABLE #WITR_ITEM_READERS
	DROP TABLE #WIPR_ITEM_PROCESSO
	SET NOCOUNT OFF
END CATCH

GO

--#####################################################################################################################
IF OBJECT_ID('wpr_CloseItemWorkflow') IS NULL
	EXEC('CREATE PROCEDURE wpr_CloseItemWorkflow AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE [dbo].[wpr_CloseItemWorkflow] (
	@ITEMWORKFLOWID int
)
AS
BEGIN TRY
	SET NOCOUNT ON
	/* CRIAÇÃO DAS TABELAS TEMPORARIAS */
	CREATE TABLE #WISP_ITEM_SUBPROCESS(
		[ISP_N_ID] [int] NOT NULL,
		[ISP_N_IPR_N_CODIGO] [int] NOT NULL,
		[ISP_N_PARENTISP_ID] [int] NOT NULL,
		[ISP_ATV_N_CODIGO] [int] NOT NULL,
		[ISP_C_IDENTIFIER] [varchar](300) NULL,
		[ISP_C_TITLE] [varchar](200) NULL,
		[ISP_C_METADATA] [varchar](max) NULL,
		[ISP_N_LOOPITEM] [int] NULL,
		[ISP_NOD_C_SCOPE] [varchar](36) NULL)
	CREATE TABLE #WANX_ANEXO_ITEM(
		[ANX_N_CODIGO] [int] NOT NULL,
		[ANX_N_IWF_N_CODIGO] [int] NOT NULL,
		[ANX_N_PRO_N_CODIGO] [int] NOT NULL,
		[ANX_N_ATV_N_CODIGO] [int] NOT NULL,
		[ANX_N_TIPO] [int] NOT NULL,
		[ANX_C_ATVALIASANEXO] [varchar](200) NULL,
		[ANX_C_MODULO] [varchar](36) NULL,
		[ANX_C_NOME] [nvarchar](250) NULL,
		[ANX_C_DESCRICAO] [text] NOT NULL,
		[ANX_C_NOMEARQ] [nvarchar](250) NULL,
		[ANX_C_CONTENT] [text] NOT NULL,
		[ANX_USU_N_CODIGO] [int] NOT NULL,
		[ANX_C_LISTAACESSO] [varchar](100) NOT NULL,
		[ANX_D_INCLUSAO] [datetime] NOT NULL,
		[ANX_N_ATIVO] [bit] NOT NULL,
		[ANX_B_OCULTO] [bit] NOT NULL,
		[ANX_ISP_N_ID] [int] NULL)
	CREATE TABLE #WHIS_HISTORICO_ITEM(
		[HIS_N_CODIGO] [int] NOT NULL,
		[HIS_N_PRO_N_CODIGO] [int] NOT NULL,
		[HIS_N_IWF_N_CODIGO] [int] NOT NULL,
		[HIS_N_USR_EXECUTOR] [int] NOT NULL,
		[HIS_N_ETA_N_CODIGO] [int] NOT NULL,
		[HIS_N_ETI_N_CODIGO] [int] NOT NULL,
		[HIS_C_STATUS] [varchar](30) NOT NULL,
		[HIS_D_GRAVACAO] [datetime] NOT NULL,
		[HIS_C_DESCRICAO] [varchar](250) NOT NULL,
		[HIS_N_ACAOID] [int] NOT NULL,
		[HIS_N_TIPOACAO] [int] NOT NULL,
		[HIS_N_EVE_N_ID] [int] NOT NULL,
		[HIS_N_ATIVO] [bit] NOT NULL,
		[HIS_ISP_N_ID] [int] NULL,
		[HIS_N_LOGLEVEL] [int] NOT NULL)
	CREATE TABLE #WIWF_ITEM_WORKFLOW(
		[IWF_N_CODIGO] [int] NOT NULL,
		[IWF_C_NOME] [varchar](80) NOT NULL,
		[IWF_C_STATUS] [varchar](50) NOT NULL,
		[IWF_D_DATAINICIO] [datetime] NOT NULL,
		[IWF_N_READONLY] [bit] NOT NULL,
		[IWF_N_USU_OWNER] [int] NOT NULL,
		[IWF_N_ARE_ORIGEM] [int] NOT NULL,
		[IWF_N_ITE_ORIGEM] [int] NOT NULL,
		[IWF_N_PRO_ORIGEM] [int] NOT NULL,
		[IWF_D_DATAFIM] [datetime] NULL,
		[IWF_C_PARAM1] [varchar](max) NULL,
		[IWF_C_PARAM2] [varchar](max) NULL,
		[IWF_C_PARAM3] [varchar](max) NULL,
		[IWF_C_PARAM4] [varchar](max) NULL,
		[IWF_C_PARAM5] [varchar](max) NULL,
		[IWF_C_METADATA] [varchar](max) NULL)

	/* ATUALIZACAO DAS INFORMACOES DE ITEM WORKFLOW*/
	IF NOT EXISTS(SELECT 1 FROM WIWF_ITEM_WORKFLOW_FINALIZADO WHERE IWF_N_CODIGO = @ITEMWORKFLOWID)
		INSERT INTO WIWF_ITEM_WORKFLOW_FINALIZADO (IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,
					IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA)
		SELECT IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,
					IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA 
		FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID
	ELSE
		UPDATE F SET
			F.IWF_C_NOME = A.IWF_C_NOME,
			F.IWF_C_STATUS = A.IWF_C_STATUS,
			F.IWF_D_DATAINICIO = A.IWF_D_DATAINICIO,
			F.IWF_N_READONLY = A.IWF_N_READONLY,
			F.IWF_N_USU_OWNER = A.IWF_N_USU_OWNER,
			F.IWF_N_ARE_ORIGEM = A.IWF_N_ARE_ORIGEM,
			F.IWF_N_ITE_ORIGEM = A.IWF_N_ITE_ORIGEM,
			F.IWF_N_PRO_ORIGEM = A.IWF_N_PRO_ORIGEM,
			F.IWF_D_DATAFIM = A.IWF_D_DATAFIM,
			F.IWF_C_PARAM1 = A.IWF_C_PARAM1,
			F.IWF_C_PARAM2 = A.IWF_C_PARAM2,
			F.IWF_C_PARAM3 = A.IWF_C_PARAM3,
			F.IWF_C_PARAM4 = A.IWF_C_PARAM4,
			F.IWF_C_PARAM5 = A.IWF_C_PARAM5,
			F.IWF_C_METADATA = A.IWF_C_METADATA
		FROM
			WIWF_ITEM_WORKFLOW_FINALIZADO AS F INNER JOIN WIWF_ITEM_WORKFLOW AS A On A.IWF_N_CODIGO = F.IWF_N_CODIGO
		WHERE F.IWF_N_CODIGO = @ITEMWORKFLOWID

	
	INSERT INTO WANF_ANEXO_FINALIZADO (ANF_N_ID, ANF_N_IWF_N_CODIGO, ANF_N_PRO_N_CODIGO, ANF_N_ATV_N_CODIGO, ANF_N_TIPO,
				ANF_C_ATVALIASANEXO, ANF_C_MODULO, ANF_C_NOME, ANF_C_DESCRICAO, ANF_C_NOMEARQ, ANF_C_CONTENT,
				ANF_USU_N_CODIGO, ANF_C_LISTAACESSO, ANF_D_INCLUSAO, ANF_N_ATIVO, ANF_ISP_N_ID, ANF_B_OCULTO)
	SELECT      ANX_N_CODIGO, ANX_N_IWF_N_CODIGO, ANX_N_PRO_N_CODIGO, ANX_N_ATV_N_CODIGO, ANX_N_TIPO, ANX_C_ATVALIASANEXO,
				ANX_C_MODULO, ANX_C_NOME, ANX_C_DESCRICAO, ANX_C_NOMEARQ, ANX_C_CONTENT, ANX_USU_N_CODIGO, ANX_C_LISTAACESSO,
				ANX_D_INCLUSAO, ANX_N_ATIVO, ANX_ISP_N_ID, ANX_B_OCULTO
	FROM WANX_ANEXO_ITEM WHERE ANX_N_IWF_N_CODIGO = @ITEMWORKFLOWID

	INSERT INTO WHIF_HISTORICO_FINALIZADO (HIF_N_PRO_N_CODIGO, HIF_N_IWF_N_CODIGO, HIF_N_USR_EXECUTOR,
				HIF_N_ETA_N_CODIGO, HIF_N_ETI_N_CODIGO, HIF_C_STATUS, HIF_D_GRAVACAO, HIF_C_DESCRICAO,
				HIF_N_ACAOID, HIF_N_TIPOACAO, HIF_N_EVE_N_ID, HIF_ISP_N_ID, HIF_N_LOGLEVEL, HIF_N_ATIVO)
	SELECT      HIS_N_PRO_N_CODIGO, HIS_N_IWF_N_CODIGO, HIS_N_USR_EXECUTOR, HIS_N_ETA_N_CODIGO, HIS_N_ETI_N_CODIGO,
				HIS_C_STATUS, HIS_D_GRAVACAO, HIS_C_DESCRICAO, HIS_N_ACAOID, HIS_N_TIPOACAO, HIS_N_EVE_N_ID,
				HIS_ISP_N_ID, HIS_N_LOGLEVEL, HIS_N_ATIVO 
	FROM WHIS_HISTORICO_ITEM WHERE HIS_N_IWF_N_CODIGO = @ITEMWORKFLOWID

	INSERT INTO WIVC_ITEMVALUECACHE_FINISHED (IVC_IWF_N_ID,IVC_ISP_N_ID,IVC_IOB_N_ID,IVC_C_ISP_IDS,IVC_C_FIELDNAME,IVC_C_FIELDVALUE)
	SELECT      IVC_IWF_N_ID,IVC_ISP_N_ID,IVC_IOB_N_ID,IVC_C_ISP_IDS,IVC_C_FIELDNAME,IVC_C_FIELDVALUE 
	FROM WIVC_ITEMVALUECACHE WHERE IVC_IWF_N_ID = @ITEMWORKFLOWID
	
	
	/* SALVA INFORMAÇÃO PARA ROLLBACK */
	INSERT INTO #WISP_ITEM_SUBPROCESS (ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,ISP_C_TITLE,ISP_C_METADATA,ISP_N_LOOPITEM,ISP_NOD_C_SCOPE)
	SELECT ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,ISP_C_TITLE,ISP_C_METADATA,ISP_N_LOOPITEM,ISP_NOD_C_SCOPE FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_IPR_N_CODIGO IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_IWF_N_CODIGO = @ITEMWORKFLOWID)
	INSERT INTO #WANX_ANEXO_ITEM (ANX_N_CODIGO,ANX_N_IWF_N_CODIGO,ANX_N_PRO_N_CODIGO,ANX_N_ATV_N_CODIGO,ANX_N_TIPO,ANX_C_ATVALIASANEXO,ANX_C_MODULO,ANX_C_NOME,ANX_C_DESCRICAO,ANX_C_NOMEARQ,ANX_C_CONTENT,ANX_USU_N_CODIGO,ANX_C_LISTAACESSO,ANX_D_INCLUSAO,ANX_N_ATIVO,ANX_B_OCULTO,ANX_ISP_N_ID)
	SELECT ANX_N_CODIGO,ANX_N_IWF_N_CODIGO,ANX_N_PRO_N_CODIGO,ANX_N_ATV_N_CODIGO,ANX_N_TIPO,ANX_C_ATVALIASANEXO,ANX_C_MODULO,ANX_C_NOME,ANX_C_DESCRICAO,ANX_C_NOMEARQ,ANX_C_CONTENT,ANX_USU_N_CODIGO,ANX_C_LISTAACESSO,ANX_D_INCLUSAO,ANX_N_ATIVO,ANX_B_OCULTO,ANX_ISP_N_ID FROM WANX_ANEXO_ITEM WHERE ANX_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
	INSERT INTO #WHIS_HISTORICO_ITEM (HIS_N_CODIGO,HIS_N_PRO_N_CODIGO,HIS_N_IWF_N_CODIGO,HIS_N_USR_EXECUTOR,HIS_N_ETA_N_CODIGO,HIS_N_ETI_N_CODIGO,HIS_C_STATUS,HIS_D_GRAVACAO,HIS_C_DESCRICAO,HIS_N_ACAOID,HIS_N_TIPOACAO,HIS_N_EVE_N_ID,HIS_N_ATIVO,HIS_ISP_N_ID,HIS_N_LOGLEVEL)
	SELECT HIS_N_CODIGO,HIS_N_PRO_N_CODIGO,HIS_N_IWF_N_CODIGO,HIS_N_USR_EXECUTOR,HIS_N_ETA_N_CODIGO,HIS_N_ETI_N_CODIGO,HIS_C_STATUS,HIS_D_GRAVACAO,HIS_C_DESCRICAO,HIS_N_ACAOID,HIS_N_TIPOACAO,HIS_N_EVE_N_ID,HIS_N_ATIVO,HIS_ISP_N_ID,HIS_N_LOGLEVEL FROM WHIS_HISTORICO_ITEM WHERE HIS_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
	INSERT INTO #WIWF_ITEM_WORKFLOW (IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA)
	SELECT IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID
	
	/* FAZ UMA VERIFICACAO FINAL E EXCLUI O ITEM WORKFLOW */
	IF NOT EXISTS(SELECT * FROM WIPR_ITEM_PROCESSO WHERE IPR_N_IWF_N_CODIGO = @ITEMWORKFLOWID)
	IF EXISTS(SELECT IWF_N_CODIGO FROM WIWF_ITEM_WORKFLOW_FINALIZADO WHERE IWF_N_CODIGO = @ITEMWORKFLOWID)
	BEGIN
		DELETE FROM WANX_ANEXO_ITEM WHERE ANX_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
		DELETE FROM WHIS_HISTORICO_ITEM WHERE HIS_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
		DELETE FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID
		--PARA NAO TER PROBLEMAS DE RELACIONAMENTO QUEBRADO SÓ EXCLUI OS DADOS DE SUBPROCESSO DEPOIS QUE MOVE OS HISTORICOS
		DELETE FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_IPR_N_CODIGO IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_IWF_N_CODIGO = @ITEMWORKFLOWID)
	END

	DROP TABLE #WIWF_ITEM_WORKFLOW
	DROP TABLE #WISP_ITEM_SUBPROCESS
	DROP TABLE #WHIS_HISTORICO_ITEM
	DROP TABLE #WANX_ANEXO_ITEM
	SET NOCOUNT OFF
END TRY
BEGIN CATCH
	DECLARE @NEWMSG VARCHAR(MAX)
	SELECT @NEWMSG = 'Error Executing Procedure: ' + 
					 ERROR_PROCEDURE() + ' / Line: ' + 
					 CONVERT(VARCHAR,ERROR_LINE()) + ' / ' + 
					 ERROR_MESSAGE() 
	INSERT INTO WFLOG_LOGMESSAGE
	(LOG_C_CATEGORY, LOG_D_TIMESTAMP, LOG_C_MESSAGE, LOG_N_TYPE, LOG_N_EVENTCODE,
	LOG_N_EVENTDETAIL, LOG_C_USER, LOG_C_URL, LOG_C_USERADDRESS, LOG_C_AUTHTYPE) VALUES 
	('CloseItemWorkflow', GETDATE(), @NEWMSG, 3, 9999, 1, 1, 'sqlexec', 'sqlserver', 'Forms')

	SET IDENTITY_INSERT WIWF_ITEM_WORKFLOW ON
	INSERT INTO WIWF_ITEM_WORKFLOW (IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA)
	SELECT IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA FROM #WIWF_ITEM_WORKFLOW 
	SET IDENTITY_INSERT WIWF_ITEM_WORKFLOW ON
	
	SET IDENTITY_INSERT WISP_ITEM_SUBPROCESS ON
	INSERT INTO WISP_ITEM_SUBPROCESS (ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,ISP_C_TITLE,ISP_C_METADATA,ISP_N_LOOPITEM,ISP_NOD_C_SCOPE)
	SELECT ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,ISP_C_TITLE,ISP_C_METADATA,ISP_N_LOOPITEM,ISP_NOD_C_SCOPE FROM #WISP_ITEM_SUBPROCESS
	SET IDENTITY_INSERT WISP_ITEM_SUBPROCESS OFF

	SET IDENTITY_INSERT WHIS_HISTORICO_ITEM ON
	INSERT INTO WHIS_HISTORICO_ITEM (HIS_N_CODIGO,HIS_N_PRO_N_CODIGO,HIS_N_IWF_N_CODIGO,HIS_N_USR_EXECUTOR,HIS_N_ETA_N_CODIGO,HIS_N_ETI_N_CODIGO,HIS_C_STATUS,HIS_D_GRAVACAO,HIS_C_DESCRICAO,HIS_N_ACAOID,HIS_N_TIPOACAO,HIS_N_EVE_N_ID,HIS_N_ATIVO,HIS_ISP_N_ID,HIS_N_LOGLEVEL)
	SELECT HIS_N_CODIGO,HIS_N_PRO_N_CODIGO,HIS_N_IWF_N_CODIGO,HIS_N_USR_EXECUTOR,HIS_N_ETA_N_CODIGO,HIS_N_ETI_N_CODIGO,HIS_C_STATUS,HIS_D_GRAVACAO,HIS_C_DESCRICAO,HIS_N_ACAOID,HIS_N_TIPOACAO,HIS_N_EVE_N_ID,HIS_N_ATIVO,HIS_ISP_N_ID,HIS_N_LOGLEVEL FROM #WHIS_HISTORICO_ITEM
	SET IDENTITY_INSERT WHIS_HISTORICO_ITEM ON

	SET IDENTITY_INSERT WANX_ANEXO_ITEM ON
	INSERT INTO WANX_ANEXO_ITEM (ANX_N_CODIGO,ANX_N_IWF_N_CODIGO,ANX_N_PRO_N_CODIGO,ANX_N_ATV_N_CODIGO,ANX_N_TIPO,ANX_C_ATVALIASANEXO,ANX_C_MODULO,ANX_C_NOME,ANX_C_DESCRICAO,ANX_C_NOMEARQ,ANX_C_CONTENT,ANX_USU_N_CODIGO,ANX_C_LISTAACESSO,ANX_D_INCLUSAO,ANX_N_ATIVO,ANX_B_OCULTO,ANX_ISP_N_ID)
	SELECT ANX_N_CODIGO,ANX_N_IWF_N_CODIGO,ANX_N_PRO_N_CODIGO,ANX_N_ATV_N_CODIGO,ANX_N_TIPO,ANX_C_ATVALIASANEXO,ANX_C_MODULO,ANX_C_NOME,ANX_C_DESCRICAO,ANX_C_NOMEARQ,ANX_C_CONTENT,ANX_USU_N_CODIGO,ANX_C_LISTAACESSO,ANX_D_INCLUSAO,ANX_N_ATIVO,ANX_B_OCULTO,ANX_ISP_N_ID FROM #WANX_ANEXO_ITEM
	SET IDENTITY_INSERT WANX_ANEXO_ITEM OFF
	
	DROP TABLE #WIWF_ITEM_WORKFLOW
	DROP TABLE #WISP_ITEM_SUBPROCESS
	DROP TABLE #WHIS_HISTORICO_ITEM
	DROP TABLE #WANX_ANEXO_ITEM
	SET NOCOUNT OFF
END CATCH

GO
--#####################################################################################################################
IF OBJECT_ID('wpr_GetDistinctExecutors') IS NULL
	EXEC('CREATE PROCEDURE wpr_GetDistinctExecutors AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE wpr_GetDistinctExecutors 
	@MARKERNAME VARCHAR(300)
AS
BEGIN
	SET NOCOUNT ON
	SELECT DISTINCT EXECUTORID FROM ZURIMARKERSLIST WHERE MARKERNAME = @MARKERNAME
	SET NOCOUNT OFF
END
GO
--#####################################################################################################################

IF NOT OBJECT_ID('wpr_RestartItemProcess') IS NULL 
BEGIN
	DROP PROCEDURE wpr_RestartItemProcess
END
GO

CREATE PROCEDURE [wpr_RestartItemProcess] (
	@ITEMPROCESSID int
)
AS
BEGIN TRANSACTION;
BEGIN TRY
	/* RECUPERA O ID DO ITEM WORKFLOW RELACIONADO */
	DECLARE @ITEMWORKFLOWID INT
	DECLARE @PROCESSOID INT
	SELECT @ITEMWORKFLOWID = IPR_N_IWF_N_CODIGO, @PROCESSOID = IPR_N_PRO_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_CODIGO = @ITEMPROCESSID
	
	/* INSERE O ITEM PROCESSO FINALIZADO */
	SET IDENTITY_INSERT WIPR_ITEM_PROCESSO ON
	INSERT INTO WIPR_ITEM_PROCESSO (IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,
				IPR_N_FINALIZADO,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA)
	SELECT IPR_N_CODIGO,IPR_N_IWF_N_CODIGO,IPR_N_PRO_N_CODIGO,IPR_N_COUNTERID,IPR_N_PRIORIDADE,IPR_D_DATAINICIO,IPR_C_STATUSCOLOR,
		   0,IPR_C_LISTAACESSO,IPR_N_LOCALIDADE,IPR_C_METADATA,IPR_D_SLAFINAL,IPR_N_CURRENTSLA FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_CODIGO = @ITEMPROCESSID
	SET IDENTITY_INSERT WIPR_ITEM_PROCESSO OFF

	/* MOVE AS MENSAGENS ASSOCIADAS AO ITEM PROCESSO */	
	SET IDENTITY_INSERT WIMG_ITEM_MESSAGE ON
	INSERT INTO WIMG_ITEM_MESSAGE (IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_N_ID,IMG_IMG_N_ID,IMG_IPR_N_CODIGO,IMG_D_DATECREATED, IMG_PRO_N_CODIGO) 
	SELECT IMG_C_SUBJECT,IMG_C_MESSAGE,IMG_N_SENDER,IMG_C_SENDERSTEP,IMG_C_RECIPIENT,IMG_C_CARBONCOPY,IMG_N_ID,IMG_IMG_N_ID,IMG_IPR_N_CODIGO,IMG_D_DATECREATED, IMG_PRO_N_CODIGO FROM WIMG_ITEM_MESSAGE_FINALIZADO WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
	SET IDENTITY_INSERT WIMG_ITEM_MESSAGE OFF

	SET IDENTITY_INSERT WIMR_ITEM_MESSAGE_READERS ON
	INSERT INTO WIMR_ITEM_MESSAGE_READERS (IMR_N_ID,IMR_IMG_N_ID,IMR_USR_N_ID,IMR_B_READ,IMR_B_ISRECIPIENT, IMR_B_LIKED, IMR_B_FLAGGED)
	SELECT IMR_N_ID,IMR_IMG_N_ID,IMR_USR_N_ID,IMR_B_READ,IMR_B_ISRECIPIENT, IMR_B_LIKED, IMR_B_FLAGGED 
	FROM WIMR_ITEM_MSG_RDRS_FIM 
	INNER JOIN WIMG_ITEM_MESSAGE_FINALIZADO ON IMR_IMG_N_ID = IMG_N_ID
	WHERE IMG_IPR_N_CODIGO = @ITEMPROCESSID
	SET IDENTITY_INSERT WIMR_ITEM_MESSAGE_READERS OFF
	
	/* MOVE OS OBSERVADORES DO ITEM */
	INSERT  INTO WITR_ITEM_READERS (ITR_N_IPR_N_CODIGO, ITR_N_USR_N_ID)
	SELECT  IRF_N_IPR_N_CODIGO, IRF_N_USR_N_ID	FROM WIRF_ITEM_READERS_FINALIZADO WHERE IRF_N_IPR_N_CODIGO = @ITEMPROCESSID

	/* MOVE AS INFORMACOES DE SUBPROCESSOS */
	SET IDENTITY_INSERT WISP_ITEM_SUBPROCESS ON
	INSERT INTO WISP_ITEM_SUBPROCESS (ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER,
											ISP_C_TITLE,ISP_C_METADATA)
	SELECT ISP_N_ID,ISP_N_IPR_N_CODIGO,ISP_N_PARENTISP_ID,ISP_ATV_N_CODIGO,ISP_C_IDENTIFIER, 
						 ISP_C_TITLE,ISP_C_METADATA FROM WISP_ITEM_SUBPROCESS_FINALIZADO WHERE ISP_N_IPR_N_CODIGO = @ITEMPROCESSID
	SET IDENTITY_INSERT WISP_ITEM_SUBPROCESS OFF
	/* EXCLUI AS INFORMACOES DE SUBPROCESSOS */
	DELETE FROM WISP_ITEM_SUBPROCESS_FINALIZADO WHERE ISP_N_IPR_N_CODIGO = @ITEMPROCESSID

	/* EXCLUI AS INFORMAÇÔES DE ITENS FINALIZADOS */
	DELETE FROM WIRF_ITEM_READERS_FINALIZADO WHERE IRF_N_IPR_N_CODIGO = @ITEMPROCESSID

	/*RECUPERA AS INFORMACOES DE RELATORIOS DE MARCADORES PARA A TABELA DE FINALIZADOS */
	INSERT INTO WMRS_MARKER_RESULT(MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,
		   MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE)
		SELECT MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_PRO_N_CODIGO,
		   MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE FROM WMRS_MARKER_RESULT_FINISHED WHERE MRS_IPR_N_CODIGO = @ITEMPROCESSID
	/* EXCLUI OS DADOS DE RELATORIOS DE MARCADORES DA TABELA FINALIZADA */
	DELETE FROM WMRS_MARKER_RESULT_FINISHED WHERE MRS_IPR_N_CODIGO = @ITEMPROCESSID

	/* FAZ UMA VERIFICACAO FINAL E EXCLUI O ITEM PROCESSO */
	IF EXISTS(SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO WHERE IPR_N_CODIGO = @ITEMPROCESSID)
	DELETE FROM WIPR_ITEM_PROCESSO_FINALIZADO WHERE IPR_N_CODIGO = @ITEMPROCESSID

	COMMIT TRANSACTION;
END TRY
BEGIN CATCH
	DECLARE @NEWMSG VARCHAR(MAX)
	SELECT @NEWMSG = 'Error Executing Procedure: ' + 
					 ERROR_PROCEDURE() + ' / Line: ' + 
					 CONVERT(VARCHAR,ERROR_LINE()) + ' / ' + 
					 ERROR_MESSAGE() 
	ROLLBACK TRANSACTION;
	INSERT INTO WFLOG_LOGMESSAGE
	(LOG_C_CATEGORY, LOG_D_TIMESTAMP, LOG_C_MESSAGE, LOG_N_TYPE, LOG_N_EVENTCODE,
	LOG_N_EVENTDETAIL, LOG_C_USER, LOG_C_URL, LOG_C_USERADDRESS, LOG_C_AUTHTYPE) VALUES 
	('CloseItemProcess', GETDATE(), @NEWMSG, 3, 9999, 1, 1, 'sqlexec', 'sqlserver', 'Forms')
END CATCH
GO
--#####################################################################################################################
IF NOT OBJECT_ID('wpr_RestartItemWorkflow') IS NULL 
BEGIN
	DROP PROCEDURE wpr_RestartItemWorkflow
END
GO

CREATE PROCEDURE [dbo].[wpr_RestartItemWorkflow] (
	@ITEMWORKFLOWID int
)
AS
BEGIN TRANSACTION;
BEGIN TRY
	IF NOT EXISTS(SELECT 1 FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID)
	BEGIN
		SET IDENTITY_INSERT WIWF_ITEM_WORKFLOW ON
		INSERT INTO WIWF_ITEM_WORKFLOW (IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,
					IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,IWF_D_DATAFIM,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA)
		SELECT IWF_N_CODIGO,IWF_C_NOME,IWF_C_STATUS,IWF_D_DATAINICIO,IWF_N_READONLY,IWF_N_USU_OWNER,IWF_N_ARE_ORIGEM,IWF_N_ITE_ORIGEM,IWF_N_PRO_ORIGEM,
					NULL,IWF_C_PARAM1,IWF_C_PARAM2,IWF_C_PARAM3,IWF_C_PARAM4,IWF_C_PARAM5,IWF_C_METADATA 
		FROM WIWF_ITEM_WORKFLOW_FINALIZADO WHERE IWF_N_CODIGO = @ITEMWORKFLOWID
		SET IDENTITY_INSERT WIWF_ITEM_WORKFLOW OFF
	END
	ELSE
		UPDATE F SET
			F.IWF_C_NOME = A.IWF_C_NOME,
			F.IWF_C_STATUS = A.IWF_C_STATUS,
			F.IWF_D_DATAINICIO = A.IWF_D_DATAINICIO,
			F.IWF_N_READONLY = A.IWF_N_READONLY,
			F.IWF_N_USU_OWNER = A.IWF_N_USU_OWNER,
			F.IWF_N_ARE_ORIGEM = A.IWF_N_ARE_ORIGEM,
			F.IWF_N_ITE_ORIGEM = A.IWF_N_ITE_ORIGEM,
			F.IWF_N_PRO_ORIGEM = A.IWF_N_PRO_ORIGEM,
			F.IWF_D_DATAFIM = NULL,
			F.IWF_C_PARAM1 = A.IWF_C_PARAM1,
			F.IWF_C_PARAM2 = A.IWF_C_PARAM2,
			F.IWF_C_PARAM3 = A.IWF_C_PARAM3,
			F.IWF_C_PARAM4 = A.IWF_C_PARAM4,
			F.IWF_C_PARAM5 = A.IWF_C_PARAM5,
			F.IWF_C_METADATA = A.IWF_C_METADATA
		FROM
			WIWF_ITEM_WORKFLOW AS F INNER JOIN WIWF_ITEM_WORKFLOW_FINALIZADO AS A On A.IWF_N_CODIGO = F.IWF_N_CODIGO
		WHERE F.IWF_N_CODIGO = @ITEMWORKFLOWID

	
	INSERT INTO WANX_ANEXO_ITEM (ANX_N_IWF_N_CODIGO, ANX_N_PRO_N_CODIGO, ANX_N_ATV_N_CODIGO, ANX_N_TIPO,
				ANX_C_ATVALIASANEXO, ANX_C_MODULO, ANX_C_NOME, ANX_C_DESCRICAO, ANX_C_NOMEARQ, ANX_C_CONTENT,
				ANX_USU_N_CODIGO, ANX_C_LISTAACESSO, ANX_D_INCLUSAO, ANX_N_ATIVO, ANX_ISP_N_ID, ANX_B_OCULTO)
	SELECT      ANF_N_IWF_N_CODIGO, ANF_N_PRO_N_CODIGO, ANF_N_ATV_N_CODIGO, ANF_N_TIPO, ANF_C_ATVALIASANEXO,
				ANF_C_MODULO, ANF_C_NOME, ANF_C_DESCRICAO, ANF_C_NOMEARQ, ANF_C_CONTENT, ANF_USU_N_CODIGO, ANF_C_LISTAACESSO,
				ANF_D_INCLUSAO, ANF_N_ATIVO, ANF_ISP_N_ID, ANF_B_OCULTO
	FROM WANF_ANEXO_FINALIZADO WHERE ANF_N_IWF_N_CODIGO = @ITEMWORKFLOWID

	INSERT INTO WHIS_HISTORICO_ITEM (HIS_N_PRO_N_CODIGO, HIS_N_IWF_N_CODIGO, HIS_N_USR_EXECUTOR,
				HIS_N_ETA_N_CODIGO, HIS_N_ETI_N_CODIGO, HIS_C_STATUS, HIS_D_GRAVACAO, HIS_C_DESCRICAO,
				HIS_N_ACAOID, HIS_N_TIPOACAO, HIS_N_EVE_N_ID, HIS_ISP_N_ID, HIS_N_LOGLEVEL, HIS_N_ATIVO)
	SELECT      HIF_N_PRO_N_CODIGO, HIF_N_IWF_N_CODIGO, HIF_N_USR_EXECUTOR, HIF_N_ETA_N_CODIGO, HIF_N_ETI_N_CODIGO,
				HIF_C_STATUS, HIF_D_GRAVACAO, HIF_C_DESCRICAO, HIF_N_ACAOID, HIF_N_TIPOACAO, HIF_N_EVE_N_ID,
				HIF_ISP_N_ID, HIF_N_LOGLEVEL, HIF_N_ATIVO
	FROM WHIF_HISTORICO_FINALIZADO WHERE HIF_N_IWF_N_CODIGO = @ITEMWORKFLOWID

	/* FAZ UMA VERIFICACAO FINAL E EXCLUI OS ANEXOS E HISTORICO. O ITEM WORKFLOW NAO PODE SER EXCLUIDO*/
	IF EXISTS(SELECT IWF_N_CODIGO FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO = @ITEMWORKFLOWID)
	BEGIN
		DELETE FROM WANF_ANEXO_FINALIZADO WHERE ANF_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
		DELETE FROM WHIF_HISTORICO_FINALIZADO WHERE HIF_N_IWF_N_CODIGO = @ITEMWORKFLOWID  
	END

	COMMIT TRANSACTION;
END TRY
BEGIN CATCH
	DECLARE @NEWMSG VARCHAR(MAX)
	SELECT @NEWMSG = 'Error Executing Procedure: ' + 
					 ERROR_PROCEDURE() + ' / Line: ' + 
					 CONVERT(VARCHAR,ERROR_LINE()) + ' / ' + 
					 ERROR_MESSAGE() 
	ROLLBACK TRANSACTION;
	INSERT INTO WFLOG_LOGMESSAGE
	(LOG_C_CATEGORY, LOG_D_TIMESTAMP, LOG_C_MESSAGE, LOG_N_TYPE, LOG_N_EVENTCODE,
	LOG_N_EVENTDETAIL, LOG_C_USER, LOG_C_URL, LOG_C_USERADDRESS, LOG_C_AUTHTYPE) VALUES 
	('CloseItemWorkflow', GETDATE(), @NEWMSG, 3, 9999, 1, 1, 'sqlexec', 'sqlserver', 'Forms')
END CATCH
GO

--#####################################################################################################################
IF OBJECT_ID('wpr_GetDistinctMarkerValues') IS NULL
	EXEC('CREATE PROCEDURE wpr_GetDistinctMarkerValues AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE [dbo].[wpr_GetDistinctMarkerValues]
	@PROCESSIDS varchar(100),
	@MARKERNAME varchar(100),
	@FIELDNAME varchar(50),
	@SCOPE varchar(10)
AS
BEGIN
	SET NOCOUNT ON
	DECLARE @EXECCOMMAND varchar(max)
	SET @EXECCOMMAND = 'SELECT DISTINCT TOP 200  ' + @FIELDNAME 
	IF @SCOPE = 'ACTIVE'
		SET @EXECCOMMAND = @EXECCOMMAND + ' FROM ZuriMarkersListActive '
	IF @SCOPE = 'CLOSED'
		SET @EXECCOMMAND = @EXECCOMMAND + ' FROM ZuriMarkersListClosed '
	IF @SCOPE = 'ALL'
		SET @EXECCOMMAND = @EXECCOMMAND + ' FROM ZuriMarkersList '
	SET @EXECCOMMAND = @EXECCOMMAND + ' WHERE MARKERNAME = ''' + @MARKERNAME + ''' AND '
	SET @EXECCOMMAND = @EXECCOMMAND + ' PROCESSID IN (' + @PROCESSIDS + ') AND '
	SET @EXECCOMMAND = @EXECCOMMAND + ' NOT ' + @FIELDNAME + ' IS NULL ORDER BY 1'
	exec(@execcommand)
	SET NOCOUNT OFF
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('wpr_MoveReaders') IS NULL 
BEGIN
	DROP PROCEDURE wpr_MoveReaders
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('wpr_DeleteMarkers') IS NULL 
BEGIN
	DROP PROCEDURE wpr_DeleteMarkers
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('wpr_MoveAnexos') IS NULL 
BEGIN
	DROP PROCEDURE wpr_MoveAnexos
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('wpr_MoveHistorico') IS NULL 
BEGIN
	DROP PROCEDURE wpr_MoveHistorico
END
GO

--#####################################################################################################################

IF NOT OBJECT_ID('wpr_GetUserItems') IS NULL 
BEGIN
	DROP PROCEDURE wpr_GetUserItems
END
GO
CREATE PROCEDURE wpr_GetUserItems (
	@USERID int
)
AS
	SELECT DISTINCT
		HIF_N_IWF_N_CODIGO AS ITEMWORKFLOWID 
	FROM 
		WHIF_HISTORICO_FINALIZADO 
	WHERE HIF_N_USR_EXECUTOR = @USERID
	UNION
	SELECT DISTINCT
		HIS_N_IWF_N_CODIGO AS ITEMWORKFLOWID 
	FROM 
		WHIS_HISTORICO_ITEM 
	WHERE HIS_N_USR_EXECUTOR = @USERID
GO

--#################################################################################################################################

IF NOT OBJECT_ID('wpr_ListWorkflowUser') IS NULL 
BEGIN
	DROP PROCEDURE wpr_ListWorkflowUser
END
GO

IF NOT OBJECT_ID('wpr_ListWorkflowSteps') IS NULL 
BEGIN
	DROP PROCEDURE wpr_ListWorkflowSteps
END
GO

IF NOT OBJECT_ID('wpr_ListWorkflowItens') IS NULL 
BEGIN
	DROP PROCEDURE wpr_ListWorkflowItens
END
GO

IF NOT OBJECT_ID('wpr_CountObservadores') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountObservadores
END
GO

IF NOT OBJECT_ID('wpr_CountMeusProcessos') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountMeusProcessos
END
GO

IF NOT OBJECT_ID('wpr_CountCaixaEntrada') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountCaixaEntrada
END
GO

IF NOT OBJECT_ID('wpr_CountProcessosAtivos') IS NULL
BEGIN
	DROP PROCEDURE wpr_CountProcessosAtivos 
END
GO

IF NOT OBJECT_ID('wpr_CountProcessosProdutividade') IS NULL
BEGIN
	DROP PROCEDURE wpr_CountProcessosProdutividade
END
GO

IF NOT OBJECT_ID('wpr_CountProcessosSlaEtapa') IS NULL
BEGIN
	DROP PROCEDURE wpr_CountProcessosSlaEtapa
END
GO

IF NOT OBJECT_ID('wpr_CountInbox') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountInbox
END
GO

CREATE PROCEDURE wpr_CountInbox (
	@USERID int
)
AS
	SELECT
		COUNT(ETE_N_ETI_N_CODIGO) AS ITEMCOUNT
	FROM         
		WETE_ETAPA_ITEM_EDITORS
	WHERE
		ETE_N_USR_N_ID = @USERID
	
GO

IF NOT OBJECT_ID('wpr_CountOutlook') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountOutlook
END
GO

CREATE PROCEDURE wpr_CountOutlook(
	@USERID int,
	@ADDFINISHED bit
)
AS
	if @ADDFINISHED = 0
	BEGIN
		SELECT COUNT(ITR_N_IPR_N_CODIGO) AS ITEMCOUNT
		FROM WITR_ITEM_READERS
		WHERE ITR_N_USR_N_ID = @USERID
	END
	ELSE
	BEGIN
		DECLARE @ATIVOS int = 0
		DECLARE @FINALIZADOS int = 0
		SELECT @ATIVOS= COUNT(ITR_N_IPR_N_CODIGO) 
		FROM WITR_ITEM_READERS
		WHERE ITR_N_USR_N_ID = @USERID
		SELECT @FINALIZADOS= COUNT(IRF_N_IPR_N_CODIGO) 
		FROM WIRF_ITEM_READERS_FINALIZADO
		WHERE IRF_N_USR_N_ID = @USERID

		SELECT @ATIVOS + @FINALIZADOS AS ITEMCOUNT
	END	
GO

IF NOT OBJECT_ID('wpr_CountMyItems') IS NULL 
BEGIN
	DROP PROCEDURE wpr_CountMyItems
END
GO

CREATE PROCEDURE wpr_CountMyItems(
	@USERID int,
	@ADDFINISHED bit
)
AS
	if @ADDFINISHED = 0
	BEGIN
		SELECT COUNT(DISTINCT HIS_N_IWF_N_CODIGO ) AS ITEMCOUNT
		FROM WHIS_HISTORICO_ITEM
		WHERE HIS_N_USR_EXECUTOR = @USERID
	END
	ELSE
	BEGIN
		DECLARE @ATIVOS int = 0
		DECLARE @FINALIZADOS int = 0
		SELECT @ATIVOS = COUNT(DISTINCT HIS_N_IWF_N_CODIGO)
		FROM WHIS_HISTORICO_ITEM
		WHERE HIS_N_USR_EXECUTOR = @USERID
		SELECT @FINALIZADOS = COUNT(DISTINCT HIF_N_IWF_N_CODIGO)
		FROM WHIF_HISTORICO_FINALIZADO
		WHERE HIF_N_USR_EXECUTOR = @USERID

		SELECT @ATIVOS + @FINALIZADOS AS ITEMCOUNT
	END	
GO


--#################################################################################################################################

IF NOT OBJECT_ID('wpr_CountPendingBySLA') IS NULL 
BEGIN
	DROP PROC wpr_CountPendingBySLA
END
GO

CREATE PROC wpr_CountPendingBySLA (
	@USER	 INT
)
AS
BEGIN
	DECLARE @RESULT TABLE(ID INT, [TYPE] varchar(5), SLA_ID INT, SLA_NAME VARCHAR(30), SLA_COLOR VARCHAR(10), TOTAL INT, [ORDER] INT)

	set nocount on
	--Totalização por SLA dos ítens vinculados ao usuário informado
	INSERT INTO @RESULT 
	SELECT ETS_N_CODIGO ID, 'mine' TYPE, ETS_N_CODIGO SLA_ID, ETS_C_NOME SLA_NAME, ETS_C_COR SLA_COLOR, COUNT(DISTINCT ETI_N_CODIGO) TOTAL, ETS_N_ORDEM 
	FROM WETI_ETAPA_ITEM 
	INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO
	INNER JOIN WETS_ETAPA_SLA ON IPR_N_CURRENTSLA = ETS_N_CODIGO
	WHERE ETI_N_USU_VINCULADO = @USER
	GROUP BY ETS_C_COR, ETS_N_CODIGO, ETS_C_NOME, ETS_N_ORDEM

	--Totalização por SLA dos ítens dos grupos do usuário informado mas que não estejam vinculados a ele
	INSERT INTO @RESULT 
	SELECT -ETS_N_CODIGO ID, 'group' TYPE, ETS_N_CODIGO SLA_ID, ETS_C_NOME SLA_NAME, ETS_C_COR SLA_COLOR, COUNT(DISTINCT ETI_N_CODIGO) TOTAL, ETS_N_ORDEM
	FROM WETI_ETAPA_ITEM 
	INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER
	INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO
	INNER JOIN WETS_ETAPA_SLA ON IPR_N_CURRENTSLA = ETS_N_CODIGO
	WHERE NOT ETI_N_USU_VINCULADO = @USER
	GROUP BY ETS_C_COR, ETS_N_CODIGO, ETS_C_NOME, ETS_N_ORDEM
	set nocount off

	SELECT ID, [TYPE], SLA_ID, SLA_NAME, SLA_COLOR, TOTAL 
	FROM @RESULT
	ORDER BY [TYPE], [ORDER]
END
GO

--#################################################################################################################################

IF NOT OBJECT_ID('wpr_CountPendingOverTime') IS NULL 
BEGIN
	DROP PROC wpr_CountPendingOverTime
END
GO

CREATE PROC wpr_CountPendingOverTime (
	@USER	 INT
)
AS
BEGIN  
 DECLARE @TODAY DATE  
 SET @TODAY = GETDATE()  
  
 DECLARE @DUE_TODAY INT, @PENDING_OVER_WEEK INT, @MINE INT, @OVERDUE INT  
 DECLARE @DUE_WEEK INT, @WEEK_IN DATE, @WEEK_OUT DATETIME  
 DECLARE @DUE_MONTH INT, @MONTH_IN DATE, @MONTH_OUT DATETIME  
  
 --CALCULA INICIO E FIM DA SEMANA  
 SET @WEEK_IN = DATEADD(D, 1-DATEPART(W, GETDATE()), GETDATE())--INICIO DA SEMANA (DOMINGO 00:00)  
 SET @WEEK_OUT = DATEADD(D, 7, @WEEK_IN) --DOMINGO SEGUINTE 00:00  
 SET @WEEK_OUT = DATEADD(S, -1, @WEEK_OUT) --SABADO SEGUINTE 23:59:59   
  
 --CALCULA INICIO E FIM DO MES  
 SET @MONTH_IN = DATEADD(D, 1-DATEPART(D, GETDATE()), GETDATE())--INICIO DO MÊS  
 SET @MONTH_OUT = DATEADD(M, 1, @MONTH_IN) --INICIO DO MÊS SEGUINTE  
 SET @MONTH_OUT = DATEADD(S, -1, @MONTH_OUT) --FINAL DO MÊS ATUAL ÀS 23:59:59   
  
 SET NOCOUNT ON  
  
 SELECT @OVERDUE = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 WHERE ETI_D_DEADLINE < GETDATE()
  
 SELECT @DUE_TODAY = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 WHERE CAST(ETI_D_DEADLINE AS DATE) = @TODAY  
  
 SELECT @DUE_WEEK = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 WHERE ETI_D_DEADLINE BETWEEN @TODAY AND @WEEK_OUT  
  
 SELECT @DUE_MONTH = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 WHERE ETI_D_DEADLINE BETWEEN @TODAY AND @MONTH_OUT  
  
 SELECT @MINE = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 INNER JOIN WIWF_ITEM_WORKFLOW ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO  
 WHERE IWF_N_USU_OWNER = @USER  
  
 SELECT @PENDING_OVER_WEEK = COUNT(DISTINCT ETI_N_CODIGO)  
 FROM WETI_ETAPA_ITEM  
 INNER JOIN WETE_ETAPA_ITEM_EDITORS ON ETE_N_ETI_N_CODIGO = ETI_N_CODIGO AND ETE_N_USR_N_ID = @USER  
 INNER JOIN WIPR_ITEM_PROCESSO ON ETI_N_IPR_N_CODIGO = IPR_N_CODIGO  
 WHERE DATEDIFF(D, ETI_D_INICIO, GETDATE()) > 7  
  
 SET NOCOUNT OFF  
  
 SELECT @USER ID, @OVERDUE OVERDUE, @DUE_TODAY DUE_TODAY, @DUE_WEEK DUE_WEEK, @DUE_MONTH DUE_MONTH, @MINE MINE, @PENDING_OVER_WEEK PENDING_OVER_WEEK  
END  

GO

--#################################################################################################################################

IF NOT OBJECT_ID('wpr_CountSocialMessages') IS NULL 
BEGIN
	DROP PROC wpr_CountSocialMessages
END
GO

CREATE PROC wpr_CountSocialMessages (
	@USER	 INT,
	@START   DATETIME,
	@UNREAD  BIT,
	@FLAGGED BIT,
	@PROCESS INT
)
AS
BEGIN
	DECLARE @LIKE VARCHAR(20)
	SET @LIKE = '%|' + CAST(@USER AS VARCHAR)  + '|%'

	SET @START = ISNULL(@START, GETDATE())
	SET @UNREAD = ISNULL(@UNREAD, 0)
	SET @FLAGGED = ISNULL(@FLAGGED,0)
	SET @PROCESS = ISNULL(@PROCESS, 0)

	DECLARE @NEW_MSG INT, @TOTAL INT, @UNREAD_COMMENTS INT, @FLAGGED_MESSAGES INT

	SET NOCOUNT ON

	--TOTAL DE MENSAGENS PARA O USUÁRIO
	SELECT @TOTAL = COUNT(*)
	FROM	WIMG_ITEM_MESSAGE M
	LEFT JOIN WIMR_ITEM_MESSAGE_READERS ON IMR_IMG_N_ID = IMG_N_ID AND IMR_USR_N_ID = @USER
	WHERE	IMG_IMG_N_ID = 0 
	AND (IMG_IPR_N_CODIGO IS NULL OR IMG_N_SENDER = @USER OR IMG_C_RECIPIENT LIKE @LIKE OR IMG_C_CARBONCOPY  LIKE @LIKE)
	AND (@FLAGGED = 0 OR IMR_B_FLAGGED = 1)
	AND (@PROCESS = 0 OR IMG_PRO_N_CODIGO = @PROCESS )
	AND (@UNREAD = 0 OR EXISTS(SELECT 1
								FROM WIMG_ITEM_MESSAGE C 
								LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR ON MR.IMR_IMG_N_ID = C.IMG_N_ID  AND MR.IMR_USR_N_ID = @USER
								WHERE C.IMG_IMG_N_ID = M.IMG_N_ID AND ISNULL(MR.IMR_B_READ, 0) = 0))

	--TOTAL DE MENSAGENS APÓS A DATA INFORMADA
	SELECT @NEW_MSG = COUNT(*)
	FROM	WIMG_ITEM_MESSAGE M
	WHERE	IMG_IMG_N_ID =0 
	AND IMG_D_DATECREATED > @START 
	AND (IMG_IPR_N_CODIGO IS NULL OR IMG_N_SENDER = @USER OR IMG_C_RECIPIENT LIKE @LIKE OR IMG_C_CARBONCOPY  LIKE @LIKE)
	AND (@PROCESS = 0 OR IMG_PRO_N_CODIGO = @PROCESS )

	--TOTAL DE COMENTÁRIOS NÃO LIDOS
	SELECT @UNREAD_COMMENTS = COUNT(*)
	FROM WIMG_ITEM_MESSAGE M1
	INNER JOIN WIMG_ITEM_MESSAGE M2 ON M2.IMG_IMG_N_ID = M1.IMG_N_ID
	LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR1 ON MR1.IMR_IMG_N_ID = M1.IMG_N_ID AND MR1.IMR_USR_N_ID = @USER
	LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR2 ON M2.IMG_N_ID = MR2.IMR_IMG_N_ID AND MR2.IMR_USR_N_ID = @USER
	WHERE (M1.IMG_IPR_N_CODIGO IS NULL OR M1.IMG_N_SENDER = @USER OR M1.IMG_C_RECIPIENT LIKE @LIKE OR M1.IMG_C_CARBONCOPY  LIKE @LIKE)
	AND ISNULL(MR2.IMR_B_READ, 0) = 0
	AND (@FLAGGED = 0 OR MR1.IMR_B_FLAGGED = 1)
	AND (@PROCESS = 0 OR M1.IMG_PRO_N_CODIGO = @PROCESS )

	--TOTAL DE MENSAGENS MARCADAS
	SELECT @FLAGGED_MESSAGES = COUNT(*)
	FROM WIMG_ITEM_MESSAGE M
	INNER JOIN WIMR_ITEM_MESSAGE_READERS ON IMG_N_ID = IMR_IMG_N_ID AND IMR_USR_N_ID = @USER AND IMR_B_FLAGGED = 1
	WHERE	IMG_IMG_N_ID = 0 		
	AND (IMG_IPR_N_CODIGO IS NULL OR IMG_N_SENDER = @USER OR IMG_C_RECIPIENT LIKE @LIKE OR IMG_C_CARBONCOPY  LIKE @LIKE)
	AND (@PROCESS = 0 OR IMG_PRO_N_CODIGO = @PROCESS )
	AND (@UNREAD = 0 OR EXISTS(SELECT 1
								FROM WIMG_ITEM_MESSAGE C 
								LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR ON MR.IMR_IMG_N_ID = C.IMG_N_ID  AND MR.IMR_USR_N_ID = @USER
								WHERE C.IMG_IMG_N_ID = M.IMG_N_ID AND ISNULL(MR.IMR_B_READ, 0) = 0))

	SET NOCOUNT OFF
	
	SELECT @USER USER_ID, @NEW_MSG NEW_MESSAGES, @TOTAL TOTAL_MESSAGES, @UNREAD_COMMENTS UNREAD_COMMENTS, @FLAGGED_MESSAGES FLAGGED_MESSAGES
END
GO


--#################################################################################################################################

IF NOT OBJECT_ID('wpr_ListSocialMessages') IS NULL 
BEGIN
	DROP PROC wpr_ListSocialMessages
END
GO

CREATE PROC wpr_ListSocialMessages (
	@USER	 INT,
	@START   DATETIME,
	@UNREAD  BIT,
	@UNREAD_COMMENTS BIT,
	@FLAGGED BIT,
	@PROCESS INT,
	@PAGE	 INT,
	@PARENT  INT
)
AS
BEGIN

	SET @PAGE = ISNULL(@PAGE, 1)

	SET @PARENT = ISNULL(@PARENT, 0)
	IF @PARENT < 0 SET @PARENT = 0
	
	DECLARE @OFFSET INT, @PAGE_SIZE INT
	SET @PAGE_SIZE = 5
	IF @PAGE > 0
	BEGIN
		SET @OFFSET = (@PAGE -1) * @PAGE_SIZE
	END
	ELSE
	BEGIN
		SET @OFFSET = 0
		SET @PAGE_SIZE = 1000
	END


	DECLARE @LIKE VARCHAR(20)
	SET @LIKE = '%|' + CAST(@USER AS VARCHAR)  + '|%'

	SELECT ID, CREATED, PROCESS, ITEM, TITLE, [SUBJECT], [MESSAGE], AUTHOR, LIKED, LIKE_COUNT, [READ], READ_COUNT, FLAGGED, FLAG_COUNT, COMMENT_COUNT, UNREAD_COMMENTS, RECIPIENT
	FROM (
		SELECT 
			IMG_N_ID			ID 
			,IMG_D_DATECREATED	CREATED
			,IMG_PRO_N_CODIGO	PROCESS
			,IMG_IPR_N_CODIGO	ITEM
			,CASE WHEN IW.IWF_C_NOME IS NULL 
				THEN P.PRO_C_NOME 
				ELSE '[#' + CAST(IW.IWF_N_CODIGO AS varchar) +  '] ' + IW.IWF_C_NOME END TITLE
			,IMG_C_SUBJECT		'SUBJECT'
			,IMG_C_MESSAGE		'MESSAGE'
			,IMG_N_SENDER		AUTHOR
			,ISNULL(IMR_B_LIKED , 0) LIKED
			,(SELECT COUNT(*) FROM WIMR_ITEM_MESSAGE_READERS WHERE IMR_IMG_N_ID = M.IMG_N_ID AND IMR_B_LIKED = 1) LIKE_COUNT
			,ISNULL(IMR_B_READ , 0) 'READ'
			,(SELECT COUNT(*) FROM WIMR_ITEM_MESSAGE_READERS WHERE IMR_IMG_N_ID = M.IMG_N_ID AND IMR_B_READ = 1) READ_COUNT
			,ISNULL(IMR_B_FLAGGED , 0) FLAGGED
			,(SELECT COUNT(*) FROM WIMR_ITEM_MESSAGE_READERS WHERE IMR_IMG_N_ID = M.IMG_N_ID AND IMR_B_FLAGGED = 1) FLAG_COUNT
			,(SELECT COUNT(*) FROM WIMG_ITEM_MESSAGE C WHERE C.IMG_IMG_N_ID = M.IMG_N_ID) COMMENT_COUNT
			,(SELECT COUNT(*) 
			  FROM WIMG_ITEM_MESSAGE C 
			  LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR ON MR.IMR_IMG_N_ID = C.IMG_N_ID AND MR.IMR_USR_N_ID = @USER
			  WHERE C.IMG_IMG_N_ID = M.IMG_N_ID AND ISNULL(MR.IMR_B_READ, 0) = 0) UNREAD_COMMENTS
			,(CASE WHEN M.IMG_C_RECIPIENT LIKE @LIKE THEN 1 ELSE 0 END) RECIPIENT
			,ROW_NUMBER() OVER (ORDER BY M.IMG_D_DATECREATED DESC) AS RowNumber
		FROM WIMG_ITEM_MESSAGE M
		LEFT JOIN WPRO_PROCESSO P ON M.IMG_PRO_N_CODIGO = P.PRO_N_CODIGO AND PRO_N_DELETED = 0 
		LEFT JOIN WIPR_ITEM_PROCESSO IP ON M.IMG_IPR_N_CODIGO = IP.IPR_N_CODIGO 
		LEFT JOIN WIWF_ITEM_WORKFLOW IW ON IP.IPR_N_IWF_N_CODIGO = IW.IWF_N_CODIGO 
		LEFT JOIN WIMR_ITEM_MESSAGE_READERS R ON R.IMR_IMG_N_ID = M.IMG_N_ID AND R.IMR_USR_N_ID = @user
		WHERE	M.IMG_D_DATECREATED <= @START AND M.IMG_IMG_N_ID = @PARENT
			AND (@PARENT > 0 OR M.IMG_IPR_N_CODIGO IS NULL OR M.IMG_N_SENDER = @USER OR M.IMG_C_RECIPIENT LIKE @LIKE OR M.IMG_C_CARBONCOPY  LIKE @LIKE)
			AND (ISNULL(@PROCESS, 0) < 1 OR M.IMG_PRO_N_CODIGO = @PROCESS)
			AND (ISNULL(@FLAGGED, 0) = 0 OR IMR_B_FLAGGED = @FLAGGED)
			AND (ISNULL(@UNREAD, 0) = 0 OR ISNULL(IMR_B_READ, 0) = 0)
			AND (ISNULL(@UNREAD_COMMENTS, 0) = 0 OR EXISTS (SELECT 1
												   FROM WIMG_ITEM_MESSAGE C 
												   LEFT JOIN WIMR_ITEM_MESSAGE_READERS MR ON MR.IMR_IMG_N_ID = C.IMG_N_ID  AND MR.IMR_USR_N_ID = @USER
												   WHERE C.IMG_IMG_N_ID = M.IMG_N_ID AND ISNULL(MR.IMR_B_READ, 0) = 0))) X
	WHERE RowNumber > @OFFSET AND RowNumber < @OFFSET + @PAGE_SIZE + 1
END
GO

--#################################################################################################################################

IF NOT OBJECT_ID('wpr_ListSocialProcsFilter') IS NULL 
BEGIN
	DROP PROC wpr_ListSocialProcsFilter
END
GO

CREATE PROC wpr_ListSocialProcsFilter (@USER INT)
AS
BEGIN
	SELECT DISTINCT PRO_N_CODIGO, PRO_C_NOME
	FROM	WPRO_PROCESSO
	INNER JOIN WIMG_ITEM_MESSAGE ON PRO_N_CODIGO = IMG_PRO_N_CODIGO 
	INNER JOIN WIMR_ITEM_MESSAGE_READERS ON IMR_IMG_N_ID = IMG_N_ID AND IMR_USR_N_ID = @USER
	WHERE	PRO_N_ATIVO = 1 AND PRO_N_DELETED = 0
	ORDER BY PRO_C_NOME
END
GO
/*************************************************************************************************************************
	ATUALIZACAO DOS DADOS DOS MARCADORES
*************************************************************************************************************************/
IF OBJECT_ID('wpr_UpdateMarkerValues') IS NULL
	EXEC('CREATE PROCEDURE wpr_UpdateMarkerValues AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE [dbo].[wpr_UpdateMarkerValues](
	@MARKERNAME VARCHAR(150)
)
AS
BEGIN
	SET NOCOUNT ON
	--DECLARE @MARKERNAME VARCHAR(100) = 'STATUS'

	DECLARE @MAXDATES TABLE (PROCESSID INT, MAXDATE DATETIME)
	
	DECLARE PROCESSIDS CURSOR FOR (SELECT DISTINCT MKR_PRO_N_CODIGO FROM WMKR_MARKER WHERE MKR_C_NAME = @MARKERNAME)
	DECLARE @PROCESSID INT

	OPEN PROCESSIDS
	FETCH NEXT FROM PROCESSIDS INTO @PROCESSID
	WHILE @@FETCH_STATUS = 0            
	BEGIN
		IF EXISTS(SELECT 1 FROM WMRS_MARKER_RESULT WHERE MRS_MKR_C_NAME = @MARKERNAME AND MRS_PRO_N_CODIGO = @PROCESSID)
			INSERT INTO @MAXDATES SELECT DISTINCT MRS_PRO_N_CODIGO, MAX(MRS_D_EXEC_DATE) FROM WMRS_MARKER_RESULT WHERE MRS_MKR_C_NAME = @MARKERNAME AND MRS_PRO_N_CODIGO = @PROCESSID GROUP BY MRS_PRO_N_CODIGO
		ELSE
			INSERT INTO @MAXDATES SELECT @PROCESSID, '20000101 00:00:00.000'
		FETCH NEXT FROM PROCESSIDS INTO @PROCESSID
	END
	CLOSE PROCESSIDS
	DEALLOCATE PROCESSIDS

	DECLARE PROC_MKR CURSOR FOR (SELECT * FROM @MAXDATES)
	DECLARE @MARKERIDS TABLE (MARKERID INT)
	
	DECLARE @EXECINFO TABLE (ITEMID INT, SUBPROCESSID INT, STEPITEM INT,  TIPOACAO INT, ACAOID INT, 
	                         EXECUTOR INT, GRAVACAO DATETIME, MARKERVALUE VARCHAR(1000), MARKERID INT)
	DECLARE @GROUPEDINFO TABLE (ITEMID INT, SUBPROCESSID INT, STEPITEM INT,  TIPOACAO INT, ACAOID INT, 
	                         EXECUTOR INT, GRAVACAO DATETIME, MARKERVALUE VARCHAR(1000), MARKERID INT, 
							 UNIQUEKEY VARCHAR(1500), EXECORDER INT)
	DECLARE @EXISTINGVALUES TABLE (UNIQUEKEY VARCHAR(1500))

	DECLARE @MAXDATE DATETIME
	DECLARE @EXECDATE DATETIME

	OPEN PROC_MKR
	FETCH NEXT FROM PROC_MKR INTO @PROCESSID, @MAXDATE
	WHILE @@FETCH_STATUS = 0            
	BEGIN
		--LIMPA AS TABELAS TEMPORARIAS
		DELETE FROM @MARKERIDS
		DELETE FROM @EXECINFO
		DELETE FROM @GROUPEDINFO
		DELETE FROM @EXISTINGVALUES
		--PRIMEIRO PEGA OS IDS DE MARCADORES NOVOS
		INSERT INTO @MARKERIDS
		SELECT MKR_N_CODIGO FROM WMKR_MARKER WHERE
				MKR_C_NAME =  @MARKERNAME AND
				MKR_D_CREATEDATE > @MAXDATE AND
				MKR_PRO_N_CODIGO = @PROCESSID AND
				MKR_N_CODIGO NOT IN (SELECT DISTINCT MRS_MKR_N_CODIGO FROM WMRS_MARKER_RESULT 
									 WHERE MRS_PRO_N_CODIGO = @PROCESSID)

		--LE AS INFORMACOES DE HISTORICO RELEVANTES BASEADO NA EXISTENCIA DE MARCADORES NOVOS PARA O PROCESSO
		IF (SELECT COUNT(1) FROM @MARKERIDS) > 0
			SET @EXECDATE = '20000101 00:00:00.000'
		ELSE
			SET @EXECDATE = @MAXDATE

		INSERT INTO @EXECINFO 
			SELECT DISTINCT HIS_N_IWF_N_CODIGO, ISNULL(HIS_ISP_N_ID,0), HIS_N_ETI_N_CODIGO, HIS_N_TIPOACAO, HIS_N_ACAOID, 
			                HIS_N_USR_EXECUTOR, HIS_D_GRAVACAO, MKR_C_VALUE, MKR_N_CODIGO
			FROM WHIS_HISTORICO_ITEM 
			INNER JOIN WMKR_MARKER ON HIS_N_TIPOACAO = MKR_N_ITEMTYPE AND HIS_N_ACAOID = MKR_N_ITEMID
			WHERE 
			MKR_C_NAME = @MARKERNAME AND
			HIS_N_PRO_N_CODIGO = @PROCESSID AND
			HIS_D_GRAVACAO > @EXECDATE

		INSERT INTO @EXECINFO 
			SELECT DISTINCT IEX_N_IWF_N_CODIGO, ISNULL(IEX_ISP_N_ID,0),IEX_N_ETI_N_CODIGO, IEX_N_TIPOACAO, IEX_N_ACAOID, 
			                IEX_N_USR_N_ID, IEX_D_EXECUCAO, MKR_C_VALUE, MKR_N_CODIGO
			FROM WIEX_ITEM_EXECUCAO 
			INNER JOIN WMKR_MARKER ON IEX_N_TIPOACAO = MKR_N_ITEMTYPE AND IEX_N_ACAOID = MKR_N_ITEMID
			WHERE
			MKR_C_NAME = @MARKERNAME AND
			MKR_PRO_N_CODIGO = @PROCESSID AND
			IEX_D_EXECUCAO > @EXECDATE 
		-- TRAZ TODOS OS REGISTROS E SO PEGA A ULTIMA EXECUCAO DE CADA VALOR DO MARCADOR
		INSERT INTO @GROUPEDINFO
		  SELECT X.*, 
				CONVERT(VARCHAR,ITEMID) + '-' + CONVERT(VARCHAR,SUBPROCESSID) + '-' + 
				CONVERT(VARCHAR,STEPITEM) + '-' + MARKERVALUE,
				ROW_NUMBER() OVER (PARTITION BY ITEMID,SUBPROCESSID,STEPITEM,MARKERVALUE ORDER BY GRAVACAO DESC)
		  FROM @EXECINFO AS X
		DELETE FROM @GROUPEDINFO WHERE EXECORDER <> 1

		-- INSERE OS VALORES NA TABELA DE MARCADORES SEM DUPLICAR 
		INSERT INTO @EXISTINGVALUES
			SELECT CONVERT(VARCHAR,MRS_IWF_N_CODIGO)  + '-' + CONVERT(VARCHAR,MRS_ISP_N_ID) + '-' +
			CONVERT(VARCHAR,MRS_ETI_N_CODIGO) + '-' + MRS_MKR_C_VALUE 
			FROM WMRS_MARKER_RESULT 
			WHERE 
			MRS_MKR_C_NAME = @MARKERNAME AND 
			MRS_PRO_N_CODIGO = @PROCESSID

		INSERT INTO WMRS_MARKER_RESULT(MRS_IWF_N_CODIGO,MRS_IPR_N_CODIGO,MRS_ISP_N_ID,MRS_ETI_N_CODIGO, 
			MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID,MRS_D_EXEC_DATE,MRS_MKR_C_NAME,MRS_MKR_C_VALUE, MRS_MKR_N_CODIGO)
			SELECT
				ITEMID,
				IPR_N_CODIGO,
				SUBPROCESSID,
				STEPITEM,
				@PROCESSID,
				EXECUTOR,
				GRAVACAO,
				@MARKERNAME,
				MARKERVALUE,
				MARKERID
			FROM
				@GROUPEDINFO AS A
				INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_IWF_N_CODIGO = ITEMID AND IPR_N_PRO_N_CODIGO = @PROCESSID
			WHERE UNIQUEKEY NOT IN (SELECT UNIQUEKEY FROM @EXISTINGVALUES)
		
		-- TRATAMENTO DOS VALORES DE ITENS FINALIZADOS
		SET @MAXDATE = '20000101 00:00:00.000'
		IF EXISTS(SELECT 1 FROM WMRS_MARKER_RESULT_FINISHED WHERE MRS_MKR_C_NAME = @MARKERNAME AND MRS_PRO_N_CODIGO = @PROCESSID)
			SELECT @MAXDATE = MAX(MRS_D_EXEC_DATE) 
			FROM WMRS_MARKER_RESULT_FINISHED 
			WHERE MRS_MKR_C_NAME = @MARKERNAME AND MRS_PRO_N_CODIGO = @PROCESSID

		DELETE FROM @MARKERIDS
		INSERT INTO @MARKERIDS
		SELECT MKR_N_CODIGO FROM WMKR_MARKER WHERE
				MKR_C_NAME =  @MARKERNAME AND
				MKR_D_CREATEDATE > @MAXDATE AND
				MKR_PRO_N_CODIGO = @PROCESSID AND
				MKR_N_CODIGO NOT IN (SELECT DISTINCT MRS_MKR_N_CODIGO FROM WMRS_MARKER_RESULT_FINISHED 
									 WHERE MRS_PRO_N_CODIGO = @PROCESSID)
		IF (SELECT COUNT(1) FROM @MARKERIDS) > 0
			SET @EXECDATE = '20000101 00:00:00.000'
		ELSE
			SET @EXECDATE = @MAXDATE

		DELETE FROM @EXISTINGVALUES
		INSERT INTO @EXISTINGVALUES
			SELECT CONVERT(VARCHAR,MRS_IWF_N_CODIGO)  + '-' + CONVERT(VARCHAR,MRS_ISP_N_ID) + '-' +
			CONVERT(VARCHAR,MRS_ETI_N_CODIGO) + '-' + MRS_MKR_C_VALUE 
			FROM WMRS_MARKER_RESULT_FINISHED 
			WHERE 
			MRS_MKR_C_NAME = @MARKERNAME AND 
			MRS_PRO_N_CODIGO = @PROCESSID
		
		DELETE FROM @GROUPEDINFO
		INSERT INTO @GROUPEDINFO
			SELECT H.HIF_N_IWF_N_CODIGO,ISNULL(H.HIF_ISP_N_ID, 0),H.HIF_N_ETI_N_CODIGO, H.HIF_N_TIPOACAO, H.HIF_N_ACAOID,
				   H.HIF_N_USR_EXECUTOR,H.HIF_D_GRAVACAO,M.MKR_C_VALUE,M.MKR_N_CODIGO,
				   CONVERT(VARCHAR,HIF_N_IWF_N_CODIGO) + '-' + CONVERT(VARCHAR,ISNULL(H.HIF_ISP_N_ID, 0)) + '-' +
				   CONVERT(VARCHAR,ISNULL(H.HIF_N_ETI_N_CODIGO, 0)) + '-' + M.MKR_C_VALUE,
				   ROW_NUMBER() OVER (PARTITION BY H.HIF_N_IWF_N_CODIGO,H.HIF_ISP_N_ID,H.HIF_N_ETI_N_CODIGO,M.MKR_C_VALUE ORDER BY H.HIF_D_GRAVACAO DESC)
			FROM WHIF_HISTORICO_FINALIZADO AS H
			INNER JOIN WMKR_MARKER AS M ON HIF_N_TIPOACAO = MKR_N_ITEMTYPE AND HIF_N_ACAOID = MKR_N_ITEMID
			WHERE 
			H.HIF_N_PRO_N_CODIGO = @PROCESSID AND 
			H.HIF_D_GRAVACAO > @EXECDATE AND
			M.MKR_C_NAME = @MARKERNAME
		DELETE FROM @GROUPEDINFO WHERE EXECORDER <> 1

		INSERT INTO WMRS_MARKER_RESULT_FINISHED (MRS_IWF_N_CODIGO, MRS_IPR_N_CODIGO, MRS_ISP_N_ID, MRS_ETI_N_CODIGO,
			MRS_PRO_N_CODIGO,MRS_N_USR_EXEC_ID, MRS_D_EXEC_DATE, MRS_MKR_C_NAME, MRS_MKR_C_VALUE, MRS_MKR_N_CODIGO)
			SELECT
				ITEMID,
				IPR_N_CODIGO,
				SUBPROCESSID,
				STEPITEM,
				@PROCESSID,
				EXECUTOR,
				GRAVACAO,
				@MARKERNAME,
				MARKERVALUE,
				MARKERID
			FROM
				@GROUPEDINFO AS A
				INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO = ITEMID AND IPR_N_PRO_N_CODIGO = @PROCESSID
			WHERE UNIQUEKEY NOT IN (SELECT UNIQUEKEY FROM @EXISTINGVALUES)

		FETCH NEXT FROM PROC_MKR INTO @PROCESSID, @MAXDATE
	END
	CLOSE PROC_MKR
	DEALLOCATE PROC_MKR
	SET NOCOUNT OFF
END
GO

IF OBJECT_ID('wpr_ResetALLMarkerValues') IS NULL
	EXEC('CREATE PROCEDURE wpr_ResetALLMarkerValues AS BEGIN	SELECT 1 END')
GO
ALTER PROCEDURE wpr_ResetALLMarkerValues(
	@MARKERNAME VARCHAR(200) = NULL
)
AS
BEGIN
	SET NOCOUNT ON
	IF NOT @MARKERNAME IS NULL 
	BEGIN
		DELETE FROM WMRS_MARKER_RESULT WHERE MRS_MKR_C_NAME = @MARKERNAME
		DELETE FROM WMRS_MARKER_RESULT_FINISHED WHERE MRS_MKR_C_NAME = @MARKERNAME
		EXEC wpr_UpdateMarkerValues @MARKERNAME
	END
	ELSE
	BEGIN
		DELETE FROM WMRS_MARKER_RESULT
		DELETE FROM WMRS_MARKER_RESULT_FINISHED
		DECLARE MKR_NAMES CURSOR FOR (SELECT DISTINCT MKR_C_NAME FROM WMKR_MARKER)
		OPEN MKR_NAMES
		FETCH NEXT FROM MKR_NAMES INTO @MARKERNAME
		WHILE @@FETCH_STATUS = 0            
		BEGIN
			EXEC wpr_UpdateMarkerValues @MARKERNAME
			FETCH NEXT FROM MKR_NAMES INTO @MARKERNAME
		END
		CLOSE MKR_NAMES
		DEALLOCATE MKR_NAMES
	END
	SET NOCOUNT OFF
END
GO

IF OBJECT_ID('wpr_GetItemMarkerValues') IS NULL
	EXEC('CREATE PROCEDURE wpr_GetItemMarkerValues AS BEGIN	SELECT 1 END')
GO

ALTER PROCEDURE [dbo].[wpr_GetItemMarkerValues](
	@MARKERNAME VARCHAR(150),
	@ITEMPROCESSID INT
)
AS
BEGIN
	SET NOCOUNT ON
	
	DECLARE @RETURNVALUES TABLE 
		(ITEMWORKFLOWID int,
		ITEMPROCESSID int,
		SUBPROCESSID int,
		PROCESSID int,
		USERID int,
		EXECDATE datetime,
		MARKERNAME varchar(200),
		MARKERVALUE varchar(200),
		MARKERID int)
	INSERT INTO @RETURNVALUES
	SELECT
		IPR_N_IWF_N_CODIGO AS ITEMWORKFLOWID,
		IPR_N_CODIGO AS ITEMPROCESSID,
		ISNULL(IEX_ISP_N_ID,'0') AS SUBPROCESSID,
		IPR_N_PRO_N_CODIGO AS PROCESSID,
		(SELECT IEX_N_USR_N_ID FROM  WIEX_ITEM_EXECUCAO AS B WHERE B.IEX_N_CODIGO = MAX(A.IEX_N_CODIGO)) AS USERID,
		(SELECT IEX_D_EXECUCAO FROM  WIEX_ITEM_EXECUCAO AS B WHERE B.IEX_N_CODIGO = MAX(A.IEX_N_CODIGO)) AS EXECDATE,
		MKR_C_NAME AS MARKERNAME,
		MKR_C_VALUE AS MARKERVALUE,
		MKR_N_CODIGO AS MARKERID
	FROM
		WIEX_ITEM_EXECUCAO AS A
		INNER JOIN WMKR_MARKER ON IEX_N_TIPOACAO = MKR_N_ITEMTYPE AND IEX_N_ACAOID = MKR_N_ITEMID
		INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_CODIGO = IEX_N_IPR_N_CODIGO
	WHERE
		MKR_C_NAME = @MARKERNAME 
		AND	IEX_N_IPR_N_CODIGO = @ITEMPROCESSID
	GROUP BY
		IPR_N_IWF_N_CODIGO,
		IPR_N_CODIGO,
		IEX_N_ETI_N_CODIGO,
		IEX_ISP_N_ID,
		IPR_N_PRO_N_CODIGO,
		MKR_C_NAME,
		MKR_C_VALUE,
		MKR_N_CODIGO
UNION		
	SELECT
		IPR_N_IWF_N_CODIGO AS ITEMWORKFLOWID,
		IPR_N_CODIGO AS ITEMPROCESSID,
		ISNULL(HIS_ISP_N_ID,0) AS SUBPROCESSID,
		IPR_N_PRO_N_CODIGO AS PROCESSID,
		(SELECT HIS_N_USR_EXECUTOR FROM  WHIS_HISTORICO_ITEM AS B WHERE B.HIS_N_CODIGO = MAX(A.HIS_N_CODIGO)) AS USERID,
		(SELECT HIS_D_GRAVACAO FROM  WHIS_HISTORICO_ITEM AS B WHERE B.HIS_N_CODIGO = MAX(A.HIS_N_CODIGO)) AS EXECDATE,
		MKR_C_NAME AS MARKERNAME,
		MKR_C_VALUE AS MARKERVALUE,
		MKR_N_CODIGO AS MARKERID
	FROM
		WHIS_HISTORICO_ITEM AS A
		INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_IWF_N_CODIGO = HIS_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIS_N_PRO_N_CODIGO
		INNER JOIN WMKR_MARKER ON HIS_N_TIPOACAO = MKR_N_ITEMTYPE AND HIS_N_ACAOID = MKR_N_ITEMID
	WHERE
		IPR_N_CODIGO = @ITEMPROCESSID AND
		MKR_C_NAME = @MARKERNAME
	GROUP BY
		IPR_N_IWF_N_CODIGO,
		IPR_N_CODIGO,
		HIS_N_ETI_N_CODIGO,
		HIS_ISP_N_ID,
		IPR_N_PRO_N_CODIGO,
		MKR_C_NAME,
		MKR_C_VALUE,
		MKR_N_CODIGO
UNION
	SELECT 
		MRS_IWF_N_CODIGO AS ITEMWORKFLOWID,
		MRS_IPR_N_CODIGO AS ITEMPROCESSID,
		MRS_ISP_N_ID AS SUBPROCESSID,
		MRS_PRO_N_CODIGO AS PROCESSID,
		MRS_N_USR_EXEC_ID AS USERID,
		MRS_D_EXEC_DATE AS EXECDATE,
		MRS_MKR_C_NAME AS MARKERNAME,
		MRS_MKR_C_VALUE AS MARKERVALUE,
		MRS_MKR_N_CODIGO AS MARKERID
	FROM 
		WMRS_MARKER_RESULT_FINISHED
	WHERE 
		MRS_IPR_N_CODIGO = @ITEMPROCESSID AND
		MRS_MKR_C_NAME = @MARKERNAME
	
	SELECT 
		MAX(ITEMWORKFLOWID) AS ITEMWORKFLOWID,
		MAX(ITEMPROCESSID) AS ITEMPROCESSID,
		SUBPROCESSID,
		PROCESSID,
		MAX(USERID) AS USERID,
		MAX(EXECDATE) AS EXECDATE,
		MAX(MARKERNAME) AS MARKERNAME,
		MARKERVALUE,
		MAX(MARKERID) AS MARKERID
	FROM 
		@RETURNVALUES
	GROUP BY 
		MARKERVALUE,
		SUBPROCESSID,
		PROCESSID
	ORDER BY EXECDATE
END
GO

--#################################################################################################################################
--***** DADOS DO ZURI *************************************************************************************************************
--#################################################################################################################################
SET NOCOUNT ON
--inclusão de módulos de workflow (só inclui os que não existirem)
IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'CA4F303D-F89E-4B92-9D4B-D8071358C57F')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'CA4F303D-F89E-4B92-9D4B-D8071358C57F', 'Etapa', '', 'components/Etapa.aspx', 710, 700, 1, 'bbbc9b8a-85be-4046-af9b-e5feae6912c3', 0, '', 'etapa.png', 'Construção', 4, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'BBBC9B8A-85BE-4046-AF9B-E5FEAE6912C3')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'BBBC9B8A-85BE-4046-AF9B-E5FEAE6912C3', 'Decisão', '', 'components/Decisao.aspx', 375, 335, 0, '', 2, 'ca4f303d-f89e-4b92-9d4b-d8071358c57f', 'decisao.png', 'Construção', 1, 1, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '47795C45-C5ED-4085-84F7-C455B8E3939D')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '47795C45-C5ED-4085-84F7-C455B8E3939D', 'Observador', '', 'components/Observador.aspx', 310, 620, 0, '', 0, '', 'observador.png', 'Construção', 1, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '1FB51CBA-5CEF-4264-85B8-8E34107C3D79')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '1FB51CBA-5CEF-4264-85B8-8E34107C3D79', 'Protegido', '', '', 0, 0, 0, '', 0, '', 'protegido.png', 'Construção', 1, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '3CBDA469-9A77-4C8E-AB36-C594AC38CD07')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '3CBDA469-9A77-4C8E-AB36-C594AC38CD07', 'Ponto de entrada', '', 'components/Entrada.aspx', 230, 340, 0, '', 0, '', 'entrada.png', 'Construção', 1, 0, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '36D24F1D-15DE-47F8-9300-F85057D28737')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '36D24F1D-15DE-47F8-9300-F85057D28737', 'Inicio', '', 'components/Inicio.aspx', 580, 750, 0, '', 0, '', 'inicio.png', 'Construção', 1, 0, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'EA6FDB27-E80F-47B0-BE22-C9D8036D8764')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'EA6FDB27-E80F-47B0-BE22-C9D8036D8764', 'Fim', '', '', 0, 0, 0, '', 0, '', 'final.png', 'Construção', 0, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '770201C8-9E53-43DC-815D-FD1488B80075')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '770201C8-9E53-43DC-815D-FD1488B80075', 'Atalho Origem', '', 'components/ConnOrigin.aspx', 220, 340, 0, '', 0, '', 'linkin.png', 'Documentos', 0, 1, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '37B6BBD5-491B-4BC1-9A8B-E8769A62BFDA')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '37B6BBD5-491B-4BC1-9A8B-E8769A62BFDA', 'Atalho Destino', '', 'components/ConnDestination.aspx', 220, 340, 0, '', 0, '', 'linkout.png', 'Documentos', 1, 0, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'EC6B2D08-54BC-40D2-B0F8-97151EF8B3CE')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'EC6B2D08-54BC-40D2-B0F8-97151EF8B3CE', 'Condensador', '', '', 0, 0, 0, '', 0, '', 'condensador.png', 'Construção', 1, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'F8D5E138-6D74-4E51-968C-E5C596EB3690')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'F8D5E138-6D74-4E51-968C-E5C596EB3690', 'Distribuidor', '', '', 0, 0, 2, 'ca4f303d-f89e-4b92-9d4b-d8071358c57f', 0, '', 'distribuidor.png', 'Construção', 4, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E5295ABD-EAD3-4DAA-AF1D-E5A564FE04A9')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'E5295ABD-EAD3-4DAA-AF1D-E5A564FE04A9', 'Comentário', '', '', 0, 0, 0, '', 0, '', 'comentario.png', 'Documentos', 0, 0, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '6EF3ECBC-8CE5-4674-8F56-8B18EED7E8F1')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '6EF3ECBC-8CE5-4674-8F56-8B18EED7E8F1', 'Ponto de parada', '', '', 0, 0, 0, '', 0, '', 'parada.png', 'Construção', 0, 2, 0, NULL, 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E51338A3-AB25-4F4A-9B0E-9E5A231A8233')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'E51338A3-AB25-4F4A-9B0E-9E5A231A8233', 'Cancela Etapa', 'cancelaetapa.ascx', 'modules/cancelaetapa.aspx', 200, 360, 0, '', 0, '', 'cancelaetapa.png', 'Módulos Básicos', 1, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'B84B5761-79EC-4773-AF92-9D00E2843DE1')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'B84B5761-79EC-4773-AF92-9D00E2843DE1', 'Data Limite', 'deadline.ascx', 'modules/deadline.aspx', 360, 450, 0, '', 0, '', 'deadline.png', 'Módulos Básicos', 1, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '8380B8F6-7B11-42A7-842E-1B40A261394E')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '8380B8F6-7B11-42A7-842E-1B40A261394E', 'Arquivo', 'arquivo.ascx', 'modules/arquivo.aspx', 620, 820, 0, '', 0, '', 'arquivo.png', 'Módulos Básicos', 1, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '9B13B80D-2A64-4266-B023-9A9C48E88C54')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '9B13B80D-2A64-4266-B023-9A9C48E88C54', 'Procedure', 'procedure.ascx', 'modules/Procedure.aspx', 485, 645, 0, '', 0, '', 'procedure.png', 'Módulos Básicos', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Procedure1', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'A8A069BF-2730-481A-A85A-FD2F37DF4A1D')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'A8A069BF-2730-481A-A85A-FD2F37DF4A1D', 'Filtro Dinâmico', 'filtrodinamico.ascx', 'modules/filtrodinamico.aspx', 350, 400, 0, '', 0, '', 'filtroDinamico.png', 'Módulos Básicos', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.FiltroDinamico1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '368BE043-E052-4E8E-A6A8-1B242960EEC8')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '368BE043-E052-4E8E-A6A8-1B242960EEC8', 'Mensagem', 'texto.ascx', 'modules/texto.aspx', 630, 930, 0, '', 0, '', 'texto.png', 'Módulos Básicos', 1, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '5DA76359-A239-467B-8B94-EDBF05A542B5')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '5DA76359-A239-467B-8B94-EDBF05A542B5', 'E-mail', 'email.ascx', 'modules/email.aspx', 710, 940, 0, '', 0, '', 'email.png', 'Módulos Básicos', 1, 2, 1, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Email1', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'C4698902-BFFE-45D2-8E0C-F18DC716F2DB')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'C4698902-BFFE-45D2-8E0C-F18DC716F2DB', 'Regra', 'regra.ascx', 'modules/regra.aspx', 500, 500, 0, '', 0, '', 'regra.png', 'Módulos Básicos', 3, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Regra1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'C9D1B328-6F78-4322-8952-287866F17E5B')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'C9D1B328-6F78-4322-8952-287866F17E5B', 'Dados externos', 'dadosexternos.ascx', 'modules/dadosexternos.aspx', 270, 400, 0, '', 0, '', 'importdata.png', 'Módulos Básicos', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.DadosExternos1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'BCB9E9AF-B503-4B01-A152-0CB32AB670C0')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'BCB9E9AF-B503-4B01-A152-0CB32AB670C0', 'Fluxo externo', 'fluxoexterno.ascx', 'modules/fluxoexterno.aspx', 370, 420, 0, '', 0, '', 'fluxoexterno.png', 'Módulos Básicos', 3, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '3AAA48DC-9426-4270-9B3B-407C8C094769')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '3AAA48DC-9426-4270-9B3B-407C8C094769', 'Formulario', 'WFFormsModule.ascx', 'modules/WFForms.aspx', 345, 645, 0, '', 0, '', 'formulario.png', 'Módulos Básicos', 1, 2, 1, '', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '041BD21B-17A1-4DCF-B49B-A7DC392AA1C0')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '041BD21B-17A1-4DCF-B49B-A7DC392AA1C0', 'Adiciona Grupo', 'adicionagrupo.ascx', 'modules/adicionagrupo.aspx', 330, 630, 0, '', 0, '', 'adicionagrupo.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.AdicionaGrupo1', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'ACFDE8CE-9386-4C0D-A6B5-E6E8FA7EC3C7')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'ACFDE8CE-9386-4C0D-A6B5-E6E8FA7EC3C7', 'Atribui Usuario', 'AtribuiUsuario.ascx', 'modules/AtribuiUsuario.aspx', 340, 630, 0, '', 0, '', 'atribuiusuario.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.AtribuiUsuario1', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'EA548DB4-4A99-469A-B932-460ADB345D18')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'EA548DB4-4A99-469A-B932-460ADB345D18', 'Delega Grupo', 'DelegaGrupo.ascx', 'modules/DelegaGrupo.aspx', 330, 635, 0, '', 0, '', 'DelegaGrupo.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.DelegaGrupo1', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'B190949D-2519-4A59-BE72-3DD0F1033810')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'B190949D-2519-4A59-BE72-3DD0F1033810', 'Desviar', 'Desvia.ascx', 'modules/Desviar.aspx', 330, 450, 0, '', 0, '', 'desviar.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.Desvia', 0, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'D7841B5B-FDFE-40B8-9A4B-2B01935236C6')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'D7841B5B-FDFE-40B8-9A4B-2B01935236C6', 'Finaliza Item', 'FinalizaItem.ascx', '', 330, 460, 0, '', 0, '', 'finalizaitem.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.FinalizaItem1', 0, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'C54FD91E-6D86-488E-B448-F2BEED66537D')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'C54FD91E-6D86-488E-B448-F2BEED66537D', 'Informações do Item', 'ItemInfo.ascx', 'modules/ItemInfo.aspx', 330, 445, 0, '', 0, '', 'iteminfo.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.ItemInfo1', 0, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'F63F5263-4B61-4B89-BE5F-470B6FC788FF')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'F63F5263-4B61-4B89-BE5F-470B6FC788FF', 'Move Anexo', 'MoveAnexo.ascx', 'modules/MoveAnexo.aspx', 330, 400, 0, '', 0, '', 'moveanexo.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.MoveAnexo1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E8588324-A835-408D-A85B-41803920A1E2')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'E8588324-A835-408D-A85B-41803920A1E2', 'WebService SOAP', 'WebService.ascx', 'modules/WebService.aspx', 485, 645, 0, '', 0, '', 'webservice.png', 'integration', 3, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.WebService', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E7A2F199-EF79-40BD-B5F3-E99D97CC91F2')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'E7A2F199-EF79-40BD-B5F3-E99D97CC91F2', 'Gerador PDF', 'PDFCreator.ascx', 'modules/PDFCreator.aspx', 485, 645, 0, '', 0, '', 'pdfcreator.png', 'Módulos Básicos', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.PDFCreator1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '0E91097C-C199-4C77-8727-65B1A6EA8833')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '0E91097C-C199-4C77-8727-65B1A6EA8833', 'Download Anexo', 'DownloadAnexo.ascx', 'modules/DownloadAnexo.aspx', 485, 645, 0, '', 0, '', 'download.png', 'Módulos Básicos', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.DownloadFile1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '1D6755CE-6FDB-423F-9DB4-897662DA1BD5')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '1D6755CE-6FDB-423F-9DB4-897662DA1BD5', 'Subprocesso', 'SubProcess.ascx', 'modules/SubProcess.aspx', 500, 600, 0, '', 0, '', 'subprcall.png', 'Navegação', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.SubProcess', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E673CA71-CA02-48F4-9FAF-701B880E39E2')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'E673CA71-CA02-48F4-9FAF-701B880E39E2', 'Subprocesso Início', 'SubProcessStart.ascx', 'modules/SubProcessStart.aspx', 400, 600, 0, '', 0, '', 'subprstart.png', 'Navegação', 1, 0, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.SubProcessStart', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'CEB0220E-D344-46BE-BBD2-1A982751EBBA')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', 'CEB0220E-D344-46BE-BBD2-1A982751EBBA', 'Subprocesso Fim', 'SubProcessEnd.ascx', '', 0, 0, 0, '', 0, '', 'subprend.png', 'Navegação', 0, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.SubProcessEnd', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'A89369F6-55F7-4854-B216-79F394BAB6EE')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'A89369F6-55F7-4854-B216-79F394BAB6EE', 'WebService REST', 'RestApi.ascx', 'modules/RestApiConfig.aspx', 500, 600, 0, '', 0, '', 'restapi.png', 'integration', 3, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.RestApi', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'BAD3B0FA-515E-4217-8945-47D9D0E1A2E6')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'BAD3B0FA-515E-4217-8945-47D9D0E1A2E6', 'Reunião', 'Meeting.ascx', 'modules/Meeting.aspx', 710, 940, 0, '', 0, '', 'meeting.png', 'Módulos Básicos', 1, 2, 1, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Meeting1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '3089F45D-6915-4727-903D-84E7F4074D1F')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '3089F45D-6915-4727-903D-84E7F4074D1F', 'Anexar Dados', 'XmlAttach.ascx', 'modules/XmlAttach.aspx', 300, 400, 0, '', 0, '', 'XmlAttach.png', 'Complementares', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.XmlAttach1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '80FB6BE8-B619-4118-BB67-54A57D2E4B47')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '80FB6BE8-B619-4118-BB67-54A57D2E4B47', 'Exclui Usuario', 'filtrausuario.ascx', 'modules/filtrausuario.aspx', 350, 400, 0, '', 0, '', 'filtrausuario.png', 'Filtros', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.FiltraUsuario', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'B4AA1704-C8B5-46ae-8E70-CE00253EE023')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'B4AA1704-C8B5-46ae-8E70-CE00253EE023', 'Senha na decisao', 'confirmadecisao.ascx', '', 0, 0, 0, '', 0, '', '', 'Módulos Básicos', 1, 2, 1, ' WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.ConfirmaDecisao', 0, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'B407BA38-9DCB-44f9-B8D1-F227C76C0097')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'B407BA38-9DCB-44f9-B8D1-F227C76C0097', 'Atribui Etapa', 'atribuietapa.ascx', '', 0, 0, 0, '', 0, '', '', 'Módulos Básicos', 1, 2, 1, ' WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.AtribuiEtapa', 0, 0)


IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'C4BBBE8E-E24A-473E-8B7B-692FDF939F6C')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'C4BBBE8E-E24A-473E-8B7B-692FDF939F6C', 'SLA do Item', 'ItemSLA.ascx', 'modules/ItemSLA.aspx', 400, 600, 0, '', 0, '', 'itemsla.png', 'integration', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.ItemSLA1', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'BA01C413-589D-44D0-BF47-981A85BBC389')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'BA01C413-589D-44D0-BF47-981A85BBC389', 'Importador Excel', 'ExcelImporter.ascx', 'modules/ExcelImporter.aspx', 600, 820, 0, '', 0, '', 'excelimporter.png', 'Complementares', 1, 2, 1, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.ExcelImporter', 1, 0)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '9E900659-89D6-4134-9C0A-2DBB53166824')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '9E900659-89D6-4134-9C0A-2DBB53166824', 'Código', 'UserCode.ascx', 'modules/UsercodeConfig.aspx', 680, 1240, 0, '', 0, '', 'code.png', 'integration', 1, 2, 0, ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.UserCode', 1, 1)

IF NOT EXISTS(SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '5E1B5704-9A42-48B6-9DC0-A8625CFEB7B1')
INSERT WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO) 
VALUES ('3CFC8AF3-C07E-4F14-B398-4A8917D97C92', '5E1B5704-9A42-48B6-9DC0-A8625CFEB7B1', 'Decisão', 'Decision.ascx', 'modules/Decision.aspx', 330, 450, 0, '', 0, '', 'decisao.png', 'Módulos Básicos', 1, 2, 0, 'WebFoundations.WFWorkflow.UI.dll|WebFoundations.WFWorkflow.UI.Decision', 0, 1)

--#################################################################################################################################

IF NOT EXISTS (SELECT 1 FROM WPRO_PROCESSO)
BEGIN
	SET IDENTITY_INSERT WPRO_PROCESSO ON

	INSERT WPRO_PROCESSO (PRO_N_CODIGO, PRO_C_NOME, PRO_C_DESCRICAO, PRO_C_GESTORES, PRO_N_ARE_N_CODIGO, PRO_N_ATIVO, PRO_N_EDICAO, PRO_D_CRIACAO, PRO_N_USU_CRIADOR, PRO_D_ALTERACAO, PRO_N_USU_ALTERADOR, PRO_N_ARQUIVAMENTO,  PRO_N_ETA_INICIAL, PRO_C_TITULOITEM, PRO_N_USECOUNTER, PRO_N_SKIPDUPLICATE, PRO_N_ADDCOMMENT, PRO_N_ADDFILE) VALUES (1, 'Default Values', 
	'Default Values', '-1;', 1, 0, 0, getdate(), 1, getdate(), 1, 360, 1, '', 0, 1,1,1)
	SET IDENTITY_INSERT WPRO_PROCESSO OFF
END

--#################################################################################################################################

IF NOT EXISTS (SELECT 1 FROM WETA_ETAPA_PROCESSO WHERE ETA_N_CODIGO = 1)
BEGIN
	SET IDENTITY_INSERT WETA_ETAPA_PROCESSO ON

	INSERT WETA_ETAPA_PROCESSO (ETA_N_CODIGO, ETA_N_PART_ID, ETA_N_PRO_N_CODIGO, ETA_C_NOME, ETA_C_GRUPOPERFIL, ETA_C_GESTORES, ETA_N_TIPOETAPA, ETA_N_ATRIBUICAO, ETA_N_PERFILRESTRICAO, ETA_N_GRPDELEGAVEL) 
	VALUES (1, 1, 1, 'Default step', '', '-1;', 1, 0, 0, 0)

	SET IDENTITY_INSERT WETA_ETAPA_PROCESSO OFF
END

--#################################################################################################################################

IF NOT EXISTS (SELECT 1 FROM WWKD_WORKDAYS)
BEGIN
	SET IDENTITY_INSERT WWKD_WORKDAYS ON

	INSERT WWKD_WORKDAYS (WKD_N_CODIGO, WKD_N_PRO_N_CODIGO, WKD_N_ETA_N_CODIGO, WKD_C_SEG_SEX_INI, WKD_C_SEG_SEX_FIM, WKD_C_SABADO_INI, WKD_C_SABADO_FIM, WKD_C_DOMINGO_INI, WKD_C_DOMINGO_FIM) 
	VALUES (1, 1, 1, '09:00', '18:00', '', '', '', '')

	SET IDENTITY_INSERT WWKD_WORKDAYS OFF
END

--#################################################################################################################################

IF NOT EXISTS (SELECT 1 FROM WPRI_PRIORIDADE)
BEGIN
	SET IDENTITY_INSERT WPRI_PRIORIDADE ON

	INSERT WPRI_PRIORIDADE (PRI_N_CODIGO, PRI_N_PRO_N_CODIGO, PRI_C_TITULO, PRI_N_VALOR) VALUES (1, 1, 'Baixa', 1)
	INSERT WPRI_PRIORIDADE (PRI_N_CODIGO, PRI_N_PRO_N_CODIGO, PRI_C_TITULO, PRI_N_VALOR) VALUES (2, 1, 'Média', 2)
	INSERT WPRI_PRIORIDADE (PRI_N_CODIGO, PRI_N_PRO_N_CODIGO, PRI_C_TITULO, PRI_N_VALOR) VALUES (3, 1, 'Alta', 3)

	SET IDENTITY_INSERT WPRI_PRIORIDADE OFF
END

--#################################################################################################################################

IF NOT EXISTS (SELECT 1 FROM WETS_ETAPA_SLA)
BEGIN
	SET IDENTITY_INSERT WETS_ETAPA_SLA ON

	INSERT [WETS_ETAPA_SLA] ([ETS_N_CODIGO], [ETS_C_NOME], [ETS_C_COR], [ETS_N_ORDEM], [ETS_N_ATRASO], [ETS_B_ACTIVE]) VALUES (1, N'No prazo', N'#049D01', 1, 0, 1)
	INSERT [WETS_ETAPA_SLA] ([ETS_N_CODIGO], [ETS_C_NOME], [ETS_C_COR], [ETS_N_ORDEM], [ETS_N_ATRASO], [ETS_B_ACTIVE]) VALUES (2, N'Atrasado', N'#CB0606', 3, 1, 1)
	INSERT [WETS_ETAPA_SLA] ([ETS_N_CODIGO], [ETS_C_NOME], [ETS_C_COR], [ETS_N_ORDEM], [ETS_N_ATRASO], [ETS_B_ACTIVE]) VALUES (3, N'Expirando', N'#FFB800', 2, 0, 1)

	SET IDENTITY_INSERT WETS_ETAPA_SLA OFF
END

--#################################################################################################################################
--GARANTE QUE TODOS OS ÍCONES DE MÓDULOS DO ZURI ESTÃO CONFIGURADOS PARA USAR PNG, NÃO GIF

SET NOCOUNT ON
UPDATE WMOD_MODULO SET MOD_C_ICONE = REPLACE(MOD_C_ICONE, '.gif', '.png')
UPDATE WPRZ_PRAZO SET PRZ_N_CONFIGURED = 1 WHERE PRZ_N_CONFIGURED IS NULL
UPDATE WETI_ETAPA_ITEM SET ETI_N_ETS_N_CODIGO = (SELECT MIN(ETS_N_CODIGO) FROM WETS_ETAPA_SLA WHERE ETS_N_ORDEM = 0) WHERE ETI_N_ETS_N_CODIGO IS NULL

--#AJUSTE NAS INFORMACOES DE ESTATISTICAS POIS GRAVAVA PRAZO FULL EM HORAS AO INVES DE MINUTOS
UPDATE WFESE_ESTATISTICA_ETAPA SET ESE_N_PRAZOFULL = ESE_N_PRAZOFULL * 60 WHERE ESE_N_PRAZOFULL < ESE_N_PRAZOREAL 
UPDATE WFESP_ESTATISTICA_PROCESSO SET ESP_N_PRAZOFULL = ESP_N_PRAZOFULL * 60 WHERE ESP_N_PRAZOFULL < ESP_N_PRAZOREAL 

--AJUSTE PARA GARANTIR QUE OS MARCADORES SERÃO SINALIZADOS CORRETAMENTE NO DESIGNER
UPDATE WNOD_NODE  SET NOD_B_MARKER = (SELECT COUNT(*) FROM WMKR_MARKER WHERE MKR_NOD_N_ID = NOD_N_ID)
--#################################################################################################################################
--### ATUALIZA OS NOMES DAS PORTAS DE SAÍDA NO DESIGNER PARA USAR O TITULO E NAO O VALUE ##########################################
UPDATE NP
SET NP.NOP_C_TITLE = REPLACE(ISNULL(ATS_C_TITULO , ''), '[ELSE]', 'else')
FROM WNOP_NODEPORT NP
INNER JOIN WATS_ATIVIDADE_SAIDA ON NOP_ATS_N_CODIGO = ATS_N_CODIGO AND NOP_C_TITLE <> REPLACE(ISNULL(ATS_C_TITULO , ''), '[ELSE]', 'else')
WHERE ATS_C_TITULO <> ATS_C_VALOR 
--#################################################################################################################################
--Ajuste no título dos nodes de fim que podem ter mudado de título se o id coincidir com uma atividade existente.
update WNOD_NODE set NOD_C_TITLE = 'Fim' where nod_mod_c_itemid = 'EA6FDB27-E80F-47B0-BE22-C9D8036D8764' and NOD_C_TITLE <> 'Fim'

--Ajuste no título dos nodes de distribuidor que podem ter mudado de título se o id coincidir com uma atividade existente.
UPDATE WNOD_NODE SET NOD_C_TITLE = 'Distribuidor' WHERE NOD_MOD_C_ITEMID = 'F8D5E138-6D74-4E51-968C-E5C596EB3690' AND NOD_C_TITLE <> 'Distribuidor'

--ATUALIZA A CONFIGURACAO DE MODULOS CONDENSADOR ANTIGOS PARA QUE O ID DA ATIVIDADE SEJA O ID DO NODE (POIS ESSE COMPORTAMENTO MUDOU DEPOIS DA IMPLEMENTACAO DO ESQUEMA DE DEPENDENCIA)
UPDATE WNOD_NODE SET NOD_ATV_N_CODIGO = NOD_N_ID WHERE NOD_MOD_C_ITEMID = 'EC6B2D08-54BC-40D2-B0F8-97151EF8B3CE' AND NOD_ATV_N_CODIGO = 0

--#################################################################################################################################
SET NOCOUNT OFF
GO

SET NOCOUNT ON
--#####################################################################################################################
--***** ITEM FINALIZADO MOVE ITENS INICIO
--#####################################################################################################################
IF NOT EXISTS (SELECT 1 FROM WIWF_ITEM_WORKFLOW_FINALIZADO)
BEGIN
	INSERT INTO WIWF_ITEM_WORKFLOW_FINALIZADO
		(IWF_N_CODIGO,
		IWF_C_NOME,
		IWF_C_STATUS,
		IWF_D_DATAINICIO,
		IWF_N_READONLY,
		IWF_N_USU_OWNER,
		IWF_N_ARE_ORIGEM,
		IWF_N_ITE_ORIGEM,
		IWF_N_PRO_ORIGEM,
		IWF_D_DATAFIM,
		IWF_C_PARAM1,
		IWF_C_PARAM2,
		IWF_C_PARAM3,
		IWF_C_PARAM4,
		IWF_C_PARAM5,
		IWF_C_METADATA)
	SELECT 		
		IWF_N_CODIGO,
		IWF_C_NOME,
		IWF_C_STATUS,
		IWF_D_DATAINICIO,
		IWF_N_READONLY,
		IWF_N_USU_OWNER,
		IWF_N_ARE_ORIGEM,
		IWF_N_ITE_ORIGEM,
		IWF_N_PRO_ORIGEM,
		IWF_D_DATAFIM,
		IWF_C_PARAM1,
		IWF_C_PARAM2,
		IWF_C_PARAM3,
		IWF_C_PARAM4,
		IWF_C_PARAM5,
		IWF_C_METADATA
	FROM 
		WIWF_ITEM_WORKFLOW
	WHERE 
		NOT IWF_D_DATAFIM IS NULL
		AND IWF_N_CODIGO NOT IN (SELECT IWF_N_CODIGO FROM WIWF_ITEM_WORKFLOW_FINALIZADO)

	INSERT INTO WIPR_ITEM_PROCESSO_FINALIZADO 
		(IPR_N_CODIGO,
		IPR_N_IWF_N_CODIGO,
		IPR_N_PRO_N_CODIGO,
		IPR_N_COUNTERID,
		IPR_N_PRIORIDADE,
		IPR_D_DATAINICIO,
		IPR_C_STATUSCOLOR,
		IPR_N_FINALIZADO,
		IPR_C_LISTAACESSO,
		IPR_N_LOCALIDADE,
		IPR_C_METADATA,
		IPR_D_SLAFINAL,
		IPR_N_CURRENTSLA)
	SELECT 		
		IPR_N_CODIGO,
		IPR_N_IWF_N_CODIGO,
		IPR_N_PRO_N_CODIGO,
		IPR_N_COUNTERID,
		IPR_N_PRIORIDADE,
		IPR_D_DATAINICIO,
		IPR_C_STATUSCOLOR,
		IPR_N_FINALIZADO,
		IPR_C_LISTAACESSO,
		IPR_N_LOCALIDADE,
		IPR_C_METADATA,
		IPR_D_SLAFINAL,
		IPR_N_CURRENTSLA
	FROM 
		WIPR_ITEM_PROCESSO
	WHERE 
		IPR_N_IWF_N_CODIGO IN (SELECT IWF_N_CODIGO FROM WIWF_ITEM_WORKFLOW_FINALIZADO)
		AND IPR_N_CODIGO NOT IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO)


		INSERT INTO WIMR_ITEM_MSG_RDRS_FIM 
		(IMR_N_ID,
		IMR_USR_N_ID,
		IMR_IMG_N_ID,
		IMR_B_ISRECIPIENT,
		IMR_B_READ, IMR_B_LIKED, IMR_B_FLAGGED)
	SELECT 		
		IMR_N_ID,
		IMR_USR_N_ID,
		IMR_IMG_N_ID,
		IMR_B_ISRECIPIENT,
		IMR_B_READ, IMR_B_LIKED, IMR_B_FLAGGED
	FROM 
		WIMR_ITEM_MESSAGE_READERS
	WHERE 
		IMR_IMG_N_ID IN (SELECT IMG_N_ID FROM WIMG_ITEM_MESSAGE_FINALIZADO)
		AND IMR_N_ID NOT IN (SELECT IMR_N_ID FROM WIMR_ITEM_MSG_RDRS_FIM)

	IF columnproperty(object_id('WIMG_ITEM_MESSAGE_FINALIZADO'),'IMG_N_ID','IsIdentity') = 1
	BEGIN
		SET IDENTITY_INSERT WIMG_ITEM_MESSAGE_FINALIZADO ON
	END
	INSERT INTO WIMG_ITEM_MESSAGE_FINALIZADO 
		(IMG_N_ID,
		IMG_IPR_N_CODIGO,
		IMG_C_SUBJECT,
		IMG_C_MESSAGE,
		IMG_N_SENDER,
		IMG_C_SENDERSTEP,
		IMG_C_RECIPIENT,
		IMG_C_CARBONCOPY,
		IMG_D_DATECREATED,
		IMG_IMG_N_ID, 
		IMG_PRO_N_CODIGO)
	SELECT 		
		IMG_N_ID,
		IMG_IPR_N_CODIGO,
		IMG_C_SUBJECT,
		IMG_C_MESSAGE,
		IMG_N_SENDER,
		IMG_C_SENDERSTEP,
		IMG_C_RECIPIENT,
		IMG_C_CARBONCOPY,
		IMG_D_DATECREATED,
		IMG_IMG_N_ID, 
		IMG_PRO_N_CODIGO
	FROM 
		WIMG_ITEM_MESSAGE
	WHERE 
		IMG_IPR_N_CODIGO IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO)
		AND IMG_N_ID NOT IN (SELECT IMG_N_ID FROM WIMG_ITEM_MESSAGE_FINALIZADO)

	IF columnproperty(object_id('WIMG_ITEM_MESSAGE_FINALIZADO'),'IMG_N_ID','IsIdentity') = 1
	BEGIN
		SET IDENTITY_INSERT WIMG_ITEM_MESSAGE_FINALIZADO OFF
	END

	DELETE FROM WIWF_ITEM_WORKFLOW WHERE IWF_N_CODIGO IN (SELECT IWF_N_CODIGO FROM WIWF_ITEM_WORKFLOW_FINALIZADO)
	DELETE FROM WIMG_ITEM_MESSAGE WHERE IMG_N_ID IN (SELECT IMG_N_ID FROM WIMG_ITEM_MESSAGE_FINALIZADO)
	DELETE FROM WIMR_ITEM_MESSAGE_READERS WHERE IMR_N_ID IN (SELECT IMR_N_ID FROM WIMR_ITEM_MSG_RDRS_FIM)
	DELETE FROM WIMR_ITEM_MESSAGE_READERS WHERE IMR_IMG_N_ID NOT IN (SELECT IMG_N_ID FROM WIMG_ITEM_MESSAGE)
	DELETE FROM WFESP_ESTATISTICA_PROCESSO WHERE ESP_N_IPR_N_CODIGO NOT IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO)
	DELETE FROM WFESE_ESTATISTICA_ETAPA WHERE ESE_N_IPR_N_CODIGO NOT IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO)
	DELETE FROM WIRF_ITEM_READERS_FINALIZADO WHERE IRF_N_IPR_N_CODIGO NOT IN (SELECT IPR_N_CODIGO FROM WIPR_ITEM_PROCESSO_FINALIZADO)
END
SET NOCOUNT OFF
GO
-- RECUPERA OS RELACIONAMENTOS DEPOIS DA ALTERAÇÃO --

IF NOT OBJECT_ID('FK_WIMR_ITEM_MESSAGE_READERS_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WIMR_ITEM_MESSAGE_READERS 
		DROP CONSTRAINT FK_WIMR_ITEM_MESSAGE_READERS_WIPR_ITEM_PROCESSO
END
GO

IF OBJECT_ID('FK_ITEMMESSAGEREADERS_ITEMMESSAGE') IS NULL
BEGIN
	ALTER TABLE WIMR_ITEM_MESSAGE_READERS 
		ADD CONSTRAINT FK_ITEMMESSAGEREADERS_ITEMMESSAGE FOREIGN KEY (IMR_IMG_N_ID)
			REFERENCES WIMG_ITEM_MESSAGE (IMG_N_ID) ON DELETE CASCADE
END
GO

IF OBJECT_ID('FK_WIMG_ITEM_MESSAGE_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE 
			ADD CONSTRAINT FK_WIMG_ITEM_MESSAGE_WIPR_ITEM_PROCESSO FOREIGN KEY (IMG_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE

END
GO

IF OBJECT_ID('FK_ITEMMESSAGE_ITEMPROCESSO_FINALIZADO') IS NULL
BEGIN
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO 
		ADD CONSTRAINT FK_ITEMMESSAGE_ITEMPROCESSO_FINALIZADO FOREIGN KEY (IMG_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
END
GO

IF OBJECT_ID('FK_WANF_ANEXO_FINALIZADO_WIWF_ITEM_WORKFLOW') IS NULL
BEGIN
	ALTER TABLE WANF_ANEXO_FINALIZADO 
		ADD CONSTRAINT FK_WANF_ANEXO_FINALIZADO_WIWF_ITEM_WORKFLOW FOREIGN KEY(ANF_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW_FINALIZADO (IWF_N_CODIGO) ON DELETE CASCADE
END
GO


IF OBJECT_ID('FK_WHIF_HISTORICO_FINALIZADO_WIWF_ITEM_WORKFLOW') IS NULL
BEGIN
	ALTER TABLE WHIF_HISTORICO_FINALIZADO  
		ADD CONSTRAINT FK_WHIF_HISTORICO_FINALIZADO_WIWF_ITEM_WORKFLOW FOREIGN KEY(HIF_N_IWF_N_CODIGO)
			REFERENCES WIWF_ITEM_WORKFLOW_FINALIZADO (IWF_N_CODIGO) ON DELETE CASCADE
END
GO

IF OBJECT_ID('FK_WFESP_ESTATISTICA_PROCESSO_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WFESP_ESTATISTICA_PROCESSO 
		ADD CONSTRAINT FK_WFESP_ESTATISTICA_PROCESSO_WIPR_ITEM_PROCESSO FOREIGN KEY(ESP_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
END
GO

IF OBJECT_ID('FK_WFESE_ESTATISTICA_ETAPA_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WFESE_ESTATISTICA_ETAPA 
		ADD CONSTRAINT FK_WFESE_ESTATISTICA_ETAPA_WIPR_ITEM_PROCESSO FOREIGN KEY(ESE_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
END
GO

IF OBJECT_ID('FK_WIRF_WIPR_ITEM_PROCESSO') IS NULL
BEGIN
	ALTER TABLE WIRF_ITEM_READERS_FINALIZADO 
		ADD CONSTRAINT FK_WIRF_WIPR_ITEM_PROCESSO FOREIGN KEY(IRF_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO_FINALIZADO (IPR_N_CODIGO) ON DELETE CASCADE
END
GO

SET NOCOUNT ON
IF NOT OBJECT_ID('PK_ITEMMESSAGE_FINALIZADO') IS NULL
BEGIN	
	DECLARE @EXECSTATEMENTS VARCHAR(2000)
	-- Adiciona coluna temporária e popula com os Id´s da PK (tabela WIMG_ITEM_MESSAGE_FINALIZADO)
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO
	ADD IMG_N_TEMP_ID INT NULL
	EXEC('UPDATE WIMG_ITEM_MESSAGE_FINALIZADO SET IMG_N_TEMP_ID = IMG_N_ID')

	-- Adiciona coluna temporária e popula com os Id´s da PK (tabela WIMR_ITEM_MSG_RDRS_FIM)
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM
	ADD IMR_N_TEMP_ID INT NULL
	EXEC('UPDATE WIMR_ITEM_MSG_RDRS_FIM	SET IMR_N_TEMP_ID = IMR_N_ID')

	-- Remove PK´s e FK´s das tabelas WIMG_ITEM_MESSAGE_FINALIZADO e WIMR_ITEM_MSG_RDRS_FIM
	IF NOT OBJECT_ID('FK_ITEMMESSAGEREADERS_ITEMMESSAGE_FINALIZADO') IS NULL
	BEGIN
		ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM DROP CONSTRAINT FK_ITEMMESSAGEREADERS_ITEMMESSAGE_FINALIZADO
	END

	IF NOT OBJECT_ID('PK_ITEMMESSAGE_READERS_FINALIZADO') IS NULL
	BEGIN
		ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM DROP CONSTRAINT PK_ITEMMESSAGE_READERS_FINALIZADO
	END

	IF NOT OBJECT_ID('PK_ITEMMESSAGE_FINALIZADO') IS NULL
	BEGIN
		ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO DROP CONSTRAINT PK_ITEMMESSAGE_FINALIZADO
	END

	-- Remove coluna Identity, adiciona a mesma coluna sem identity,
	-- popula com os valores da coluna temporária, exclui coluna temporária (tabela WIMG_ITEM_MESSAGE_FINALIZADO)
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO
	DROP COLUMN IMG_N_ID
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO
	ADD IMG_N_ID INT NOT NULL DEFAULT 0
	EXEC('UPDATE WIMG_ITEM_MESSAGE_FINALIZADO SET IMG_N_ID = IMG_N_TEMP_ID')
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO
	DROP COLUMN IMG_N_TEMP_ID

	-- Remove coluna Identity, adiciona a mesma coluna sem identity,
	-- popula com os valores da coluna temporária, exclui coluna temporária (tabela WIMR_ITEM_MSG_RDRS_FIM)
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM
	DROP COLUMN IMR_N_ID
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM
	ADD IMR_N_ID INT NOT NULL DEFAULT 0
	EXEC('UPDATE WIMR_ITEM_MSG_RDRS_FIM SET IMR_N_ID = IMR_N_TEMP_ID')
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM
	DROP COLUMN IMR_N_TEMP_ID

	-- Adiciona PK´s e FK´s
	ALTER TABLE WIMG_ITEM_MESSAGE_FINALIZADO
		ADD CONSTRAINT PK_ITEMMSG_FINALIZADO PRIMARY KEY CLUSTERED (IMG_N_ID ASC)

	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM
		ADD CONSTRAINT PK_ITEMMSG_READERS_FINALIZADO PRIMARY KEY CLUSTERED (IMR_N_ID ASC)

	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM 
		ADD CONSTRAINT FK_ITEMMSGREADERS_ITEMMMSG_FINALIZADO FOREIGN KEY (IMR_IMG_N_ID)
			REFERENCES WIMG_ITEM_MESSAGE_FINALIZADO (IMG_N_ID) ON DELETE CASCADE
END
SET NOCOUNT OFF
GO

IF OBJECT_ID('FK_ITEMMSGREADERS_ITEMMMSG_FINALIZADO') IS NULL
BEGIN
	ALTER TABLE WIMR_ITEM_MSG_RDRS_FIM 
		ADD CONSTRAINT FK_ITEMMSGREADERS_ITEMMMSG_FINALIZADO FOREIGN KEY (IMR_IMG_N_ID)
			REFERENCES WIMG_ITEM_MESSAGE_FINALIZADO (IMG_N_ID) ON DELETE CASCADE
END
GO
--#####################################################################################################################
--***** ITEM FINALIZADO MOVE ITENS FINAL
--#####################################################################################################################

--#####################################################################################################################
--***** AJUSTE PARA REMOVER DUPLICIDADE DE EVENTOS NA TABELA DE ITENS FINALIZADOS
--#####################################################################################################################
SET NOCOUNT ON
IF NOT OBJECT_ID('WHIF_HISTORICO_FINALIZADOOLD') IS NULL AND OBJECT_ID('WHIF_HISTORICO_ARQUIVADO') IS NULL
	EXEC SP_RENAME WHIF_HISTORICO_FINALIZADOOLD , WHIF_HISTORICO_ARQUIVADO
SET NOCOUNT OFF
GO

SET NOCOUNT ON
IF NOT OBJECT_ID('WHIF_HISTORICO_FIM_OLD') IS NULL AND OBJECT_ID('WHIF_HISTORICO_ARQUIVADO') IS NULL
	EXEC SP_RENAME WHIF_HISTORICO_FIM_OLD , WHIF_HISTORICO_ARQUIVADO
SET NOCOUNT OFF
GO

SET NOCOUNT ON
IF NOT EXISTS(SELECT 1 FROM WHIF_HISTORICO_ARQUIVADO)
BEGIN
	BEGIN TRAN
	INSERT INTO WHIF_HISTORICO_ARQUIVADO(
		HIF_N_PRO_N_CODIGO,
		HIF_N_IWF_N_CODIGO,
		HIF_N_USR_EXECUTOR,
		HIF_N_ETA_N_CODIGO,
		HIF_N_ETI_N_CODIGO,
		HIF_C_STATUS,
		HIF_D_GRAVACAO,
		HIF_C_DESCRICAO,
		HIF_N_ACAOID,
		HIF_N_TIPOACAO,
		HIF_N_EVE_N_ID,
		HIF_N_ATIVO,
		HIF_ISP_N_ID)
	SELECT 
		HIF_N_PRO_N_CODIGO,
		HIF_N_IWF_N_CODIGO,
		HIF_N_USR_EXECUTOR,
		HIF_N_ETA_N_CODIGO,
		HIF_N_ETI_N_CODIGO,
		HIF_C_STATUS,
		HIF_D_GRAVACAO,
		HIF_C_DESCRICAO,
		HIF_N_ACAOID,
		HIF_N_TIPOACAO,
		HIF_N_EVE_N_ID,
		HIF_N_ATIVO,
		HIF_ISP_N_ID
	FROM WHIF_HISTORICO_FINALIZADO
	WHERE
		HIF_N_LOGLEVEL = 6 AND
		HIF_N_CODIGO NOT IN (
			SELECT MAX(HIF_N_CODIGO)
			FROM WHIF_HISTORICO_FINALIZADO 
			WHERE 
				HIF_N_LOGLEVEL = 6 AND 
				(HIF_N_EVE_N_ID = 0 OR HIF_N_EVE_N_ID NOT IN (SELECT HIF_N_EVE_N_ID FROM WHIF_HISTORICO_FINALIZADO WHERE HIF_N_LOGLEVEL <> 6))
			GROUP BY 
				HIF_N_IWF_N_CODIGO,HIF_ISP_N_ID, HIF_N_EVE_N_ID, HIF_N_TIPOACAO,HIF_N_ACAOID
		)

	DELETE FROM WHIF_HISTORICO_FINALIZADO
	WHERE
		HIF_N_LOGLEVEL = 6 AND
		HIF_N_CODIGO NOT IN (
			SELECT MAX(HIF_N_CODIGO)
			FROM WHIF_HISTORICO_FINALIZADO 
			WHERE 
				HIF_N_LOGLEVEL = 6 AND 
				(HIF_N_EVE_N_ID = 0 OR HIF_N_EVE_N_ID NOT IN (SELECT HIF_N_EVE_N_ID FROM WHIF_HISTORICO_FINALIZADO WHERE HIF_N_LOGLEVEL <> 6))
			GROUP BY 
				HIF_N_IWF_N_CODIGO,HIF_ISP_N_ID, HIF_N_EVE_N_ID, HIF_N_TIPOACAO,HIF_N_ACAOID
		)
	COMMIT TRAN
END


--REMOVE O ANTIGO MODULO DE CAIXA DE ENTRADA SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WPCTT_CONTENT WHERE CTT_N_MOD_N_ID IN (SELECT MOD_N_ID FROM WPMOD_MODULE WHERE MOD_C_GUID = 'F7A8D3DC-0591-45D6-94B5-EF07497EF90B'))
BEGIN
	DELETE FROM WPMOD_MODULE WHERE MOD_C_GUID = 'F7A8D3DC-0591-45D6-94B5-EF07497EF90B'
END

--REMOVE O ANTIGO MODULO DE MEUS ITENS SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WPCTT_CONTENT WHERE CTT_N_MOD_N_ID IN (SELECT MOD_N_ID FROM WPMOD_MODULE WHERE MOD_C_GUID = '9690E4D1-724B-49E8-AA30-7A42CB1C64ED'))
BEGIN
	DELETE FROM WPMOD_MODULE WHERE MOD_C_GUID = '9690E4D1-724B-49E8-AA30-7A42CB1C64ED'
END

--REMOVE O ANTIGO MODULO DE OBSERVADORES SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WPCTT_CONTENT WHERE CTT_N_MOD_N_ID IN (SELECT MOD_N_ID FROM WPMOD_MODULE WHERE MOD_C_GUID = '9D8E1B38-E45B-4C21-B565-1B9A1B010D5B'))
BEGIN
	DELETE FROM WPMOD_MODULE WHERE MOD_C_GUID = '9D8E1B38-E45B-4C21-B565-1B9A1B010D5B'
END

--REMOVE O ANTIGO MODULO DE APROVACAO POR EMAIL SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WPCTT_CONTENT WHERE CTT_N_MOD_N_ID IN (SELECT MOD_N_ID FROM WPMOD_MODULE WHERE MOD_C_GUID = '2E1057DE-5960-400E-B946-6F8371C83413'))
BEGIN
	DELETE FROM WPMOD_MODULE WHERE MOD_C_GUID = '2E1057DE-5960-400E-B946-6F8371C83413'
END


--JANELAS DE CONFIGURACAO DEFAULT
IF NOT EXISTS(SELECT 1 FROM WZCF_ZURI_CONFIGURATION WHERE ZCF_C_CONFIGITEM = 'ZURI.POPUP' AND ZCF_N_CONFIGID = 1)
INSERT INTO WZCF_ZURI_CONFIGURATION (ZCF_C_CONFIGITEM,ZCF_N_CONFIGID,ATC_C_CONFIGURATION,ZCF_C_CONFIGALIAS)
VALUES ('ZURI.POPUP',1,'<AREADETRABALHO UtilizarTabs="true" AbrirMaximizado="true" IsDefault="true" SecoesItem="HOME;DETAILS;HISTORY;ATTACH;MSGS;GPS;" PopUpWidth="0" PopUpHeight="0" PopUpLeft="0" PopUpTop="0" />','Padrão')

IF NOT EXISTS(SELECT 1 FROM WZCF_ZURI_CONFIGURATION WHERE ZCF_C_CONFIGITEM = 'ZURI.POPUP' AND ZCF_N_CONFIGID = 2)
INSERT INTO WZCF_ZURI_CONFIGURATION (ZCF_C_CONFIGITEM,ZCF_N_CONFIGID,ATC_C_CONFIGURATION,ZCF_C_CONFIGALIAS)
VALUES ('ZURI.POPUP',2,'<AREADETRABALHO UtilizarTabs="true" AbrirMaximizado="true" IsDefault="false" SecoesItem="HOME;" PopUpWidth="0" PopUpHeight="0" PopUpLeft="0" PopUpTop="0" />','Criação')

IF NOT EXISTS(SELECT 1 FROM WZCF_ZURI_CONFIGURATION WHERE ZCF_C_CONFIGITEM = 'ZURI.POPUP' AND ZCF_N_CONFIGID = 3)
INSERT INTO WZCF_ZURI_CONFIGURATION (ZCF_C_CONFIGITEM,ZCF_N_CONFIGID,ATC_C_CONFIGURATION,ZCF_C_CONFIGALIAS)
VALUES ('ZURI.POPUP',3,'<AREADETRABALHO UtilizarTabs="true" AbrirMaximizado="true" IsDefault="false" SecoesItem="HOME;DETAILS;HISTORY;ATTACH;GPS;" PopUpWidth="0" PopUpHeight="0" PopUpLeft="0" PopUpTop="0" />','Consulta')

--ATUALIZACAO DOS VALORES DE SLA
UPDATE WIPR_ITEM_PROCESSO SET IPR_N_CURRENTSLA = (SELECT TOP 1 ETS_N_CODIGO FROM WETS_ETAPA_SLA ORDER BY ETS_N_ORDEM) WHERE IPR_N_CURRENTSLA = 0 OR IPR_N_CURRENTSLA IS NULL
SET NOCOUNT OFF
GO

SET NOCOUNT ON
--AJUSTE NOS EVENTOS DE FINAL DE ETAPA (TIPO ACAO = 22 AO INVES DE 2)
UPDATE WHIS_HISTORICO_ITEM SET HIS_N_TIPOACAO = 22 WHERE HIS_C_DESCRICAO LIKE 'Finalizou a etapa %' AND HIS_N_TIPOACAO = 2
UPDATE WHIF_HISTORICO_FINALIZADO SET HIF_N_TIPOACAO = 22 WHERE HIF_C_DESCRICAO LIKE 'Finalizou a etapa %' AND HIF_N_TIPOACAO = 2

--O MODULO DE MENSAGEM PASSA A APARECER NO PRAZO
UPDATE WMOD_MODULO SET MOD_N_USOPRAZO = 1 WHERE MOD_C_ITEMID = '368BE043-E052-4E8E-A6A8-1B242960EEC8'
SET NOCOUNT OFF
GO


--#####################################################################################################################
--***** ACERTA OS IDENTIFICADORES DE SUBPROCESSO
--#####################################################################################################################
SET NOCOUNT ON
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	begin tran
	--PARA GARANTIR AS INTEGRIDADES DOS ID´S PRIMEIRO INSERE TUDO NA TABELA DE ATIVOS
	--INSERE OS ITENS INATIVOS NA TABELA DE SUBPROCESSO	(INSERE PARENTID = -1 PARA DIFERENCIAR E PODER MOVER DEPOIS)
	DECLARE @UPDQUERY VARCHAR(2000)
	SET @UPDQUERY = '
	INSERT INTO WISP_ITEM_SUBPROCESS (
		ISP_N_IPR_N_CODIGO,
		ISP_N_PARENTISP_ID,
		ISP_ATV_N_CODIGO,
		ISP_C_IDENTIFIER,
		ISP_C_TITLE,
		ISP_C_METADATA)
	SELECT DISTINCT 
		IPR_N_CODIGO,
		-1, 
		0, 
		HIF_C_IDENTIFICADOR, 
		'''',
		''''
	FROM 
		WHIF_HISTORICO_FINALIZADO 
		INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO = HIF_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIF_N_PRO_N_CODIGO
	WHERE 
		(NOT HIF_C_IDENTIFICADOR IS NULL) AND HIF_C_IDENTIFICADOR <> '''' AND
		HIF_N_TIPOACAO = 3 AND
		HIF_N_ACAOID IN (SELECT ATV_N_CODIGO FROM WATV_ATIVIDADE WHERE ATV_N_MOD_N_CODIGO IN 
		(SELECT MOD_N_CODIGO FROM WMOD_MODULO WHERE MOD_C_ITEMID = ''E673CA71-CA02-48F4-9FAF-701B880E39E2''))
	'
	EXEC (@UPDQUERY)

	--INSERE OS ITENS ATIVOS NA TABELA DE SUBPROCESSO
	SET @UPDQUERY = '
	INSERT INTO WISP_ITEM_SUBPROCESS(
		ISP_N_IPR_N_CODIGO,
		ISP_N_PARENTISP_ID,
		ISP_ATV_N_CODIGO,
		ISP_C_IDENTIFIER,
		ISP_C_TITLE,
		ISP_C_METADATA)
	SELECT DISTINCT 
		IPR_N_CODIGO,
		0, 
		0, 
		HIS_C_IDENTIFICADOR, 
		ETI_C_SUBTITLE,
		''''
	FROM 
		WHIS_HISTORICO_ITEM 
		INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_IWF_N_CODIGO = HIS_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIS_N_PRO_N_CODIGO
		LEFT JOIN WETI_ETAPA_ITEM ON ETI_N_CODIGO = HIS_N_ETI_N_CODIGO
	WHERE 
		(NOT HIS_C_IDENTIFICADOR IS NULL) AND HIS_C_IDENTIFICADOR <> '''' AND
		HIS_N_TIPOACAO = 3 AND
		HIS_N_ACAOID IN (SELECT ATV_N_CODIGO FROM WATV_ATIVIDADE WHERE ATV_N_MOD_N_CODIGO IN 
		(SELECT MOD_N_CODIGO FROM WMOD_MODULO WHERE MOD_C_ITEMID = ''E673CA71-CA02-48F4-9FAF-701B880E39E2'')) 
	'
	EXEC (@UPDQUERY)
	
	SET @UPDQUERY = '
	UPDATE 
		WETI_ETAPA_ITEM
	SET 
		ETI_C_SUBTITLE = ETI_C_IDENTIFICADOR
	WHERE 
		(NOT ETI_C_IDENTIFICADOR IS NULL) AND ETI_C_IDENTIFICADOR <> '''' AND
		(ETI_C_SUBTITLE IS NULL OR ETI_C_SUBTITLE = '''')
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WETI_ETAPA_ITEM
	SET 
		ETI_ISP_N_ID = ISP_N_ID
	FROM WETI_ETAPA_ITEM
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = ETI_N_IPR_N_CODIGO AND ISP_C_IDENTIFIER = ETI_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WIEX_ITEM_EXECUCAO
	SET 
		IEX_ISP_N_ID = ISP_N_ID
	FROM WIEX_ITEM_EXECUCAO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IEX_N_IPR_N_CODIGO AND ISP_C_IDENTIFIER = IEX_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WITA_ITEM_ACESSO
	SET 
		ITA_ISP_N_ID = ISP_N_ID
	FROM WITA_ITEM_ACESSO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = ITA_N_IPR_N_CODIGO AND ISP_C_IDENTIFIER = ITA_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WITR_ITEM_RESTRICAO
	SET 
		ITR_ISP_N_ID = ISP_N_ID
	FROM WITR_ITEM_RESTRICAO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = ITR_N_IPR_N_CODIGO AND ISP_C_IDENTIFIER = ITR_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WITX_ITEM_EXCLUSAO
	SET 
		ITX_ISP_N_ID = ISP_N_ID
	FROM WITX_ITEM_EXCLUSAO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = ITX_N_IPR_N_CODIGO AND ISP_C_IDENTIFIER = ITX_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WANX_ANEXO_ITEM
	SET 
		ANX_ISP_N_ID = ISP_N_ID
	FROM WANX_ANEXO_ITEM
	INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_IWF_N_CODIGO = ANX_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = ANX_N_PRO_N_CODIGO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO AND ISP_C_IDENTIFIER = ANX_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WANF_ANEXO_FINALIZADO
	SET 
		ANF_ISP_N_ID = ISP_N_ID
	FROM WANF_ANEXO_FINALIZADO
	INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO = ANF_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = ANF_N_PRO_N_CODIGO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO AND ISP_C_IDENTIFIER = ANF_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WHIS_HISTORICO_ITEM
	SET 
		HIS_ISP_N_ID = ISP_N_ID
	FROM WHIS_HISTORICO_ITEM
	INNER JOIN WIPR_ITEM_PROCESSO ON IPR_N_IWF_N_CODIGO = HIS_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIS_N_PRO_N_CODIGO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO AND ISP_C_IDENTIFIER = HIS_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WHIF_HISTORICO_FINALIZADO
	SET 
		HIF_ISP_N_ID = ISP_N_ID
	FROM WHIF_HISTORICO_FINALIZADO
	INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO = HIF_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIF_N_PRO_N_CODIGO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO AND ISP_C_IDENTIFIER = HIF_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE 
		WHIF_HISTORICO_ARQUIVADO
	SET 
		HIF_ISP_N_ID = ISP_N_ID
	FROM WHIF_HISTORICO_ARQUIVADO
	INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON IPR_N_IWF_N_CODIGO = HIF_N_IWF_N_CODIGO AND IPR_N_PRO_N_CODIGO = HIF_N_PRO_N_CODIGO
	INNER JOIN WISP_ITEM_SUBPROCESS ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO AND ISP_C_IDENTIFIER = HIF_C_IDENTIFICADOR
	'
	EXEC (@UPDQUERY)

	--ATUALIZA OS CAMPOS DO SUBPROCESSO DE ACORDO COM ETAPAITEM / ANEXO ITEM E ANEXO FINALIZADO
	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET	
		ISP_C_TITLE = ETI_C_SUBTITLE
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID
	WHERE (NOT ETI_C_SUBTITLE IS NULL) AND  ETI_C_SUBTITLE <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET	
		ISP_C_TITLE = ANX_C_SUBTITULO
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WANX_ANEXO_ITEM ON ANX_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ANX_C_SUBTITULO IS NULL) AND  ANX_C_SUBTITULO <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET	
		ISP_C_TITLE = ANF_C_SUBTITULO
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WANF_ANEXO_FINALIZADO ON ANF_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ANF_C_SUBTITULO IS NULL) AND  ANF_C_SUBTITULO <> ''''	
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET	
		ISP_C_TITLE = HIS_C_SUBTITULO
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WHIS_HISTORICO_ITEM ON HIS_ISP_N_ID = ISP_N_ID 
	WHERE (NOT HIS_C_SUBTITULO IS NULL) AND  HIS_C_SUBTITULO <> ''''	
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET	
		ISP_C_TITLE = HIF_C_SUBTITULO
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WHIF_HISTORICO_FINALIZADO ON HIF_ISP_N_ID = ISP_N_ID 
	WHERE (NOT HIF_C_SUBTITULO IS NULL) AND  HIF_C_SUBTITULO <> ''''	
	'
	EXEC (@UPDQUERY)

	--ACERTA OS ANTECESSORES COMO FALLBACK
	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ''<Antecessors>'' + ETI_C_ANTECESSORES + ''</Antecessors>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_C_ANTECESSORES IS NULL) AND ETI_C_ANTECESSORES <> ''''
	'
	EXEC (@UPDQUERY)

	--ACERTA OS PARAMETROS TEMPORARIOS
	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<ItemName>'' + ETI_IWF_C_NOME + ''</ItemName>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_NOME IS NULL) AND ETI_IWF_C_NOME <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<ItemStatus>'' + ETI_IWF_C_STATUS + ''</ItemStatus>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_STATUS IS NULL) AND ETI_IWF_C_STATUS <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<Param1>'' + ETI_IWF_C_PARAM1 + ''</Param1>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_PARAM1 IS NULL) AND ETI_IWF_C_PARAM1 <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<Param2>'' + ETI_IWF_C_PARAM2 + ''</Param2>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_PARAM2 IS NULL) AND ETI_IWF_C_PARAM2 <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<Param3>'' + ETI_IWF_C_PARAM3 + ''</Param3>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_PARAM3 IS NULL) AND ETI_IWF_C_PARAM3 <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<Param4>'' + ETI_IWF_C_PARAM4 + ''</Param4>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_PARAM4 IS NULL) AND ETI_IWF_C_PARAM4 <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET ISP_C_METADATA = ISP_C_METADATA + ''<Param5>'' + ETI_IWF_C_PARAM5 + ''</Param5>''
	FROM WISP_ITEM_SUBPROCESS
	INNER JOIN WETI_ETAPA_ITEM ON ETI_ISP_N_ID = ISP_N_ID 
	WHERE (NOT ETI_IWF_C_PARAM5 IS NULL) AND ETI_IWF_C_PARAM5 <> ''''
	'
	EXEC (@UPDQUERY)

	--COLOCA OS DELIMITADORES DO XML DE METADADOS
	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS
	SET
		ISP_C_METADATA = ''<SPMETAINFO>'' + ISP_C_METADATA + ''</SPMETAINFO>''
	FROM WISP_ITEM_SUBPROCESS
	WHERE (NOT ISP_C_METADATA IS NULL) AND ISP_C_METADATA <> ''''
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	UPDATE WISP_ITEM_SUBPROCESS 
		SET ISP_C_TITLE = ISP_C_IDENTIFIER
	WHERE 
		ISP_C_TITLE IS NULL OR ISP_C_TITLE = ''''
	'
	EXEC (@UPDQUERY)

	--MOVE OS ITENS FINALIZADOS PARA A TABELA CORRETA
	SET @UPDQUERY = '
	INSERT INTO WISP_ITEM_SUBPROCESS_FINALIZADO (
		ISP_N_ID,
		ISP_N_IPR_N_CODIGO,
		ISP_N_PARENTISP_ID,
		ISP_ATV_N_CODIGO,
		ISP_C_IDENTIFIER,
		ISP_C_TITLE,
		ISP_C_METADATA, 
		ISP_NOD_C_SCOPE)
	SELECT
		ISP_N_ID,
		ISP_N_IPR_N_CODIGO,
		0,
		ISP_ATV_N_CODIGO,
		ISP_C_IDENTIFIER,
		ISP_C_TITLE,
		ISP_C_METADATA, 
		ISP_NOD_C_SCOPE
	FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_PARENTISP_ID = -1
	'
	EXEC (@UPDQUERY)

	SET @UPDQUERY = '
	DELETE FROM WISP_ITEM_SUBPROCESS WHERE ISP_N_PARENTISP_ID = -1
	'
	EXEC (@UPDQUERY)


	SET @UPDQUERY = 'UPDATE WETI_ETAPA_ITEM SET ETI_C_IDENTIFICADOR = '''''
	EXEC (@UPDQUERY)

	-- SO DEPOIS DE MOVER OS CAMPOS RECRIA A CONSTRAINT
	ALTER TABLE WISP_ITEM_SUBPROCESS ADD
	CONSTRAINT FK_SUBPROCESS_ITEM FOREIGN KEY(ISP_N_IPR_N_CODIGO)
			REFERENCES WIPR_ITEM_PROCESSO (IPR_N_CODIGO) ON DELETE CASCADE
	commit tran
END
SET NOCOUNT OFF
GO

--ELIMINA AS COLUNAS DE SUBPROCESSO QUE NAO SAO MAIS USADAS 
IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'ETI_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WETI_ETAPA_ITEM'))
BEGIN
	DECLARE @PREPAREOK INT
	SET @PREPAREOK = 0
	DECLARE @EXECQUERY nvarchar(1000)
	SET @EXECQUERY = 'SELECT @PREPAREOK = COUNT(1) FROM WETI_ETAPA_ITEM WHERE ETI_C_IDENTIFICADOR <> '''''
	EXEC sp_executesql @EXECQUERY, N'@PREPAREOK int out', @PREPAREOK out
	IF @PREPAREOK = 0 
	BEGIN
		begin tran
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_C_IDENTIFICADOR
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_C_ANTECESSORES
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_C_SUBTITLE
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_NOME
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_STATUS
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_PARAM1
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_PARAM2
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_PARAM3
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_PARAM4
		ALTER TABLE WETI_ETAPA_ITEM DROP COLUMN ETI_IWF_C_PARAM5
		ALTER TABLE WIEX_ITEM_EXECUCAO DROP COLUMN IEX_C_IDENTIFICADOR
		ALTER TABLE WANX_ANEXO_ITEM DROP COLUMN ANX_C_IDENTIFICADOR
		ALTER TABLE WANX_ANEXO_ITEM DROP COLUMN ANX_C_SUBTITULO
		ALTER TABLE WANF_ANEXO_FINALIZADO DROP COLUMN ANF_C_IDENTIFICADOR
		ALTER TABLE WANF_ANEXO_FINALIZADO DROP COLUMN ANF_C_SUBTITULO
		ALTER TABLE WHIS_HISTORICO_ITEM DROP COLUMN HIS_C_IDENTIFICADOR
		ALTER TABLE WHIS_HISTORICO_ITEM DROP COLUMN HIS_C_SUBTITULO 
		ALTER TABLE WHIF_HISTORICO_FINALIZADO DROP COLUMN HIF_C_IDENTIFICADOR
		ALTER TABLE WHIF_HISTORICO_FINALIZADO DROP COLUMN HIF_C_SUBTITULO
		IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'HIF_C_IDENTIFICADOR' AND OBJECT_ID = OBJECT_ID('WHIF_HISTORICO_ARQUIVADO')) ALTER TABLE WHIF_HISTORICO_ARQUIVADO DROP COLUMN HIF_C_IDENTIFICADOR
		ALTER TABLE WITA_ITEM_ACESSO DROP COLUMN ITA_C_IDENTIFICADOR
		ALTER TABLE WITR_ITEM_RESTRICAO DROP COLUMN ITR_C_IDENTIFICADOR
		ALTER TABLE WITX_ITEM_EXCLUSAO DROP COLUMN ITX_C_IDENTIFICADOR
		commit tran
	END
END

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'EVP_C_IDENTIFIER' AND OBJECT_ID = OBJECT_ID('WEVP_EVENTO_PENDENTE'))
BEGIN
	ALTER TABLE WEVP_EVENTO_PENDENTE DROP COLUMN EVP_C_CALLERID
	ALTER TABLE WEVP_EVENTO_PENDENTE DROP COLUMN EVP_C_IDENTIFIER
	ALTER TABLE WEVP_EVENTO_PENDENTE DROP COLUMN EVP_C_CALLERIDENTIFIER
END
GO

IF EXISTS (SELECT 1 FROM SYS.COLUMNS WHERE NAME = 'MVL_C_ACTIVITYID' AND OBJECT_ID = OBJECT_ID('WMVL_MARKER_VALUES'))
BEGIN
	ALTER TABLE WMVL_MARKER_VALUES DROP COLUMN MVL_C_ACTIVITYID
	DELETE FROM WMVL_MARKER_VALUES
END
GO

--##################################################################################################
IF OBJECT_ID('SubprocessStatus') IS NULL
BEGIN
	EXEC sp_executesql N'CREATE VIEW SubprocessStatus AS SELECT 1 AS A'
END
GO

/*
VIEW PARA LISTAR OS SUBPROCESSOS EXISTENTES COM UM FLAG INDICANDO SE FOI FINALIZADO.
*/
ALTER VIEW SubprocessStatus
AS 
	SELECT DISTINCT ISP_N_ID, ISP_N_IPR_N_CODIGO, case when isnull(ISP_C_TITLE, '') = '' then ISP_C_IDENTIFIER else ISP_C_TITLE end ISP_C_TITLE, ISP_NOD_C_SCOPE, CAST(ISNULL(HIS_ISP_N_ID, 0) AS bit) ISP_B_IS_FINISHED
	FROM WISP_ITEM_SUBPROCESS 
	INNER JOIN WIPR_ITEM_PROCESSO ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO
	INNER JOIN WIWF_ITEM_WORKFLOW ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO
	LEFT JOIN WNOD_NODE ON NOD_PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND NOD_C_SCOPE = ISP_NOD_C_SCOPE AND NOD_MOD_C_ITEMID = 'ceb0220e-d344-46be-bbd2-1a982751ebba' 
	LEFT JOIN WNOP_NODEPORT ON NOP_NOD_N_ID = NOD_N_ID
	LEFT JOIN WNOL_NODELINK ON NOL_DESTINATION_NOP_N_ID = NOP_N_ID
	LEFT JOIN WHIS_HISTORICO_ITEM ON HIS_ISP_N_ID = ISP_N_ID AND HIS_N_EVE_N_ID = NOL_EVE_N_CODIGO
	UNION ALL 
	SELECT DISTINCT ISP_N_ID, ISP_N_IPR_N_CODIGO, case when isnull(ISP_C_TITLE, '') = '' then ISP_C_IDENTIFIER else ISP_C_TITLE end ISP_C_TITLE, ISP_NOD_C_SCOPE, CAST(ISNULL(HIF_ISP_N_ID, 0) AS bit) ISP_B_IS_FINISHED
	FROM WISP_ITEM_SUBPROCESS_FINALIZADO 
	INNER JOIN WIPR_ITEM_PROCESSO_FINALIZADO ON ISP_N_IPR_N_CODIGO = IPR_N_CODIGO
	INNER JOIN WIWF_ITEM_WORKFLOW_FINALIZADO ON IPR_N_IWF_N_CODIGO = IWF_N_CODIGO
	LEFT JOIN WNOD_NODE ON NOD_PRO_N_CODIGO = IPR_N_PRO_N_CODIGO AND NOD_C_SCOPE = ISP_NOD_C_SCOPE AND NOD_MOD_C_ITEMID = 'ceb0220e-d344-46be-bbd2-1a982751ebba' 
	LEFT JOIN WNOP_NODEPORT ON NOP_NOD_N_ID = NOD_N_ID
	LEFT JOIN WNOL_NODELINK ON NOL_DESTINATION_NOP_N_ID = NOP_N_ID
	LEFT JOIN WHIF_HISTORICO_FINALIZADO ON HIf_ISP_N_ID = ISP_N_ID AND HIf_N_EVE_N_ID = NOL_EVE_N_CODIGO
GO


--##################################################################################################
-- LIMPEZA DOS METADOS UTILIZADOS NOS RELATORIOS PARA CONTER AS INFORMACOES DE SUBPROCESSOS
IF NOT EXISTS (SELECT 1 FROM WIWF_ITEM_WORKFLOW WHERE IWF_C_METADATA LIKE '% AttSPId=%')
BEGIN
	SET NOCOUNT ON
	UPDATE WIWF_ITEM_WORKFLOW SET IWF_C_METADATA = NULL
	UPDATE WIWF_ITEM_WORKFLOW_FINALIZADO SET IWF_C_METADATA = NULL
	SET NOCOUNT OFF
END
--##################################################################################################

--##################################################################################################
-- LIMPEZA DAS ACOES PENDENTES QUE FICARAM SEM PRAZO POIS O MESMO FOI EXCLUIDO E NAO TINHA CASCADE
SET NOCOUNT ON
DELETE FROM WACI_ACAO_ITEM WHERE ACI_N_PRZ_N_ID <> 0 AND ACI_N_PRZ_N_ID NOT IN (SELECT PRZ_N_CODIGO FROM WPRZ_PRAZO)
SET NOCOUNT OFF
--##################################################################################################

--##################################################################################################
-- AJUSTE DE CARACTERES INVALIDOS NA TABELA DE ITEM CACHE
IF EXISTS(SELECT 1 FROM WIVC_ITEMVALUECACHE WHERE IVC_C_FIELDNAME LIKE '[[]%')
BEGIN
UPDATE WIVC_ITEMVALUECACHE SET IVC_C_FIELDNAME = REPLACE(REPLACE(IVC_C_FIELDNAME,'[','|'),']','|')
DELETE FROM WMUX_MARKER_UPDATE_EXECUTION
END
--##################################################################################################

--### 21 NINKI ZURI ##################################################################################

IF NOT EXISTS (SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'E3DFBF27-FD95-48E1-869B-5221974E70A8')
	INSERT INTO WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO)
	VALUES('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'E3DFBF27-FD95-48E1-869B-5221974E70A8', 'Anexa SubFormulario', 'WFFormChildModule.ascx', 'modules/WFFormChild.aspx', 330, 410, 0, '', 0, '', 'attachsubform.png', 'Complementares', 1, 2, 0, 'WebFoundations.WFForms.WFWorkflow.dll|WebFoundations.WFForms.WFWorkflow.WFFormChildModule', 1, 0)
GO

--REMOVE O MODULO COMPARACAO DE FORMULARIO SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = 'FCE3D2BF-B698-42A7-AEE6-F2CB7B540379')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'FCE3D2BF-B698-42A7-AEE6-F2CB7B540379'
END

--REMOVE O MODULO HISTORICO DE FORMULARIO SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '09D0F038-CD61-4594-AF2F-28F9CE830CE8')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '09D0F038-CD61-4594-AF2F-28F9CE830CE8'
END

IF NOT EXISTS (SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'CCD110AE-A4B9-4974-B4EC-F446A296BE28')
	INSERT INTO WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO)
	VALUES('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', 'CCD110AE-A4B9-4974-B4EC-F446A296BE28', 'Preenche formulário', 'FormFiller.ascx', 'modules/FormFiller.aspx', 770, 1100, 0, '', 0, '', 'formfiller.png', 'content', 1, 2, 0, 'WebFoundations.WFForms.WFWorkflow.dll|WebFoundations.WFForms.WFWorkflow.FormFiller1', 1, 1)
GO

IF NOT EXISTS (SELECT 1 FROM WMOD_MODULO WHERE MOD_C_ITEMID = '3CB57AE4-1FF2-458C-BE50-D53F720FB9D3')
	INSERT INTO WMOD_MODULO (MOD_C_OWNERID, MOD_C_ITEMID, MOD_C_TITULO, MOD_C_ASCX, MOD_C_ASPXADM, MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR, MOD_C_GUIDANTECESSOR, MOD_C_ICONE, MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA, MOD_N_TIPO_ENTRADA, MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO, MOD_N_USOPRAZO)
	VALUES('39095AD1-18AF-4948-8F1F-12D39B7C1F5B', '3CB57AE4-1FF2-458C-BE50-D53F720FB9D3', 'Anexa formulário', 'AttachForm.ascx', 'modules/Attachform.aspx', 300, 600, 0, '', 0, '', 'attachform.png', 'content', 1, 2, 0, 'WebFoundations.WFForms.WFWorkflow.dll|WebFoundations.WFForms.WFWorkflow.AttachForm', 1, 1)
GO
if not exists (select 1 from WMOD_MODULO where MOD_C_ITEMID = '1B34D0FA-D951-425A-97F7-7F1C6652794D')
begin
	insert WMOD_MODULO 
		(MOD_C_OWNERID, MOD_C_ITEMID,MOD_C_TITULO,	MOD_C_ASCX,	MOD_C_ASPXADM,
		 MOD_N_POPADM_HEIGHT, MOD_N_POPADM_WIDTH, MOD_N_TIPOSUCESSOR, MOD_C_GUIDSUCESSOR, MOD_N_TIPOANTECESSOR,	MOD_C_GUIDANTECESSOR, MOD_C_ICONE,
		 MOD_C_CATEGORIA, MOD_N_TIPO_SAIDA,	MOD_N_TIPO_ENTRADA,	MOD_N_INTERATIVO, MOD_C_ASSEMBLYINFO, MOD_N_USODESENHO,	MOD_N_USOPRAZO,	MOD_N_ORDER)
	values ('1B34D0FA-D951-425A-97F7-7F1C6652794D', '1B34D0FA-D951-425A-97F7-7F1C6652794D', 'Formulário Mobile', 'NinkiFormMobile.ascx', 'modules/NinkiFormMobile.aspx', 
	         400, 600, 0, '', 0, '', 'ninkiformmobile.png', 'content', 3,2,1,'WF.Ninki.Zuri.dll|WF.Ninki.Zuri.NinkiFormMobile',1,0,2)
end
else
begin
	update WMOD_MODULO
	 set MOD_C_ASCX= 'NinkiFormMobile.ascx', MOD_C_ASPXADM='modules/NinkiFormMobile.aspx', 
	 MOD_N_POPADM_HEIGHT=400 , MOD_N_POPADM_WIDTH=600,
	 MOD_C_ICONE = 'ninkiformmobile.png',
	 MOD_C_ASSEMBLYINFO = 'WF.Ninki.Zuri.dll|WF.Ninki.Zuri.NinkiFormMobile',
	 MOD_N_TIPO_SAIDA = 3
	 WHERE
	 MOD_C_ITEMID = '1B34D0FA-D951-425A-97F7-7F1C6652794D'
end

update WMOD_MODULO set MOD_N_USODESENHO = 0 where MOD_C_ITEMID IN ('B4AA1704-C8B5-46AE-8E70-CE00253EE023','B407BA38-9DCB-44F9-B8D1-F227C76C0097')

--REMOVE O MODULO FORM OFFLINE SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = 'B73CA527-D874-422C-B021-AD332D1C5D1E')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'B73CA527-D874-422C-B021-AD332D1C5D1E'
END

--REMOVE O MODULO FORM OFFLINE SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = 'A7933258-C5B6-4172-B3D8-4F841A892A26')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = 'A7933258-C5B6-4172-B3D8-4F841A892A26'
END

SET NOCOUNT ON
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = '36D24F1D-15DE-47F8-9300-F85057D28737' --Inicio
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'EA6FDB27-E80F-47B0-BE22-C9D8036D8764' --Fim
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 680,  MOD_N_POPADM_WIDTH = 885 WHERE MOD_C_ITEMID = 'CA4F303D-F89E-4B92-9D4B-D8071358C57F' --Etapa
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 460,  MOD_N_POPADM_WIDTH = 460 WHERE MOD_C_ITEMID = 'BBBC9B8A-85BE-4046-AF9B-E5FEAE6912C3' --Decisão
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 750,  MOD_N_POPADM_WIDTH = 950, MOD_C_TITULO='Formulario Web', MOD_C_ASSEMBLYINFO='WebFoundations.WFForms.WFWorkflow.dll|WebFoundations.WFForms.WFWorkflow.WFFormsModule' WHERE MOD_C_ITEMID = '3AAA48DC-9426-4270-9B3B-407C8C094769' --Formulario Web
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 750,  MOD_N_POPADM_WIDTH = 950, MOD_C_TITULO='E-mail', MOD_C_ASSEMBLYINFO = ' WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Email1' WHERE MOD_C_ITEMID = '5DA76359-A239-467B-8B94-EDBF05A542B5' --E-mail
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 5,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 670,  MOD_N_POPADM_WIDTH = 950 WHERE MOD_C_ITEMID = '368BE043-E052-4E8E-A6A8-1B242960EEC8' --Mensagem
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 6,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 770,  MOD_N_POPADM_WIDTH = 950 WHERE MOD_C_ITEMID = '8380B8F6-7B11-42A7-842E-1B40A261394E' --Arquivo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 7,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 750,  MOD_N_POPADM_WIDTH = 950 WHERE MOD_C_ITEMID = 'C4698902-BFFE-45D2-8E0C-F18DC716F2DB' --Regra
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 8,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 565, MOD_C_TITULO='Informações do item' WHERE MOD_C_ITEMID = 'C54FD91E-6D86-488E-B448-F2BEED66537D' --Item Info
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 9,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320,  MOD_C_ICONE = 'origin.png' WHERE MOD_C_ITEMID = '770201C8-9E53-43DC-815D-FD1488B80075' --Atalho Origem
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 10,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320, MOD_C_ICONE = 'destination.png' WHERE MOD_C_ITEMID = '37B6BBD5-491B-4BC1-9A8B-E8769A62BFDA' --Atalho Destino
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = '041BD21B-17A1-4DCF-B49B-A7DC392AA1C0' --Adiciona Grupo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'ACFDE8CE-9386-4C0D-A6B5-E6E8FA7EC3C7' --Atribui Usuario
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'EA548DB4-4A99-469A-B932-460ADB345D18' --Delega Grupo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'B190949D-2519-4A59-BE72-3DD0F1033810' --Desviar
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'B4AA1704-C8B5-46AE-8E70-CE00253EE023' --Senha na decisao
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'B407BA38-9DCB-44F9-B8D1-F227C76C0097' --Atribui Etapa
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 0,  MOD_C_CATEGORIA = 'main', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 800, MOD_N_USODESENHO = 0, MOD_N_USOPRAZO = 0 WHERE MOD_C_ITEMID = 'E5295ABD-EAD3-4DAA-AF1D-E5A564FE04A9' --Comentário

UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640, MOD_N_TIPOSUCESSOR=0, MOD_C_GUIDSUCESSOR='' WHERE MOD_C_ITEMID = 'F8D5E138-6D74-4E51-968C-E5C596EB3690' --Distribuidor
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 400,  MOD_N_POPADM_WIDTH = 640, MOD_C_ASPXADM = 'modules/Condensador.aspx' WHERE MOD_C_ITEMID = 'EC6B2D08-54BC-40D2-B0F8-97151EF8B3CE' --Condensador
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 905 WHERE MOD_C_ITEMID = '1D6755CE-6FDB-423F-9DB4-897662DA1BD5' --Subprocesso
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'E673CA71-CA02-48F4-9FAF-701B880E39E2' --Subprocesso Início
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 5,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'CEB0220E-D344-46BE-BBD2-1A982751EBBA' --Subprocesso Fim
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 6,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 800,  MOD_N_POPADM_WIDTH = 950, MOD_N_USOPRAZO = 1, MOD_C_ASSEMBLYINFO='WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.FluxoExterno1' WHERE MOD_C_ITEMID = 'BCB9E9AF-B503-4B01-A152-0CB32AB670C0' --Fluxo externo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 7,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = '3CBDA469-9A77-4C8E-AB36-C594AC38CD07' --Ponto de entrada
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 8,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = '6EF3ECBC-8CE5-4674-8F56-8B18EED7E8F1' --Ponto de parada
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 9,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640, MOD_C_ASSEMBLYINFO='WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.CancelaEtapa1' WHERE MOD_C_ITEMID = 'E51338A3-AB25-4F4A-9B0E-9E5A231A8233' --Cancela Etapa
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 10,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = '44BE0CE3-FBB1-4744-8AD4-279B0A0A68B2' --Cancela Item
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 11,  MOD_C_CATEGORIA = 'detour', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320, MOD_C_ASPXADM = 'modules/finalizaitem.aspx', MOD_N_TIPO_SAIDA = 0 WHERE MOD_C_ITEMID = 'D7841B5B-FDFE-40B8-9A4B-2B01935236C6' --Finaliza Item

UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 950, MOD_C_TITULO='Importador Excel' WHERE MOD_C_ITEMID = 'BA01C413-589D-44D0-BF47-981A85BBC389' --Importador Excel
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = '1B34D0FA-D951-425A-97F7-7F1C6652794D' --Formulário Mobile
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 910 WHERE MOD_C_ITEMID = 'B73CA527-D874-422C-B021-AD332D1C5D1E' --Formulário Mobile Offline
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = 'A7933258-C5B6-4172-B3D8-4F841A892A26' --Cancela Formulário Offline
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 7,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = 'E3DFBF27-FD95-48E1-869B-5221974E70A8' --Anexa SubFormulario
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 8,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = '3089F45D-6915-4727-903D-84E7F4074D1F' --Anexar Dados
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 9,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 560 WHERE MOD_C_ITEMID = 'F63F5263-4B61-4B89-BE5F-470B6FC788FF' --Move Anexo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 10,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 300,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = '0E91097C-C199-4C77-8727-65B1A6EA8833' --Download Anexo
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 11,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 960, MOD_C_TITULO='Gerador PDF', MOD_C_ICONE='pdfcreator.png', MOD_C_ASSEMBLYINFO = 'WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.PDFCreator1' WHERE MOD_C_ITEMID = 'E7A2F199-EF79-40BD-B5F3-E99D97CC91F2' --Gerador PDF
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 12,  MOD_C_CATEGORIA = 'content', MOD_N_POPADM_HEIGHT = 350,  MOD_N_POPADM_WIDTH = 320 WHERE MOD_C_ITEMID = 'C9D1B328-6F78-4322-8952-287866F17E5B' --Dados externos

UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'filter', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640, MOD_C_TITULO='Filtro Dinâmico' WHERE MOD_C_ITEMID = 'A8A069BF-2730-481A-A85A-FD2F37DF4A1D' --Filtro Dinâmico
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'filter', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640, MOD_C_TITULO='Exclui Usuário' WHERE MOD_C_ITEMID = '80FB6BE8-B619-4118-BB67-54A57D2E4B47' --Exclui Usuario
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'filter', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 480 WHERE MOD_C_ITEMID = '49E8621B-E087-45B7-856B-F00A632B37A4' --Seta Hierarquia
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'filter', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 480, MOD_N_TIPOSUCESSOR=2, MOD_C_GUIDSUCESSOR = 'ca4f303d-f89e-4b92-9d4b-d8071358c57f' WHERE MOD_C_ITEMID = '79CA6394-5884-42FF-9946-87CD68763CA2' --Filtro Hierarquia
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 5,  MOD_C_CATEGORIA = 'filter', MOD_N_POPADM_HEIGHT = 600,  MOD_N_POPADM_WIDTH = 800 WHERE MOD_C_ITEMID = '9F766967-CA15-42D6-8A42-6BE0C89B301F' --Filtro por origem

UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'integration', MOD_N_POPADM_HEIGHT = 680,  MOD_N_POPADM_WIDTH = 1100, MOD_C_TITULO='WebService SOAP', MOD_N_TIPO_SAIDA = 3 WHERE MOD_C_ITEMID = 'E8588324-A835-408D-A85B-41803920A1E2' --WebService
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'integration', MOD_N_POPADM_HEIGHT = 680,  MOD_N_POPADM_WIDTH = 1100, MOD_C_TITULO='WebService REST', MOD_N_TIPO_SAIDA = 3 WHERE MOD_C_ITEMID = 'A89369F6-55F7-4854-B216-79F394BAB6EE' --Rest Api
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'integration', MOD_N_POPADM_HEIGHT = 680,  MOD_N_POPADM_WIDTH = 1100 WHERE MOD_C_ITEMID = '9B13B80D-2A64-4266-B023-9A9C48E88C54' --Procedure
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'integration', MOD_N_POPADM_HEIGHT = 680,  MOD_N_POPADM_WIDTH = 1240 WHERE MOD_C_ITEMID = '9E900659-89D6-4134-9C0A-2DBB53166824' --Code


UPDATE WMOD_MODULO SET  MOD_N_ORDER = 1,  MOD_C_CATEGORIA = 'monitoring', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640, MOD_C_TITULO='Observador' WHERE MOD_C_ITEMID = '47795C45-C5ED-4085-84F7-C455B8E3939D' --Observador
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 2,  MOD_C_CATEGORIA = 'monitoring', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640,  MOD_C_TITULO = 'Protegido', MOD_C_ICONE = 'protegido.png' WHERE MOD_C_ITEMID = '1FB51CBA-5CEF-4264-85B8-8E34107C3D79' --Protegido
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 3,  MOD_C_CATEGORIA = 'monitoring', MOD_N_POPADM_HEIGHT = 460,  MOD_N_POPADM_WIDTH = 910, MOD_C_TITULO='Data limite', MOD_C_ASSEMBLYINFO = 'WebFoundations.WFWorkflow.Modules.UI.dll|WebFoundations.WFWorkflow.Modules.UI.Deadline1' WHERE MOD_C_ITEMID = 'B84B5761-79EC-4773-AF92-9D00E2843DE1' --Data Limite
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 4,  MOD_C_CATEGORIA = 'monitoring', MOD_N_POPADM_HEIGHT = 480,  MOD_N_POPADM_WIDTH = 640 WHERE MOD_C_ITEMID = 'C4BBBE8E-E24A-473E-8B7B-692FDF939F6C' --Item SLA
UPDATE WMOD_MODULO SET  MOD_N_ORDER = 5,  MOD_C_CATEGORIA = 'monitoring', MOD_N_POPADM_HEIGHT = 800,  MOD_N_POPADM_WIDTH = 800 WHERE MOD_C_ITEMID = 'BAD3B0FA-515E-4217-8945-47D9D0E1A2E6' --Reunião

--REMOVE O MODULO DE PUSH DO ZURI
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '72E93007-59FA-4158-B700-C282075C210B')
	BEGIN
		DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '72E93007-59FA-4158-B700-C282075C210B'
	END
ELSE
	BEGIN
		DELETE FROM WATV_ATIVIDADE WHERE ATV_N_CODIGO IN (SELECT ATV_N_CODIGO FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '72E93007-59FA-4158-B700-C282075C210B')
		DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '72E93007-59FA-4158-B700-C282075C210B'
	END

--REMOVE O MODULO CANCELA ITEM SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '44BE0CE3-FBB1-4744-8AD4-279B0A0A68B2')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '44BE0CE3-FBB1-4744-8AD4-279B0A0A68B2'
END
--REMOVE O MODULO FILTRA HIERARQUIA SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '79CA6394-5884-42FF-9946-87CD68763CA2')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '79CA6394-5884-42FF-9946-87CD68763CA2'
END
--REMOVE O MODULO SETA HIERARQUIA SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '49E8621B-E087-45B7-856B-F00A632B37A4')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '49E8621B-E087-45B7-856B-F00A632B37A4'
END
--REMOVE O MODULO FILTRO POR ORIGEM SE NAO ESTIVER EM USO
IF NOT EXISTS(SELECT * FROM WATV_ATIVIDADE INNER JOIN WMOD_MODULO ON MOD_N_CODIGO = ATV_N_MOD_N_CODIGO WHERE MOD_C_ITEMID = '9F766967-CA15-42D6-8A42-6BE0C89B301F')
BEGIN
	DELETE FROM WMOD_MODULO WHERE MOD_C_ITEMID = '9F766967-CA15-42D6-8A42-6BE0C89B301F'
END

--AJUSTE DOS MODULOS USADOS NO DESENHO E NOS PRAZOS
UPDATE WMOD_MODULO SET MOD_N_USODESENHO = 1, MOD_N_USOPRAZO= 0

UPDATE WMOD_MODULO SET MOD_N_USOPRAZO = 1
WHERE MOD_C_ITEMID IN
('9B13B80D-2A64-4266-B023-9A9C48E88C54','5DA76359-A239-467B-8B94-EDBF05A542B5', '041BD21B-17A1-4DCF-B49B-A7DC392AA1C0',
'ACFDE8CE-9386-4C0D-A6B5-E6E8FA7EC3C7', 'EA548DB4-4A99-469A-B932-460ADB345D18', 'B190949D-2519-4A59-BE72-3DD0F1033810',
'D7841B5B-FDFE-40B8-9A4B-2B01935236C6', 'C54FD91E-6D86-488E-B448-F2BEED66537D', 'E8588324-A835-408D-A85B-41803920A1E2',
'BCB9E9AF-B503-4B01-A152-0CB32AB670C0', 'A89369F6-55F7-4854-B216-79F394BAB6EE', '9E900659-89D6-4134-9C0A-2DBB53166824', 
'5E1B5704-9A42-48B6-9DC0-A8625CFEB7B1')

UPDATE WMOD_MODULO SET MOD_N_USODESENHO = 0
WHERE MOD_C_ITEMID IN
('041BD21B-17A1-4DCF-B49B-A7DC392AA1C0', 'ACFDE8CE-9386-4C0D-A6B5-E6E8FA7EC3C7', 'EA548DB4-4A99-469A-B932-460ADB345D18', 
'B190949D-2519-4A59-BE72-3DD0F1033810','B4AA1704-C8B5-46AE-8E70-CE00253EE023','B407BA38-9DCB-44F9-B8D1-F227C76C0097',
'5E1B5704-9A42-48B6-9DC0-A8625CFEB7B1')
--#####################################################################################################################################################################################

--AJUSTES NO MENU ADMIN
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'Desenho de Processos' WHERE MEI_C_URL = '/WFAdmin/WFWorkflow/Processos.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Registration/Modules.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Registration/Containers.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Pages/Publish.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Pages/Scheduler.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Reports/Messages.aspx'
DELETE FROM WFMEI_MENUITEM WHERE MEI_C_URL = '/WFAdmin/Reports/RSSFeeds.aspx'
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'PROCESSOS' WHERE MEI_C_NAME = 'ZURI'
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'FORMULÁRIOS' WHERE MEI_C_NAME = 'FORMS'
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'Configuração de Tema' WHERE MEI_C_URL = '/WFAdmin/Pages/ThemeSettings.aspx'
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'Mensagens de Log' WHERE MEI_C_URL = '/WFAdmin/Reports/Logs.aspx'
UPDATE WFMEI_MENUITEM SET MEI_C_NAME = 'Mensagens de Auditoria' WHERE MEI_C_URL = '/WFAdmin/Reports/LogsAudit.aspx'

SET NOCOUNT OFF
GO

UPDATE SP
SET SP.ISP_NOD_C_SCOPE = NOD_C_SCOPE
FROM WISP_ITEM_SUBPROCESS AS SP
INNER JOIN MWSUB_SUBPROCESS ON ISP_ATV_N_CODIGO = SUB_N_ATV_N_CODIGO
INNER JOIN WNOD_NODE ON SUB_N_CALL_ATIVIDADE = NOD_ATV_N_CODIGO AND NOD_MOD_C_ITEMID = 'E673CA71-CA02-48F4-9FAF-701B880E39E2'
WHERE SP.ISP_NOD_C_SCOPE IS NULL
GO

--Correção na gravação da configuração de anexos de atividade, pois se o alias estiver nulo os valores não são lidos corretamente.
UPDATE WATX_ATIVIDADE_ANEXO SET ATX_C_ALIASANEXO = '' WHERE ATX_C_ALIASANEXO IS NULL
GO


--### SET ZURI VERSION ###
begin try
	declare @v sysname = '9.1902.2406'--zuriversion
	declare @d varchar(50) = SYSDATETIMEOFFSET()
	if not @v is null and exists (select 1 from sys.extended_properties where class = 0 and name = 'Version')
	begin
		exec sp_updateextendedproperty Version, @v
		exec sp_updateextendedproperty VersionDate, @d
	end 
	else
	begin
		exec sp_addextendedproperty Version, @v
		exec sp_addextendedproperty VersionDate, @d
	end
	select * from sys.extended_properties 
end try
begin catch
end catch

--### Zuri9.1902.2406 ###  
