Dre4m Shell
Server IP : 103.6.199.200  /  Your IP : 3.14.132.178
Web Server : Microsoft-IIS/10.0
System : Windows NT EMPUSA 10.0 build 20348 (Windows Server 2016) i586
User : EMPUSA$ ( 0)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : OFF  |  Perl : OFF  |  Python : OFF  |  Sudo : OFF  |  Pkexec : OFF
Directory :  C:/Domains/jivisol1/build/3.20.11.100/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME SHELL ]     

Current File : C:/Domains/jivisol1/build/3.20.11.100/MergeScripts.sql
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.A_Shifts') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[A_Shifts](
	[AId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftId] [bigint] NULL,
	[EmployeeId] [BigInt] NULL,
	[Action] [nvarchar](500) NULL,
	[ShiftBandName] [nvarchar](50) NULL,
	[ShiftStartTime] [datetime] NULL,
	[ShiftEndTime] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[ClockIn] [datetime] NULL,
	[ClockOut] [datetime] NULL,
	[ReconStatus] [nvarchar](500) NULL,
	[InStatus] [nvarchar](50) NULL,
	[OutStatus] [nvarchar](50) NULL,
	[LeaveType] [nvarchar](500) NULL,
	[LeaveAppliedBy] [nvarchar](50) NULL,
	[LeaveApprovedBy] [nvarchar](50) NULL,
	[LeaveAppliedDate] [datetime] NULL,
	[LeaveApprovedDate] [datetime] NULL,
	[ShiftCost] [text] NULL,
	[Remarks] [text] NULL,
	[ActionDate] [datetime] NULL,
	 CONSTRAINT [PK_A_Shifts] PRIMARY KEY CLUSTERED 
	(
		[AId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]




END
ELSE 
 Print 'A_Shifts Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_Employee') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[C_Employee](
	[EmployeeId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[RosterGroupId] [bigint] NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[BadgeNumber] [nvarchar](50) NULL,
	[FirstName] [nvarchar](500) NULL,
	[MiddleName] [nvarchar](500) NULL,
	[LastName] [nvarchar](500) NULL,
	[DisplayName] [nvarchar](2500) NULL,
	[DateOfBirth] [date] NULL,
	[EmploymentBasisId] [bigint] NULL,
	[MaritalStatusId] [int] NULL,
	[GenderId] [int] NULL,
	[ReligionId] [int] NULL,
	[Address1] [nvarchar](500) NULL,
	[Address2] [nvarchar](500) NULL,
	[Address3] [nvarchar](500) NULL,
	[City] [nvarchar](500) NULL,
	[PostCode] [nvarchar](50) NULL,
	[State] [nvarchar](500) NULL,
	[CountryId] [int] NULL,
	[HomePhone] [nvarchar](50) NULL,
	[MobilePhone] [nvarchar](50) NULL,
	[EmailAddress] [nvarchar](500) NULL,
	[IsTerminated] [bit] NULL,
	[TerminationDate] [date] NULL,
	[HiredDate] [date] NULL,
	[ProbationExpiryDate] [date] NULL,
	[Position] [nvarchar](500) NULL,
	[Title] [nvarchar](50) NULL,
	[ProfilePhoto1] [nvarchar](max) NULL,
	[ProfilePhoto2] [nvarchar](max) NULL,
	[ScheduleRuleId] [bigint] NULL,
	[PayGroupId] [bigint] NULL,
	[OvertimeId] [bigint] NULL,
	[HourlyRate] [decimal](18, 4) NULL,
	[ContractedHours] [decimal](18, 2) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_Employee] PRIMARY KEY CLUSTERED 
	(
		[EmployeeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'C_Employee Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeContacts') AND type in ('U'))
BEGIN

	
CREATE TABLE [dbo].[C_EmployeeContacts](
	[EmployeeContactId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[Relationship] [nvarchar](100) NULL,
	[ContactName] [nvarchar](1000) NULL,
	[Address1] [nvarchar](500) NULL,
	[Address2] [nvarchar](500) NULL,
	[Address3] [nvarchar](500) NULL,
	[City] [nvarchar](500) NULL,
	[State] [nvarchar](100) NULL,
	[HomePhone] [nvarchar](100) NULL,
	[MobilePhone] [nvarchar](100) NULL,
	[EmailAddress] [nvarchar](100) NULL,
	[PostCode] [nvarchar](50) NULL,
	[Country] [nvarchar](500) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_EmployeeEmergencyContacts] PRIMARY KEY CLUSTERED 
	(
		[EmployeeContactId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'C_EmployeeContacts Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeDiciplinary') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[C_EmployeeDiciplinary](
	[DisciplinaryId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[OUId] [bigint] NOT NULL,
	[StatusId] [int] NOT NULL,
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
	[Remarks] [nvarchar](1000) NULL,
	[ActionDate] [datetime] NOT NULL,
	[ActiveStatus] [bit] NULL,
	[DisciplinaryActionStatus] [int] NULL, 
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeeDiciplinary] PRIMARY KEY CLUSTERED 
	(
		[DisciplinaryId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[C_EmployeeDiciplinary] ADD  CONSTRAINT [DF_C_EmployeeDiciplinary_StatusId]  DEFAULT ((1)) FOR [StatusId]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = Employment , 2 = Suspenstion' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_EmployeeDiciplinary', @level2type=N'COLUMN',@level2name=N'StatusId'

END
ELSE 
 Print 'C_EmployeeDiciplinary Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeExcludeSkills') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[C_EmployeeExcludeSkills](
	[SkillExcludeId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[SkillStartDate] [datetime] NULL,
	[SkillEndDate] [datetime] NULL,
	[Reason] [nvarchar](500) NULL,
	[ActiveStatus] [BIT] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_EmployeeExcludeSkills] PRIMARY KEY CLUSTERED 
	(
		[SkillExcludeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'C_EmployeeExcludeSkills Table Exist'
 
 GO
/****** Object:  Table [dbo].[C_EmployeeLeaveProfile]    Script Date: 6/19/2018 10:58:03 AM ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeLeaveProfile') AND type in ('U'))
begin


	CREATE TABLE [dbo].[C_EmployeeLeaveProfile](
	[EmployeeLeaveProfileId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[LeaveProfileHeaderId] [int] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[ActionDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_EmployeeLeaveProfile] PRIMARY KEY CLUSTERED 
	(
		[EmployeeLeaveProfileId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
end
else 
 Print 'C_EmployeeLeaveProfile Table Exist'

GO
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeMovement') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[C_EmployeeMovement](
		[MovementId] [bigint] IDENTITY(1,1) NOT NULL,
		[EmployeeId] [bigint] NULL,
		[OUId] [bigint] NULL,
		[StartDate] [date] NULL,
		[EndDate] [date] NULL,
		[PrimaryRoleId] [bigint] NOT NULL,
		[RosterGroupId] [bigint] NOT NULL,
		[OTSettingsId] [bigint] NOT NULL,
		[ScheduleRuleId] [bigint] NOT NULL,
		[ActiveStatus] [bit] NULL,
		[MovementStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeeEmployment] PRIMARY KEY CLUSTERED 
	(
		[MovementId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'C_EmployeeMovement Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeOU') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[C_EmployeeOU](
		[EmployeeOUId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NULL,
		[IsPrimaryOU] [bit] NOT NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeeOU] PRIMARY KEY CLUSTERED 
	(
		[EmployeeOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE
	Print 'C_EmployeeOU Already Exists'
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeRoles') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_EmployeeRoles](
	[EmployeeRoleId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[RoleId] [bigint] NOT NULL,
	[IsPrimaryRole] [bit] NOT NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeeRoles] PRIMARY KEY CLUSTERED 
	(
		[EmployeeRoleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



	ALTER TABLE [dbo].[C_EmployeeRoles] ADD  CONSTRAINT [DF_C_EmployeeRoles_IsPrimaryRole]  DEFAULT ((0)) FOR [IsPrimaryRole]

END
ELSE 
 Print 'C_EmployeeRoles Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeSkills') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_EmployeeSkills](
	[EmployeeSkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[IsPrimary] [BIT] NULL,
	[SkillRating] [int] NULL,
	[RotationNo] [int] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[IsActingSkill] [BIT] NULL,
	[ActiveStatus] [BIT] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_EmployeeSkills] PRIMARY KEY CLUSTERED 
	(
		[EmployeeSkillId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



	ALTER TABLE [dbo].[C_EmployeeSkills] ADD  CONSTRAINT [DF_C_EmployeeSkills_SkillRating]  DEFAULT ((0)) FOR [SkillRating]


	ALTER TABLE [dbo].[C_EmployeeSkills] ADD  CONSTRAINT [DF_C_EmployeeSkills_RotationNo]  DEFAULT ((0)) FOR [RotationNo]


END
ELSE 
 Print 'C_EmployeeSkills Table Exist'
 
 GO

 /****** Object:  Table [dbo].[C_EmployeeLeaveProfile]    Script Date: 6/19/2018 10:58:03 AM ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeWorkflow') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[C_EmployeeWorkflow](
	[EmployeeWorkflowId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[ModuleId] [int] NOT NULL,
	[RouteId] [bigint] NOT NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL
	) ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Employee Id from C_Employee' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_EmployeeWorkflow', @level2type=N'COLUMN',@level2name=N'EmployeeId'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Module Id From W_Modules' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_EmployeeWorkflow', @level2type=N'COLUMN',@level2name=N'ModuleId'
	
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Route Id From W_WorkflowRoute' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_EmployeeWorkflow', @level2type=N'COLUMN',@level2name=N'RouteId'

END
ELSE
	Print 'C_EmployeeWorkflow Table Exist'
GO
	IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_InterfaceConfig') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_InterfaceConfig](
		[InterfaceConfigId] [int] IDENTITY(1,1) NOT NULL,
		[InterfaceId] [bigint] NOT NULL,
		[ConfigType] [nvarchar](255) NULL,
		[ConfigValue] [nvarchar](max) NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_InterfaceConfig] PRIMARY KEY CLUSTERED 
	(
		[InterfaceConfigId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Ex: ConnectionString, SelectQuery, UpdateQuery, DeleteQuery' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_InterfaceConfig', @level2type=N'COLUMN',@level2name=N'ConfigType'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Actual ConnectionString / Select / Update / Delete Statements' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_InterfaceConfig', @level2type=N'COLUMN',@level2name=N'ConfigValue'

END
Else
	Print 'C_InterfaceConfig Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_InterfaceLog') AND type in ('U'))
begin

	CREATE TABLE [dbo].[C_InterfaceLog](
	[LogId] [bigint] IDENTITY(1,1) NOT NULL,
	[InterfaceId] [bigint] NULL,
	[TranId] [bigint] NULL,
	[RowNo] [bigint] NULL,
	[FileContent] [text] NULL,
	[MessageType] [int] NULL,
	[Message] [text] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_InterfaceLog] PRIMARY KEY CLUSTERED 
	(
		[LogId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


	ALTER TABLE [dbo].[C_InterfaceLog] ADD  CONSTRAINT [DF_C_InterfaceLog_MessageType]  DEFAULT ((0)) FOR [MessageType]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0- Success 1- Error 2- Warning' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_InterfaceLog', @level2type=N'COLUMN',@level2name=N'MessageType'
	
end
else 
 Print 'C_InterfaceLog Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_Interfaces') AND type in ('U'))
begin

	CREATE TABLE [dbo].[C_Interfaces](
	[InterfaceId] [bigint] IDENTITY(1,1) NOT NULL,
	[Type] [nvarchar](50) NULL,
	[Name] [nvarchar](500) NULL,
	[ModuleName] [nvarchar](50) NULL,
	[Method] [nvarchar](50) NULL,
	[FileType] [nvarchar](50) NULL,
	[SoftwareName] [nvarchar](500) NOT NULL,
	[FileNamePrefix] [nvarchar](50) NULL,
	[FileLocation] [nvarchar](2000) NULL,
	[FileFormat] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_Interfaces] PRIMARY KEY CLUSTERED 
	(
		[InterfaceId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]



	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Import/ Export' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Interfaces', @level2type=N'COLUMN',@level2name=N'Type'


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Employee, T&A' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Interfaces', @level2type=N'COLUMN',@level2name=N'ModuleName'


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'File, Database, Webservice' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Interfaces', @level2type=N'COLUMN',@level2name=N'Method'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'txt,XLX,CSV' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Interfaces', @level2type=N'COLUMN',@level2name=N'FileType'


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Local/Server' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Interfaces', @level2type=N'COLUMN',@level2name=N'FileNamePrefix'

	
end
else 
 Print 'C_Interfaces Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_InterfaceTransactions') AND type in ('U'))
begin


	CREATE TABLE [dbo].[C_InterfaceTransactions](
	[TranId] [bigint] IDENTITY(1,1) NOT NULL,
	[InterfaceId] [bigint] NULL,
	[InitializedDate] [datetime] NULL,
	[InitializedUser] [nvarchar](50) NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[Status] [int] NULL,
	[Remarks] [text] NULL,
	[FileName] [text] NULL,
	CONSTRAINT [PK_C_InterfaceTransactions] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	ALTER TABLE [dbo].[C_InterfaceTransactions] ADD  CONSTRAINT [DF_C_InterfaceTransactions_Status]  DEFAULT ((0)) FOR [Status]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - in queue, 1 - In progress , 2-Completed 3 - Cancelled 4- Failed' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_InterfaceTransactions', @level2type=N'COLUMN',@level2name=N'Status'

end
else 
 Print 'C_InterfaceTransactions Table Exist'

 GO
/****** Object:  Table [dbo].[C_Menu]    Script Date: 6/19/2018 10:58:03 AM ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.c_menu') AND type in ('U'))
begin
	CREATE TABLE [dbo].[C_Menu](
		[MenuID] [bigint] IDENTITY(1,1) NOT NULL,
		[ParentMenuID] [bigint] NULL,
		[MenuName] [nvarchar](50) NOT NULL,
		[MenuLink] [nvarchar](max) NULL,
		[DisplayOrder] [int] NOT NULL,
		[MenuImage] [nvarchar](200) NOT NULL,
		[IsActive] [bit] NOT NULL CONSTRAINT [DF_C_Menu_IsActive]  DEFAULT ((1)),
		[CreatedBy] [nvarchar](100) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[Sequence] [int] NULL,
		[IsSelfService] [bit] NOT NULL CONSTRAINT [DF_C_Menu_IsSelfService]  DEFAULT ((0)),
	 CONSTRAINT [PK_C_Menu] PRIMARY KEY CLUSTERED 
	(
		[MenuID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	
end
else 
 Print 'C_Menu Table Exist'

 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_OrganizationNode') AND type in ('U'))
begin
	CREATE TABLE [dbo].[C_OrganizationNode](
	[OUId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUName] [nvarchar](500) NULL,
	[OUDesc] [nvarchar](2000) NULL,
	[ParentOUId] [bigint] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_OrganizationNode] PRIMARY KEY CLUSTERED 
	(
	[OUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

end
else 
 Print 'C_OrganizationNode Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_Permissions') AND type in ('U'))
begin


	CREATE TABLE [dbo].[C_Permissions](
	[PermissionId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[MenuId] [bigint] NULL,
	[PermissionTypeId] [int] NULL,
	[SecurityRoleID] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_Permissions] PRIMARY KEY CLUSTERED 
	(
		[PermissionId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[C_Permissions] ADD  CONSTRAINT [DF_C_Permissions_PermissionTypeId]  DEFAULT ((1)) FOR [PermissionTypeId]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Read, 2- Read and Write' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_Permissions', @level2type=N'COLUMN',@level2name=N'PermissionTypeId'


end
else 
 Print 'C_Permissions Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_SecurityRole') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_SecurityRole](
	[SecurityRoleID] [bigint] IDENTITY(1,1) NOT NULL,
	[SecurityRoleCode] [nvarchar](50) NOT NULL,
	[Description] [nvarchar](500) NULL,
	[IsActive] [bit] NOT NULL CONSTRAINT [DF_C_UserRole_IsActiveSec]  DEFAULT ((1)),
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_SecurityRole] PRIMARY KEY CLUSTERED 
	(
	[SecurityRoleID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
ELSE 
 Print 'C_SecurityRole Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_SecurityRolePermissions') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_SecurityRolePermissions](
	[SecurityRolePermissionId] [bigint] IDENTITY(1,1) NOT NULL,
	[SecurityRoleId] [bigint] NOT NULL,
	[MenuId] [bigint] NOT NULL,
	[PermissionTypeId] [int] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_SecurityRolePermissions] PRIMARY KEY CLUSTERED 
	(
		[SecurityRolePermissionId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[C_SecurityRolePermissions] ADD  CONSTRAINT [DF_C_SecurityRolePermissions_PermissionTypeId]  DEFAULT ((1)) FOR [PermissionTypeId]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Read, 2- Read and Write' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_SecurityRolePermissions', @level2type=N'COLUMN',@level2name=N'PermissionTypeId'

END
ELSE 
 Print 'C_SecurityRolePermissions Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_User') AND type in ('U'))
begin
	CREATE TABLE [dbo].[C_User](
	[UserID] [bigint] IDENTITY(1,1) NOT NULL,
	[UserName] [nvarchar](100) NULL,
	[PasswordHash] [nvarchar](max) NULL,
	[PasswordSalt] [nvarchar](200) NULL,
	[UserRoleID] [bigint] NULL,
	[EmployeeID] [bigint] NULL,
	[LastLoginDate] [datetime] NULL,
	[ChangePasswordOnLogin] [bit] NOT NULL CONSTRAINT [DF_C_User_ChangePasswordOnLogin]  DEFAULT ((0)),
	[ResetPassword] [bit] NOT NULL CONSTRAINT [DF_C_User_ResetPassword]  DEFAULT ((0)),
	[IsActive] [bit] NOT NULL CONSTRAINT [DF_C_User_IsActive]  DEFAULT ((1)),
	[CreatedBy] [nvarchar](100) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](100) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_User] PRIMARY KEY CLUSTERED 
	(
	[UserID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


	
end
else 
 Print 'C_User Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_UserAudit') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_UserAudit](
	[UserAuditId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [bigint] NULL,
	[UserName] [nVarchar](255) NULL,
	[ActionDate] [datetime] NOT NULL,
	[ActionType] [int] NOT NULL,
	[ActionDescription] [text] NOT NULL,
	[TraceLog] [text] NULL,
	 CONSTRAINT [PK_C_UserAudit] PRIMARY KEY CLUSTERED 
	(
		[UserAuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
ELSE 
	Print 'C_UserAudit Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_UserSecurityRole') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_UserSecurityRole](
		[UserSecurityRoleId] [bigint] IDENTITY(1,1) NOT NULL,
		[UserId] [bigint] NOT NULL,
		[SecurityRoleId] [bigint] NOT NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_UserSecurityRole] PRIMARY KEY CLUSTERED 
	([UserSecurityRoleId] ASC )
	WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[C_UserSecurityRole] ADD  CONSTRAINT [DF_C_UserSecurityRole_ActiveStatus]  DEFAULT ((1)) FOR [ActiveStatus]
	
END
ELSE 
 Print 'C_UserSecurityRole Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_UserSecurityRoleOU') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_UserSecurityRoleOU](
		[UserSecurityRoleOUId] [bigint] IDENTITY(1,1) NOT NULL,
		[UserSecurityRoleId] [bigint] NOT NULL,
		[OUId] [bigint] NOT NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_UserSecurityRoleOU] PRIMARY KEY CLUSTERED 
	(
	[UserSecurityRoleOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[C_UserSecurityRoleOU] ADD  CONSTRAINT [DF_C_UserSecurityRoleOU_ActiveStatus]  DEFAULT ((1)) FOR [ActiveStatus]
	
END
ELSE 
 Print 'C_UserSecurityRoleOU Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_UserSecurityRoles') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[C_UserSecurityRoles](
	[UserSecurityRoleId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [bigint] NOT NULL,
	[SecurityRoleId] [bigint] NOT NULL,
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_UserSecurityRoles] PRIMARY KEY CLUSTERED 
	(
		[UserSecurityRoleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'C_UserSecurityRoles Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_EmailTemplate') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_EmailTemplate](
		[TemplateId] [bigint] IDENTITY(1,1) NOT NULL,
		[LanguageId] [int] NULL,
		[FunctionId] [int] NULL,
		[MailSubject] [text] NULL,
		[MailBody] [text] NULL,
		[MailCC] [text] NULL,
		[MailFrom] [text] NULL,
		[ActiveStatus] [bit] NULL,
		[SaveLog] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_EmailTemplate] PRIMARY KEY CLUSTERED 
	(
		[TemplateId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	ALTER TABLE [dbo].[D_EmailTemplate] ADD  CONSTRAINT [DF_D_EmailTemplate_StoreLog]  DEFAULT ((0)) FOR [SaveLog]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Example 1 = Leave Application, 2 = Approved Leave, 3 = Rejected Leave, 4 = Cancel Leave,' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'D_EmailTemplate', @level2type=N'COLUMN',@level2name=N'FunctionId'	
END
Else
	Print 'D_EmailTemplate Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_EmploymentBasis') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_EmploymentBasis](
	[EmploymentBasisId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmploymentBasisCode] [nvarchar](500) NULL,
	[EmploymentBasisDesc] [nvarchar](1000) NULL,
	[Seq] [int] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_EmploymentBasis] PRIMARY KEY CLUSTERED 
	(
		[EmploymentBasisId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_EmploymentBasis Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_EmploymentBasisOU') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[D_EmploymentBasisOU](
	[EmploymentBasisOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmploymentBasisId] [bigint] NULL,
	[OUId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_EmploymentBasisOU] PRIMARY KEY CLUSTERED 
	(
		[EmploymentBasisOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'D_EmploymentBasisOU Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ExceptionCodes') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_ExceptionCodes](
		[ExceptionCodeId] [bigint] IDENTITY(1,1) NOT NULL,
		[ExcpetionCodeName] [nvarchar](50) NULL,
		[ExceptionCodeDesc] [nvarchar](255) NULL,
		[ExceptionTypeId] [int] NULL,
		[ColorCode] [nvarchar](50) NULL,
		[IsPaid] [bit] NULL,
		[ESS] [bit] NULL,
		[ShiftLength] [numeric](18, 2) NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_ExceptionCodes] PRIMARY KEY CLUSTERED 
	(
		[ExceptionCodeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_ExceptionCodes Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ExceptionCodesOU') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_ExceptionCodesOU](
		[ExceptionCodeOUId] [bigint] IDENTITY(1,1) NOT NULL,
		[ExceptionCodeId] [bigint] NOT NULL,
		[OUId] [bigint] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_ExceptionCodesOU] PRIMARY KEY CLUSTERED 
	(
		[ExceptionCodeOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_ExceptionCodesOU Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ExceptionType') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_ExceptionType](
		[ExceptionTypeId] [int] IDENTITY(1,1) NOT NULL,
		[ExceptionTypeName] [nvarchar](50) NOT NULL,
		[ExceptionTypeDesc] [nvarchar](100) NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_ExceptionType] PRIMARY KEY CLUSTERED 
	(
		[ExceptionTypeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
ELSE 
 Print 'D_ExceptionType Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_MasterCodes') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_MasterCodes](
	[CodeId] [bigint] IDENTITY(1,1) NOT NULL,
	[CodeType] [nvarchar](50) NULL,
	[CodeValue] [nvarchar](500) NULL,
	[Seq] [int] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_MasterCodes] PRIMARY KEY CLUSTERED 
	(
	[CodeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_MasterCodes Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PayCodeOU') AND type in ('U'))
BEGIN
	
	
CREATE TABLE [dbo].[D_PayCodeOU](
	[PayCodeOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[PayCodeId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PayCodeOU] PRIMARY KEY CLUSTERED 
	(
		[PayCodeOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'D_PayCodeOU Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PayCodes') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[D_PayCodes](
	[PayCodeId] [bigint] IDENTITY(1,1) NOT NULL,
	[PayCode] [nvarchar](50) NULL,
	[PayCodeDesc] [nvarchar](500) NULL,
	[Multiplier] [decimal](18, 5) NULL,
	[Seq] [int] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PayCodes] PRIMARY KEY CLUSTERED 
	(
		[PayCodeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_PayCodes Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PayGroup') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_PayGroup](
	[PayGroupId] [bigint] IDENTITY(1,1) NOT NULL,
	[PayGroupCode] [nvarchar](50) NULL,
	[PayGroupDesc] [nvarchar](500) NULL,
	[PayPeriod] [nvarchar](500) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PayGroup] PRIMARY KEY CLUSTERED 
	(
	[PayGroupId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'PayGroup Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PaygroupCodes') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[D_PaygroupCodes](
	[PayGroupPayCodeId] [bigint] IDENTITY(1,1) NOT NULL,
	[PayCodeId] [bigint] NULL,
	[PayGroupId] [bigint] NOT NULL,
	[PaycodeType] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_PaygroupCodes] PRIMARY KEY CLUSTERED 
	(
		[PayGroupPayCodeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	ALTER TABLE [dbo].[D_PaygroupCodes] ADD  CONSTRAINT [DF_D_PaygroupCodes_PaycodeType]  DEFAULT ((1)) FOR [PaycodeType]

	ALTER TABLE [dbo].[D_PaygroupCodes]  WITH CHECK ADD  CONSTRAINT [FK_D_PaygroupCodes_D_PayCodes] FOREIGN KEY([PayCodeId])
	REFERENCES [dbo].[D_PayCodes] ([PayCodeId])

	ALTER TABLE [dbo].[D_PaygroupCodes] CHECK CONSTRAINT [FK_D_PaygroupCodes_D_PayCodes]

	ALTER TABLE [dbo].[D_PaygroupCodes]  WITH CHECK ADD  CONSTRAINT [FK_D_PaygroupCodes_D_PayGroup] FOREIGN KEY([PayGroupId])
	REFERENCES [dbo].[D_PayGroup] ([PayGroupId])

	ALTER TABLE [dbo].[D_PaygroupCodes] CHECK CONSTRAINT [FK_D_PaygroupCodes_D_PayGroup]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Normal 2 - Overtime 3- Public Holiday 4. Premium OT 5 - Ramadan' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'D_PaygroupCodes', @level2type=N'COLUMN',@level2name=N'PaycodeType'



END
ELSE 
 Print 'D_PaygroupCodes Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PayGroupOU') AND type in ('U'))
BEGIN
	
	
CREATE TABLE [dbo].[D_PayGroupOU](
	[PayGroupOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[PayGroupId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PayGroupOU] PRIMARY KEY CLUSTERED 
	(
		[PayGroupOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'D_PayGroupOU Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PublicHolidays') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[D_PublicHolidays](
	[PublicHolidayId] [bigint] IDENTITY(1,1) NOT NULL,
	[HolidayName] [nvarchar](500) NULL,
	[HolidayDate] [date] NULL,
	[IsPaid] [bit] NULL,
	[IsLeaveProcess] [bit] NULL,
	[IsShiftProcess] [bit] NULL,
	[HolidayNote] [nvarchar](500) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PublicHolidays] PRIMARY KEY CLUSTERED 
	(
		[PublicHolidayId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

	ALTER TABLE [dbo].[D_PublicHolidays] ADD  CONSTRAINT [DF_D_PublicHolidays_IsLeaveProcess]  DEFAULT ((0)) FOR [IsLeaveProcess]
	

	ALTER TABLE [dbo].[D_PublicHolidays] ADD  CONSTRAINT [DF_D_PublicHolidays_IsShiftProcess]  DEFAULT ((0)) FOR [IsShiftProcess]

END
ELSE 
 Print 'D_PublicHolidays Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_RamadanPeriod') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_RamadanPeriod](
		[RamadanPeriodId] [bigint] IDENTITY(1,1) NOT NULL,
		[RamadanYear] [int] NOT NULL,
		[PeriodStart] [date] NOT NULL,
		[PeriodEnd] [date] NOT NULL,
		[Description] [nvarchar](500) NOT NULL,
		[DailyOverTimeHours] [decimal](18, 2) NOT NULL,
		[WeeklyOverTimeHours] [decimal](18, 2) NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_RamadanPeriod] PRIMARY KEY CLUSTERED 
	(
		[RamadanPeriodId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
Else
	Print 'D_RamadanPeriod Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_RamadanPeriodEmployeeList') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_RamadanPeriodEmployeeList](
		[TranId] [bigint] IDENTITY(1,1) NOT NULL,
		[RamadanPeriodId] [bigint] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[TypeId] [int] NOT NULL,
		[TypeDescription] [nvarchar](500) NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_RamadanPeriodEmployeeList] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[D_RamadanPeriodEmployeeList]  WITH CHECK ADD  CONSTRAINT [FK_D_RamadanPeriodEmployeeList_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])

	ALTER TABLE [dbo].[D_RamadanPeriodEmployeeList] CHECK CONSTRAINT [FK_D_RamadanPeriodEmployeeList_C_Employee]

	ALTER TABLE [dbo].[D_RamadanPeriodEmployeeList]  WITH CHECK ADD  CONSTRAINT [FK_D_RamadanPeriodEmployeeList_D_RamadanPeriod] FOREIGN KEY([RamadanPeriodId])
	REFERENCES [dbo].[D_RamadanPeriod] ([RamadanPeriodId])

	ALTER TABLE [dbo].[D_RamadanPeriodEmployeeList] CHECK CONSTRAINT [FK_D_RamadanPeriodEmployeeList_D_RamadanPeriod]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = A, 2 = B, 3 = C' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'D_RamadanPeriodEmployeeList', @level2type=N'COLUMN',@level2name=N'TypeDescription'

END
Else
	Print 'D_RamadanPeriodEmployeeList Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ReliefRule') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[D_ReliefRule](
	[RuleId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[RuleName] [nvarchar](1000) NULL,
	[RuleDesc] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_ReliefRule] PRIMARY KEY CLUSTERED 
	(
		[RuleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'D_ReliefRule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ReliefRuleSkill') AND type in ('U'))
BEGIN	

CREATE TABLE [dbo].[D_ReliefRuleSkill](
	[RuleDetId] [bigint] IDENTITY(1,1) NOT NULL,
	[RuleId] [bigint] NULL,
	[Seq] [int] NULL,
	[Clause] [nvarchar](50) NULL,
	[SkillId] [bigint] NULL,
	[OperatingHour] [int] NULL,
	[NoOfEmployee] [int] NULL,
	[NoOfActivity] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
 CONSTRAINT [PK_D_ReliefRuleSkill] PRIMARY KEY CLUSTERED 
(
	[RuleDetId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]


END
ELSE 
 Print 'D_ReliefRuleSkill Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_RoleGroup') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[D_RoleGroup](
	[RoleGroupId] [bigint] IDENTITY(1,1) NOT NULL,
	[RoleGroupName] [nvarchar](50) NULL,
	[OUId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_RoleGroup] PRIMARY KEY CLUSTERED 
	(
		[RoleGroupId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_RoleGroup Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_RoleOU') AND type in ('U'))
BEGIN


CREATE TABLE [dbo].[D_RoleOU](
	[RoleOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[RoleId] [bigint] NULL,
	[OUId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_RoleOU] PRIMARY KEY CLUSTERED 
	(
		[RoleOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'D_RoleOU Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_Roles') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[D_Roles](
	[RoleId] [bigint] IDENTITY(1,1) NOT NULL,
	[RoleName] [nvarchar](50) NULL,
	[RoleDesc] [nvarchar](500) NULL,
	[PreparationTime] [int] NULL,
	[DePreparationTime] [int] NULL,
	[PrimarySkillId] [bigint] NOT NULL,
	[RoleGroupId] [bigint] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_Roles] PRIMARY KEY CLUSTERED 
	(
		[RoleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_Roles Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_RoleSkill') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[D_RoleSkill](
	[RoleSkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[RoleId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[Priority] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_RoleSkill] PRIMARY KEY CLUSTERED 
	(
		[RoleSkillId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'D_RoleSkill Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ShiftBand') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_ShiftBand](
	[ShiftBandId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftBandName] [nvarchar](500) NULL,
	[ShiftBandDesc] [nvarchar](100) NULL,
	[ShiftBandCode] [nvarchar](50) NULL,
	[ShiftTypeId] [int] NULL,
	[StartTime] [datetime] NULL,
	[StartRangeBegin] [int] NULL,
	[StartRangeEnd] [int] NULL,
	[EndTime] [datetime] NULL,
	[EndRangeBegin] [int] NULL,
	[EndRangeEnd] [int] NULL,
	[ShiftLengthMin] [int] NULL,
	[ShiftLengthMax] [int] NULL,
	[ColorCode] [nvarchar](50) NULL,
	[OvertimeType] [nvarchar](50) NULL,
	[OverttimeStart] [datetime] NULL,
	[OvertimeEnd] [datetime] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_ShiftBand] PRIMARY KEY CLUSTERED 
	(
		[ShiftBandId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

END
ELSE 
 Print 'D_ShiftBand Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ShiftBandCombination') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_ShiftBandCombination](
	[ComboId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftBandId] [bigint] NULL,
	[ComboShiftBandId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_ShiftBandCombination] PRIMARY KEY CLUSTERED 
	(
		[ComboId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'D_ShiftBandCombination Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ShiftBandOU') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[D_ShiftBandOU](
	[ShiftBandOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftBandId] [bigint] NULL,
	[OUId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_ShiftBandOU] PRIMARY KEY CLUSTERED 
	(
		[ShiftBandOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'D_ShiftBandOU Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_ShiftBandType') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_ShiftBandType](
	[ShiftTypeId] [int] IDENTITY(1,1) NOT NULL,
	[ShiftBandTypeDescription] [nvarchar](50) NULL,
	[Seq] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	[IsActive] [bit] NULL,
	CONSTRAINT [PK_D_ShiftBandType] PRIMARY KEY CLUSTERED 
	(
	[ShiftTypeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'D_ShiftBandType Table Exist'
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_Skill') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_Skill](
	[SkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[Skill] [nvarchar](50) NULL,
	[SkillDesc] [nvarchar](500) NULL,
	[LicenceRequired] [bit] NULL,
	[Seq] [int] NULL,
	[ColorCode] [nvarchar](50) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_Skill] PRIMARY KEY CLUSTERED 
	(
		[SkillId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'D_Skill Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_SkillOU') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_SkillOU](
	[SkillOUId] [bigint] IDENTITY(1,1) NOT NULL,
	[SkillId] [bigint] NULL,
	[OUId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_SkillOU] PRIMARY KEY CLUSTERED 
	(
		[SkillOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

END
ELSE 
 Print 'D_SkillOU Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_SystemParams') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[D_SystemParams](
	[ParamId] [bigint] IDENTITY(1,1) NOT NULL,
	[ParamName] [nvarchar](500) NULL,
	[ParamValue] [nvarchar](4000) NULL,
	[ParamDesc] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_SystemParams] PRIMARY KEY CLUSTERED 
	(
		[ParamId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'D_SystemParams Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EqipmentMatrix_Schedule') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[E_EqipmentMatrix_Schedule](
	[MatrixScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[MatrixId] [bigint] NULL,
	[ScheduledValue] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EqipmentMatrix_Schedule] PRIMARY KEY CLUSTERED 
	(
		[MatrixScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'E_EqipmentMatrix_Schedule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EquipmentMatrix') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[E_EquipmentMatrix](
	[MatrixId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[MatrixEQTypeId] [bigint] NULL,
	[TemplateName] [nvarchar](500) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EquipmentMatrix] PRIMARY KEY CLUSTERED 
	(
		[MatrixId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	
END
ELSE 
 Print 'E_EquipmentMatrix Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EquipmentMatrix_EquipmentType') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[E_EquipmentMatrix_EquipmentType](
	[MatrixEquipmentTypeId] [bigint] IDENTITY(1,1) NOT NULL,
	[MatrixId] [bigint] NULL,
	[MatrixScheduleId] [bigint] NULL,
	[EquipmentTypeId] [bigint] NULL,
	[EquipmentTypeValue] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EquipmentMatrix_EquipmentType] PRIMARY KEY CLUSTERED 
	(
		[MatrixEquipmentTypeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'E_EquipmentMatrix_EquipmentType Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EquipmentType_Matrix_Det') AND type in ('U'))
BEGIN	


	CREATE TABLE [dbo].[E_EquipmentType_Matrix_Det](
	[MatrixEQTypeDetId] [bigint] IDENTITY(1,1) NOT NULL,
	[MatrixEQTypeId] [bigint] NULL,
	[EquipmentTypeId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EquipmentType_Matrix_Det] PRIMARY KEY CLUSTERED 
	(
		[MatrixEQTypeDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'E_EquipmentType_Matrix_Det Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EquipmentType_Matrix_Template') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[E_EquipmentType_Matrix_Template](
	[MatrixEQTypeId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[TemplateName] [nvarchar](500) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EquipmentType_Matrix_Template] PRIMARY KEY CLUSTERED 
	(
		[MatrixEQTypeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'E_EquipmentType_Matrix_Template Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.I_BoxMovementSummary') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[I_BoxMovementSummary](
		[BoxMovementId] [bigint] IDENTITY(1,1) NOT NULL,
		[Date] [datetime] NOT NULL,
		[ShiftBandId] [bigint] NOT NULL,
		[CMPHTarget] [decimal](18, 2) NULL,
		[CMPHActual] [decimal](18, 2) NULL,
		[PMPHTarget] [decimal](18, 2) NULL,
		[PMPHActual] [decimal](18, 2) NULL,
		[MovesTarget] [decimal](18, 2) NULL,
		[MovesActual] [decimal](18, 2) NULL,
		[ActualGang] [decimal](18, 2) NULL,
		[ColumnA] [decimal](18, 2) NULL,
		[ColumnB] [decimal](18, 2) NULL,
		[ColumnC] [decimal](18, 2) NULL,
		[ColumnD] [decimal](18, 2) NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_I_BoxMovementSummary] PRIMARY KEY CLUSTERED 
	(
		[BoxMovementId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_Activity') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[J_Activity](
	[ActivityId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[ShiftBandId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[WorkType] [int] NULL,
	--[CraneScheduleId] [bigint] NULL,
	--[EquipmentScheduleId] [bigint] NULL,
	[ShiftId] [bigint] NULL,
	[RuleId] [bigint] NULL,
	[GroupNo] [int] NULL,
	[AllocationNo] [int] NULL,
	[ProgresstionState] [int] NULL CONSTRAINT [DF_J_Activity_ProgresstionState]  DEFAULT ((1)),
	[DeployedDate] [datetime] NULL,
	[DeployedUser] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_Activity] PRIMARY KEY CLUSTERED 
	(
		[ActivityId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	

	ALTER TABLE [dbo].[J_Activity] ADD  CONSTRAINT [DF_J_Activity_WorkType]  DEFAULT ((0)) FOR [WorkType]
	

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Crane, 2 - Equipment 3 - Auxiliry' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_Activity', @level2type=N'COLUMN',@level2name=N'WorkType'
	

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Not Signed off 2 - Signed off 3 - Deployed 4- Publish' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_Activity', @level2type=N'COLUMN',@level2name=N'ProgresstionState'
	



END
ELSE 
 Print 'J_Activity Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_ActivityAttributes') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_ActivityAttributes](
	[ActivityAttributeId] [bigint] IDENTITY(1,1) NOT NULL,
	[ActivityId] [bigint] NULL,
	[AttributeId] [int] NULL,
	[ScheduleId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_J_ActivityAttributes] PRIMARY KEY CLUSTERED 
	(
		[ActivityAttributeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	ALTER TABLE [dbo].[J_ActivityAttributes] ADD  CONSTRAINT [DF_J_ActivityAttributes_AttributeId]  DEFAULT ((1)) FOR [AttributeId]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Schedule' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_ActivityAttributes', @level2type=N'COLUMN',@level2name=N'AttributeId'

END
ELSE 
 Print 'J_ActivityAttributes Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_AllocationFactor') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_AllocationFactor](
	[FactorId] [int] NOT NULL,
	[FactorName] [nvarchar](500) NULL,
	[FactoryDesc] [text] NULL,
	[FactorValue] [bigint] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_AllocationFactor] PRIMARY KEY CLUSTERED 
	(
		[FactorId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'J_AllocationFactor Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_AllocationRule') AND type in ('U'))
BEGIN	
	CREATE TABLE [dbo].[J_AllocationRule](
	[AllocationRuleId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[RuleName] [nvarchar](500) NULL,
	[RuleDesc] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_AllocationRule] PRIMARY KEY CLUSTERED 
	(
		[AllocationRuleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'J_AllocationRule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_AllocationRuleEmploymentBasis') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_AllocationRuleEmploymentBasis](
	[AllocationRuleEmployeementBasisId] [bigint] IDENTITY(1,1) NOT NULL,
	[AllocationRuleId] [bigint] NULL,
	[EmploymentBasisId] [bigint] NULL,
	[PrioritySeq] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_J_AllocationRuleEmploymentBasis] PRIMARY KEY CLUSTERED 
	(
		[AllocationRuleEmployeementBasisId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'J_AllocationRuleEmploymentBasis Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_AllocationRuleFactor') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_AllocationRuleFactor](
	[RuleFactoryId] [bigint] IDENTITY(1,1) NOT NULL,
	[AllocationRuleId] [bigint] NULL,
	[FactorId] [int] NULL,
	[FactorValue] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_AllocationRuleFactor] PRIMARY KEY CLUSTERED 
	(
		[RuleFactoryId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'J_AllocationRuleFactor Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_AllocationRuleSkillPriority') AND type in ('U'))
BEGIN	

CREATE TABLE [dbo].[J_AllocationRuleSkillPriority](
	[AllocationRuleSkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[AllocationRuleId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[PrioritySeq] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
 CONSTRAINT [PK_J_AllocationRuleSkillPriority] PRIMARY KEY CLUSTERED 
(
	[AllocationRuleSkillId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



END
ELSE 
 Print 'J_AllocationRuleFactor Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_BroadcastDeployment') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[J_BroadcastDeployment](
		[BroadcastId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[BroadcastDate] [datetime] NOT NULL,
		[ShiftBandId] [bigint] NOT NULL,
		[StartTime] [datetime] NOT NULL,
		[EndTime] [datetime] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[ShiftId] [bigint] NOT NULL,
		[Sequence] [int] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_J_BroadcastDeployment] PRIMARY KEY CLUSTERED 
	(
		[BroadcastId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'J_BroadcastDeployment Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_EmployeeShiftValue') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_EmployeeShiftValue](
	[EmployeeId] [bigint] NULL,
	[OUId] [bigint] NULL,
	[ShiftBandId] [bigint] NULL,
	[ShiftDate] [date] NULL,
	[SkillId] [bigint] NULL,
	[ShiftId] [bigint] NULL,
	[FactorValue] [bigint] NULL,
	[Allocated] [bit] NULL,
	[PrimarySkill] [bit] NULL
	) ON [PRIMARY]


END
ELSE 
 Print 'J_EmployeeShiftValue Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_ManningRatio') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_ManningRatio](
	[RatioId] [int] IDENTITY(1,1) NOT NULL,
	[Employee] [int] NULL,
	[Activity] [int] NULL,
	[MaxHour] [int] NULL,
	[ShiftHour] [int] NULL,
	[RBHour] [int] NULL,
	CONSTRAINT [PK_J_ManningRatio] PRIMARY KEY CLUSTERED 
	(
		[RatioId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'J_ManningRatio Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_PlanningEquipmentRequirements') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[J_PlanningEquipmentRequirements](
	[PlanningEquipmentRequirementId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NOT NULL,
	[EquipmentTypeId] [bigint] NOT NULL,
	[ShiftBandId] [bigint] NOT NULL,
	[RequirementDate] [datetime] NOT NULL,
	[ShiftStartTime] [datetime] NOT NULL,
	[ShiftEndTime] [datetime] NOT NULL,
	[RequirementCount] [bigint] NOT NULL,
	[DeployedCount] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_J_PlanningEquipmentRequirements] PRIMARY KEY CLUSTERED 
	(
		[PlanningEquipmentRequirementId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
Else
	Print 'J_PlanningEquipmentRequirements Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_PlanningRequirements') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[J_PlanningRequirements](
		[PlanningRequirementId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[SkillId] [bigint] NOT NULL,
		[ShiftBandId] [bigint] NOT NULL,
		[RequirementDate] [datetime] NOT NULL,
		[ShiftStartTime] [datetime] NOT NULL,
		[ShiftEndTime] [datetime] NOT NULL,
		[RequirementCount] [bigint] NOT NULL,
		[DeployedCount] [bigint] NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_J_PlanningRequirements] PRIMARY KEY CLUSTERED 
	(
		[PlanningRequirementId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[J_PlanningRequirements] ADD  CONSTRAINT [DF_J_PlanningRequirements_DeployedCount]  DEFAULT ((0)) FOR [DeployedCount]
END
Else
	Print 'J_PlanningRequirements Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_SliceSeq') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_SliceSeq](
		[SliceId] [int] IDENTITY(1,1) NOT NULL,
		[RatioId] [int] NULL,
		[ActivityNo] [int] NULL,
		[Seq] [int] NULL,
		[ActHour] [int] NULL,
		[AllocationNo] [int] NULL,
	 CONSTRAINT [PK_J_SliceSeq] PRIMARY KEY CLUSTERED 
	(
		[SliceId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'J_SliceSeq Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_Workload') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[J_Workload](
	[WorkloadId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[WorkType] [int] NULL,
	[CraneScheduleId] [bigint] NULL,
	[EquipmentScheduleId] [bigint] NULL,
	[VesselScheduleId] [bigint] NULL,
	[ShiftBandId] [bigint] NULL,
	[ScheduleId] [bigint] NULL,
	[Imported] [bit] NULL,
	[WorkloadGenerated] [bit] NULL,
	[SignOffStatus] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_Workload] PRIMARY KEY CLUSTERED 
	(
		[WorkloadId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



	ALTER TABLE [dbo].[J_Workload] ADD  CONSTRAINT [DF_J_Workload_WorkType]  DEFAULT ((0)) FOR [WorkType]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Crane, 2 - Equipment 3 - Auxiliry' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_Workload', @level2type=N'COLUMN',@level2name=N'WorkType'


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'M_AuxiliaryWork' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_Workload', @level2type=N'COLUMN',@level2name=N'ScheduleId'


END
ELSE 
 Print 'J_Workload Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_EmployeeLeaveProfiles') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[L_EmployeeLeaveProfiles](
		[EmpProfileId] [bigint] IDENTITY(1,1) NOT NULL,
		[EmployeeId] [bigint] NULL,
		[LeaveProfileId] [int] NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[LeaveYear] [int] NULL,
		[ExceptionId] [bigint] NULL,
		[EntitlementDays] [decimal](18, 2) NULL,
		[CarryForwardDays] [decimal](18, 2) NULL,
		[EarnedDays] [decimal](18, 2) NULL,
		[DaysUsed] [decimal](18, 2) NULL,
		[AdjustDays] [decimal](18, 2) NULL,
		[DaysLieu] [decimal](18, 2) NULL,
		[UsedDays] [decimal](18, 2) NULL,
		[BalanceDays] [decimal](18, 2) NULL,
		[EarnedDays_Cal] [decimal](18, 2) NULL,
		[EarnedDays_Adj] [decimal](18, 2) NULL,
		[EarnedMonth] [int] NULL,
		[AdjustmentRemakrs] [text] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_EmployeeLeaveProfiles] PRIMARY KEY CLUSTERED 
	(
		[EmpProfileId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]




END
ELSE 
 Print 'L_EmployeeLeaveProfiles Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_LeaveBalanceAudit') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[L_LeaveBalanceAudit](
	[LeaveAuditId] [bigint] IDENTITY(1,1) NOT NULL,
	[ActionDate] [datetime] NULL,
	[ReferenceNo] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[ExceptionCodeId] [bigint] NULL,
	[LeaveStart] [datetime] NULL,
	[LeaveEnd] [datetime] NULL,
	[ActionCode] [nvarchar](50) NULL,
	[ActionDesc] [nvarchar](1000) NULL,
	[NoOfDays] [decimal](18, 2) NULL,
	[EntitlementDays] [decimal](18, 2) NULL,
	[CarryForwardDays] [decimal](18, 2) NULL,
	[EarnedDays] [decimal](18, 2) NULL,
	[DaysUsed] [decimal](18, 2) NULL,
	[BalanceDays] [decimal](18, 2) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_L_LeaveBalanceAudit] PRIMARY KEY CLUSTERED 
	(
		[LeaveAuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE
	Print 'L_LeaveBalanceAudit Already Exists'
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_LeaveProfileHeader') AND type in ('U'))
BEGIN
	/****** Object:  Table [dbo].[L_LeaveProfileHeader]    Script Date: 2/19/2019 4:09:16 PM ******/
	SET ANSI_NULLS ON
	SET QUOTED_IDENTIFIER ON

	CREATE TABLE [dbo].[L_LeaveProfileHeader](
		[LeaveProfileHeaderId] [int] IDENTITY(1,1) NOT NULL,
		[ProfileName] [nvarchar](50) NOT NULL,
		[Remarks] [nvarchar](1000) NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_LeaveProfileHeader] PRIMARY KEY CLUSTERED 
	(
		[LeaveProfileHeaderId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE
BEGIN
	Print 'L_LeaveProfileHeader Already Exists'
END
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_LeaveProfileOU') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[L_LeaveProfileOU](
		[LeaveProfileOUId] [int] IDENTITY(1,1) NOT NULL,
		[LeaveProfileHeaderId] [int] NULL,
		[OUId] [bigint] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_LeaveProfileOU] PRIMARY KEY CLUSTERED 
	(
		[LeaveProfileOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_LeaveProfiles') AND type in ('U'))
BEGIN
	/****** Object:  Table [dbo].[L_LeaveProfiles]    Script Date: 2/19/2019 4:09:20 PM ******/
	SET ANSI_NULLS ON
	SET QUOTED_IDENTIFIER ON

	CREATE TABLE [dbo].[L_LeaveProfiles](
		[LeaveProfileId] [int] IDENTITY(1,1) NOT NULL,
		[LeaveProfileHeaderId] [int] NULL,
		[ExceptionCodeId] [bigint] NULL,
		[EntitlementDays] [decimal](18, 2) NULL,
		[CarryForward] [bit] NULL,
		[MaximumDaysPerYear] [decimal](18, 2) NULL,
		[Accural] [bit] NULL,
		[CarryforwardDateType] [int] NULL CONSTRAINT [DF_L_LeaveProfiles_CarryforwardDateType]  DEFAULT ((1)),
		[CarryforwardDate] [datetime] NULL,
		[DayCalculation] [int] NULL CONSTRAINT [DF_L_LeaveProfiles_DayCalculation]  DEFAULT ((1)),
		[DaysInAdvance] [decimal](18, 2) NULL,
		[MinimumDaysRequest] [decimal](18, 2) NULL,
		[MaximumDaysRequest] [decimal](18, 2) NULL,
		[RequestPerYear] [int] NULL,
		[NegativeBalance] [bit] NULL,
		[MaximumDaysNegative] [decimal](18, 2) NULL,
		[HalfDays] [bit] NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_LeaveProfiles] PRIMARY KEY CLUSTERED 
	(
		[LeaveProfileId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- On Date 2 - Calendar Year 3 - Anniversary Date' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'L_LeaveProfiles', @level2type=N'COLUMN',@level2name=N'CarryforwardDateType'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Working Days 2- Calendar Days' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'L_LeaveProfiles', @level2type=N'COLUMN',@level2name=N'DayCalculation'

END
ELSE
BEGIN
	Print 'L_LeaveProfiles Already Exists'
END

GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_Leaves') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[L_Leaves](
	[LeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[ExceptionCodeId] [bigint] NULL,
	[LeaveStart] [datetime] NULL,
	[LeaveEnd] [datetime] NULL,
	[LeaveType] [int] NULL,
	[NoOfDays] [decimal](18, 2) NULL,
	[ReasonId] [int] NULL,
	[IsEmergency] [bit] NULL,
	[ApprovalStatusId] [int] NULL,
	[ReferenceNo] [nvarchar](50) NULL,
	[Remarks] [text] NULL,
	[AppliedBy] [nvarchar](50) NULL,
	[AppliedDate] [datetime] NULL,
	[ApprovedBy] [nvarchar](50) NULL,
	[ApprovedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [DateTime] NULL,
	CONSTRAINT [PK_L_Leaves] PRIMARY KEY CLUSTERED 
	(
		[LeaveId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	ALTER TABLE [dbo].[L_Leaves] ADD  CONSTRAINT [DF_L_Leaves_LeaveType]  DEFAULT ((1)) FOR [LeaveType]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Fullday 2- Morning 3- Afternoon' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'L_Leaves', @level2type=N'COLUMN',@level2name=N'LeaveType'



END
ELSE 
 Print 'L_Leaves Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_LeaveThreshold') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[L_LeaveThreshold](
	[ThresholdId] [bigint] IDENTITY(1,1) NOT NULL,
	[RosterGroupId] [bigint] NULL,
	[RoleGroupId] [bigint] NULL,
	[ExceptionCodeId] [bigint] NULL,
	[ThresholdValue] [decimal](18, 5) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_L_LeaveThreshold] PRIMARY KEY CLUSTERED 
	(
		[ThresholdId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	


END
ELSE
	Print 'L_LeaveThreshold Already Exists'
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_PublicHolidayProcessAudit') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[L_PublicHolidayProcessAudit](
		[PublicHolidayAuditId] [bigint] IDENTITY(1,1) NOT NULL,
		[PublicHolidayId] [bigint] NULL,
		[ProcessDate] [datetime] NULL,
		[EmployeeId] [int] NULL,
		[ActionType] [int] NULL,
		[ActionCode] [nvarchar](50) NULL,
		[ActionDesc] [nvarchar](100) NULL,
		[ActionLog] [text] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_PublicHolidayProcessAudit] PRIMARY KEY CLUSTERED 
	(
		[PublicHolidayAuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Delete, 2 Update 3 Create' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'L_PublicHolidayProcessAudit', @level2type=N'COLUMN',@level2name=N'ActionType'




END
ELSE 
 Print 'L_PublicHolidayProcessAudit Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_RequestDaysInLieu') AND type in ('U'))
BEGIN	


	CREATE TABLE [dbo].[L_RequestDaysInLieu](
	[DaysInLieuId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[RequestedDate] [datetime] NOT NULL,
	[Remarks] [nvarchar](100) NULL,
	[ApprovalStatusId] [int] NOT NULL,
	[ApproverId] [bigint] NULL,
	[AppliedDate] [datetime] NOT NULL,
	[ApprovedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
		CONSTRAINT [PK_L_RequestDaysInLieu] PRIMARY KEY CLUSTERED 
	(
		[DaysInLieuId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'L_RequestDaysInLieu Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_RosterGroupLeaveThreshold') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[L_RosterGroupLeaveThreshold](
	[ThresholdId] [int] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[RosterGroupId] [bigint] NULL,
	[RoleGroupId] [bigint] NULL,
	[ExceptionCodeId] [bigint] NULL,
	[PValu] [decimal](18, 2) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_L_RosterGroupLeaveThreshold] PRIMARY KEY CLUSTERED 
	(
		[ThresholdId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'L_RosterGroupLeaveThreshold Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_TimeOff') AND type in ('U'))
BEGIN	


	CREATE TABLE [dbo].[L_TimeOff](
	[TimeOffId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[Duration] [decimal](18, 2) NULL,
	[BreakHours] [decimal](18, 2) NULL,
	[Remarks] [nvarchar](100) NULL,
	[ApprovalStatusId] [int] NULL,
	[ApproverId] [bigint] NULL,
	[AppliedDate] [datetime] NULL,
	[ApprovedDate] [datetime] NULL,
	[ShiftId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_TimeOff] PRIMARY KEY CLUSTERED 
	(
		[TimeOffId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'L_TimeOff Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.L_Validations') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[L_Validations](
	[ValidationId] [bigint] IDENTITY(1,1) NOT NULL,
	[ExceptionCodeId] [bigint] NOT NULL,
	[ProcedureToExecute] [nvarchar](255) NOT NULL,
	[ActiveStatus] [bit] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_L_Validations] PRIMARY KEY CLUSTERED 
	(
		[ValidationId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[L_Validations] ADD  CONSTRAINT [DF_L_Validations_ActiveStatus]  DEFAULT ((0)) FOR [ActiveStatus]

	ALTER TABLE [dbo].[L_Validations]  WITH CHECK ADD  CONSTRAINT [FK_L_Validations_L_Validations] FOREIGN KEY([ExceptionCodeId])
	REFERENCES [dbo].[D_ExceptionCodes] ([ExceptionCodeId])

	ALTER TABLE [dbo].[L_Validations] CHECK CONSTRAINT [FK_L_Validations_L_Validations]
END
Else
	Print 'L_Validations Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_AuxiliaryWork') AND type in ('U'))
BEGIN	
/****** Object:  Table [dbo].[M_AuxiliaryWork]    Script Date: 8/17/2018 12:54:47 PM ******/
SET ANSI_NULLS ON

SET QUOTED_IDENTIFIER ON
	CREATE TABLE [dbo].[M_AuxiliaryWork](
		[ScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NULL,
		[ShiftBandId] [bigint] NULL,
		[SkillId] [bigint] NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[Requirement] [int] NULL,
		[WorkloadGenereated] [bit] NULL,
		[SignOffStatus] [bit] NULL,
		[CreatedDate] [datetime] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_AuxiliaryWork] PRIMARY KEY CLUSTERED 
	(
		[ScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'M_AuxiliaryWork Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Berth') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[M_Berth](
	[BerthId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[Berth] [nvarchar](50) NULL,
	[BerthDesc] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_Berth] PRIMARY KEY CLUSTERED 
	(
		[BerthId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'M_Berth Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_BerthCranes') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[M_BerthCranes](
	[BerthCraneId] [bigint] IDENTITY(1,1) NOT NULL,
	[BerthId] [bigint] NULL,
	[CraneId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_BerthCranes] PRIMARY KEY CLUSTERED 
	(
		[BerthCraneId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'M_BerthCranes Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Cranes') AND type in ('U'))
begin
	

	CREATE TABLE [dbo].[M_Cranes](
	[CraneId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[CraneNumber] [nvarchar](50) NULL,
	[CraneDesc] [nvarchar](500) NULL,
	[LocationId] [bigint] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_Cranes] PRIMARY KEY CLUSTERED 
	(
		[CraneId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


end
else 
 Print 'M_Cranes Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_CraneSchedule') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_CraneSchedule](
	[CraneScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[CraneId] [bigint] NULL,
	[VesselScheduleId] [bigint] NULL,
	[LocationId] [bigint] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[Imported] [bit] NULL,
	[WorkloadGenerated] [bit] NULL,	
	[SignOffStatus] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_CraneSchedule] PRIMARY KEY CLUSTERED 
	(
		[CraneScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'M_CraneSchedule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Crane_Requirement') AND type in ('U'))
begin
	CREATE TABLE [dbo].[M_Crane_Requirement](
		[CraneReqId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NULL,
		[SkillId] [bigint] NULL,
		[Requirement] [int] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_Crane_Requirement] PRIMARY KEY CLUSTERED 
	(
		[CraneReqId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


end
else 
 Print 'M_Crane_Requirement Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentMaintenance') AND type in ('U'))
begin

	CREATE TABLE [dbo].[M_EquipmentMaintenance](
	[MaintenanceId] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentId] [bigint] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[Reason] [text] NULL,
	[Notes] [text] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_EquipmentMaintenance] PRIMARY KEY CLUSTERED 
	(
		[MaintenanceId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]	

	

end
else 
 Print 'M_EquipmentMaintenance Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Equipments') AND type in ('U'))
begin
	CREATE TABLE [dbo].[M_Equipments](
	[EquipmentId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EquipmentTypeId] [bigint] NULL,
	[EquipmentName] [nvarchar](100) NULL,
	[EquipmentDesc] [nvarchar](1000) NULL,
	[LocationId] [bigint] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_Equipments] PRIMARY KEY CLUSTERED 
	(
		[EquipmentId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
end
else 
 Print 'M_Equipments Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentSchedule') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_EquipmentSchedule](
	[EquipmentScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EquipmentTypeId] [bigint] NULL,
	[EquipmentId] [bigint] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[CraneScheduleId] [bigint] NULL,
	[WorkloadGenereated] [bit] NULL,
	[SignOffStatus] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_EquipmentSchedule] PRIMARY KEY CLUSTERED 
	(
		[EquipmentScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

END
ELSE 
 Print 'M_EquipmentSchedule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentType') AND type in ('U'))
begin


	CREATE TABLE [dbo].[M_EquipmentType](
	[EquipmentTypeId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EquipmentType] [nvarchar](100) NULL,
	[EqipmentTypeDesc] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_EquipmentType] PRIMARY KEY CLUSTERED 
	(
		[EquipmentTypeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


end
else 
 Print 'M_EquipmentType Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentType_Requirement') AND type in ('U'))
begin
	CREATE TABLE [dbo].[M_EquipmentType_Requirement](
	[EquipmentTypeReqId] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentTypeId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[Requirement] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_EquipmentType_Requirement] PRIMARY KEY CLUSTERED 
	(
		[EquipmentTypeReqId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]




end
else 
 Print 'M_EquipmentType_Requirement Table Exist'
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Locations') AND type in ('U'))
begin


	CREATE TABLE [dbo].[M_Locations](
	[LocationId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[LocationName] [nvarchar](500) NULL,
	[LocationDesc] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_Locations] PRIMARY KEY CLUSTERED 
	(
		[LocationId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
	
end
else 
 Print 'M_Locations Table Exist'
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_ResourceSet') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[M_ResourceSet](
	[ResourceSetId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[SetName] [nvarchar](500) NULL,
	[SetDesc] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_ResourceSet] PRIMARY KEY CLUSTERED 
	(
		[ResourceSetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]




END
ELSE 
 Print 'M_ResourceSet Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_ResourceSetDetails') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[M_ResourceSetDetails](
	[ResourceSetDetId] [bigint] IDENTITY(1,1) NOT NULL,
	[ResourceSetId] [bigint] NULL,
	[SkillId] [bigint] NULL,
	[Requirement] [int] NULL,
	[LocationId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_ResourceSetDetails] PRIMARY KEY CLUSTERED 
	(
		[ResourceSetDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'M_ResourceSetDetails Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[M_ShiftSignOffStatus](
	[StatusId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[ShiftDate] [date] NULL,
	[ShiftBandId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[Status] [int] NULL,
	[SignedOffBy] [nvarchar](50) NULL,
	[SignedOffDate] [datetime] NULL,
	 CONSTRAINT [PK_M_ShiftSignOffStatus] PRIMARY KEY CLUSTERED 
	(
		[StatusId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Signed Off 2 - Deployed 3 - Deployment Published' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'M_ShiftSignOffStatus', @level2type=N'COLUMN',@level2name=N'Status'
	


END
ELSE 
 Print 'M_ShiftSignOffStatus Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_SkillMatrix') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_SkillMatrix](
		[SkillMatrixId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[MatrixSkillId] [bigint] NOT NULL,
		[SkillMatrixName] [nvarchar](255) NOT NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_SkillMatrix] PRIMARY KEY CLUSTERED 
	(
		[SkillMatrixId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
Else 
	Print 'M_SkillMatrix Already Exists.'
GO






IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_SkillMatrix_Schedule') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_SkillMatrix_Schedule](
	[SkillMatrixScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[SkillMatrixId] [bigint] NOT NULL,
	[ScheduledValue] [int] NOT NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_SkillMatrix_Schedule] PRIMARY KEY CLUSTERED 
	(
		[SkillMatrixScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
Else 
	Print 'M_SkillMatrix_Schedule Already Exists.'
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_SkillMatrix_Skills') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[M_SkillMatrix_Skills](
		[SkillMatrixDetailsId] [bigint] IDENTITY(1,1) NOT NULL,
		[SkillMatrixId] [bigint] NOT NULL,
		[SkillMatrixScheduleId] [bigint] NOT NULL,
		[SkillId] [bigint] NOT NULL,
		[SkillValue] [int] NOT NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [nchar](10) NULL,
	 CONSTRAINT [PK_M_SkillMatrix_Skills] PRIMARY KEY CLUSTERED 
	(
		[SkillMatrixDetailsId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'This will determine number of cranes. Based on the required cranes matrix value shall be picked' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'M_SkillMatrix_Skills', @level2type=N'COLUMN',@level2name=N'SkillMatrixScheduleId'
END
Else 
	Print 'M_SkillMatrix_Skills Already Exists.'
GO





IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Skill_Matrix_Det') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_Skill_Matrix_Det](
		[MatrixSkillDetId] [bigint] IDENTITY(1,1) NOT NULL,
		[MatrixSkillId] [bigint] NOT NULL,
		[SkillId] [bigint] NOT NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_Skill_Matrix_Det] PRIMARY KEY CLUSTERED 
	(
		[MatrixSkillDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
Else 
	Print 'M_Skill_Matrix_Det Already Exists.'
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_Skill_Matrix_Template') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_Skill_Matrix_Template](
		[MatrixSkillId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[SkillTemplateName] [nvarchar](255) NOT NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_Skill_Matrix_Template] PRIMARY KEY CLUSTERED 
	(
		[MatrixSkillId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
Else 
	Print 'M_Skill_Matrix_Template Already Exists.'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_VesselList') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_VesselList](
	[VesselId] [bigint] IDENTITY(1,1) NOT NULL,
	[VesselName] [nvarchar](500) NULL,
	[LastVisitStartDate] [datetime] NULL,
	[LastVisitEndDate] [datetime] NULL,
	[CraneReq] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_VesselList] PRIMARY KEY CLUSTERED 
	(
		[VesselId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

END
ELSE 
 Print 'M_VesselList Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_VesselSchedule') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_VesselSchedule](
	[VesselScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[VesselName] [nvarchar](1000) NULL,
	[VisitId] [nvarchar](100) NULL,
	[BerthId] [bigint] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[ETA] [datetime] NULL,
	[ETD] [datetime] NULL,
	[NoOfCraneReq] [int] NULL,
	[Priority] [int] NULL,
	[Status] [int] NULL,
	[CraneScheduled] [bit] NULL,
	[ResourceSetId] [bigint] NULL,
	[IsImported] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_VesselSchedule] PRIMARY KEY CLUSTERED 
	(
		[VesselScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	

	ALTER TABLE [dbo].[M_VesselSchedule] ADD  CONSTRAINT [DF_M_VesselSchedule_Priority]  DEFAULT ((1)) FOR [Priority]


	ALTER TABLE [dbo].[M_VesselSchedule] ADD  CONSTRAINT [DF_M_VesselSchedule_Status]  DEFAULT ((1)) FOR [Status]


	ALTER TABLE [dbo].[M_VesselSchedule] ADD  CONSTRAINT [DF_M_VesselSchedule_CraneScheduled]  DEFAULT ((0)) FOR [CraneScheduled]


	ALTER TABLE [dbo].[M_VesselSchedule] ADD  CONSTRAINT [DF_M_VesselSchedule_IsImported]  DEFAULT ((0)) FOR [IsImported]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Planning 2- Planning SignOff 3 - Deployed' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'M_VesselSchedule', @level2type=N'COLUMN',@level2name=N'Status'


	

END
ELSE 
 Print 'M_VesselSchedule Table Exist'
 
GO
 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_AddTRN_ApprovalRoute')
	DROP PROC prW_AddTRN_ApprovalRoute
GO

----------------------------------------------------------------------------
-- Insert a single record into W_TRN_ApprovalRoute
----------------------------------------------------------------------------
CREATE PROC prW_AddTRN_ApprovalRoute
	@ApprovalModuleID int = NULL,
	@RouteID bigint = NULL,
	@ApplicantId bigint = NULL,
	@AppliedEmployeeId bigint = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@CreatedDate datetime = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdatedDate datetime = NULL
AS

INSERT W_TRN_ApprovalRoute(ApprovalModuleID, RouteID, ApplicantId, AppliedEmployeeId, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate)
VALUES (@ApprovalModuleID, @RouteID, @ApplicantId, @AppliedEmployeeId, @CreatedBy, @CreatedDate, @UpdatedBy, @UpdatedDate)

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.P_ActingIncentiveRates') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[P_ActingIncentiveRates](
	[ActingIncentiveId] [int] IDENTITY(1,1) NOT NULL,
	[PositionId] [bigint] NULL,
	[IncentiveRate] [decimal](18, 5) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_P_ActingIncentiveRates] PRIMARY KEY CLUSTERED 
	(
		[ActingIncentiveId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'P_ActingIncentiveRates Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.P_OvertimeDayNightSettings') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[P_OvertimeDayNightSettings](
	[OTSettingsId] [int] IDENTITY(1,1) NOT NULL,
	[OvertimeId] [bigint] NULL,
	[DayNightType] [int] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_P_OvertimeDayNightSettings] PRIMARY KEY CLUSTERED 
	(
		[OTSettingsId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[P_OvertimeDayNightSettings] ADD  CONSTRAINT [DF_P_OvertimeDayNightSettings_DayNightType]  DEFAULT ((1)) FOR [DayNightType]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - Day 2 - Night' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'P_OvertimeDayNightSettings', @level2type=N'COLUMN',@level2name=N'DayNightType'


END
ELSE 
 Print 'P_OvertimeDayNightSettings Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.P_OvertimeSettings') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[P_OvertimeSettings](
		[OvertimeId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NULL,
		[OTName] [nvarchar](500) NULL,
		[OTDesc] [nvarchar](1000) NULL,
		[PeriodUnit] [int] NULL CONSTRAINT [DF_P_OvertimeSetup_PeriodUnit]  DEFAULT ((1)),
		[PeriodLength] [int] NULL,
		[ApprovalRequired] [bit] NULL,
		[DayNightOvertime] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_P_OvertimeSetup] PRIMARY KEY CLUSTERED 
	(
		[OvertimeId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



END
ELSE 
 Print 'P_OvertimeSettings Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.P_ShiftCosts') AND type in ('U'))
BEGIN	


CREATE TABLE [dbo].[P_ShiftCosts](
	[ShiftCostId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftId] [bigint] NULL,
	[PayCodeId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[ActualHour] [int] NULL,
	[ShiftCost] [decimal](18, 5) NULL,
	[AdjustmentCost] [decimal](18, 5) NULL,
	[TotalCost] [decimal](18, 5) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_P_ShiftCosts] PRIMARY KEY CLUSTERED 
	(
		[ShiftCostId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



END
ELSE 
 Print 'P_ShiftCosts Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_EmployeeLeaves') AND type in ('U'))
BEGIN


	CREATE TABLE [dbo].[S_EmployeeLeaves](
	[LeaveId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[ExceptionCodeId] [bigint] NULL,
	[FromDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[ApprovedBy] [nvarchar](50) NULL,
	[LeaveHours] [bigint] NULL,
	[ShiftId] [bigint] NULL,
	[Remarks] [nvarchar](1000) NULL,
	[PickedTHP] [bit] NULL,
	[Note] [text] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_EmployeeLeaves] PRIMARY KEY CLUSTERED 
	(
		[LeaveId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]



	

END
ELSE 
 Print 'S_EmployeeLeaves Table Exist'
 GO

 /****** Object:  Table [dbo].[S_PublicholidayEmployeeList]    Script Date: 6/19/2018 10:58:03 AM ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_PublicholidayEmployeeList') AND type in ('U'))
begin
	

	CREATE TABLE [dbo].[S_PublicholidayEmployeeList](
	[TranId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[TypeId] [int] NULL,
	[TypeDesc] [nvarchar](500) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_PublicholidayEmployeeList] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - A, 2 - B , 3 - C' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_PublicholidayEmployeeList', @level2type=N'COLUMN',@level2name=N'TypeId'



	
end
else 
 Print 'S_PublicholidayEmployeeList Table Exist'

 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_PublishRoster') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[S_PublishRoster](
	[PublishId] [bigint] IDENTITY(1,1) NOT NULL,
	[TemplateId] [bigint] NULL,
	[PublishDate] [datetime] NULL,
	[PublishUser] [nvarchar](50) NULL,
	[ProcessStatus] [int] NULL,
	[ProcessStart] [datetime] NULL,
	[ProcessEnd] [datetime] NULL,
	[Notes] [nvarchar](500) NULL,
	CONSTRAINT [PK_S_PublishRoster] PRIMARY KEY CLUSTERED 
	(
		[PublishId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0- Completed ,1 - In Progress' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_PublishRoster', @level2type=N'COLUMN',@level2name=N'ProcessStatus'
	
END
ELSE 
 Print 'S_PublishRoster Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_PublishRosterDetails') AND type in ('U'))
BEGIN
	
CREATE TABLE [dbo].[S_PublishRosterDetails](
	[PublishDetId] [bigint] IDENTITY(1,1) NOT NULL,
	[PublishId] [bigint] NULL,
	[TemplateLineId] [bigint] NULL,
	[TemplateFrom] [datetime] NULL,
	[TemplateTo] [datetime] NULL,
	[PublishFrom] [datetime] NULL,
	[PublishTo] [datetime] NULL,
	[ProcessStatus] [int] NULL,
	[ProcessStart] [datetime] NULL,
	[ProcessEnd] [datetime] NULL,
	[Notes] [nvarchar](500) NULL,
	[DefaultForLine] [bit] NULL,
	CONSTRAINT [PK_S_PublishRosterDetails] PRIMARY KEY CLUSTERED 
	(
		[PublishDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	ALTER TABLE [dbo].[S_PublishRosterDetails] ADD  CONSTRAINT [DF_S_PublishRosterDetails_ProcessStatus]  DEFAULT ((2)) FOR [ProcessStatus]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Completed, 1-In Progress , 2 - Not Started' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_PublishRosterDetails', @level2type=N'COLUMN',@level2name=N'ProcessStatus'

END
ELSE 
 Print 'S_PublishRosterDetails Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_RosterGroup') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[S_RosterGroup](
	[RosterGroupId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[GroupName] [nvarchar](500) NULL,
	[GroupDesc] [nvarchar](2000) NULL,
	[Remarks] [nvarchar](2000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_RosterGroup] PRIMARY KEY CLUSTERED 
	(
		[RosterGroupId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	

END
ELSE 
 Print 'S_RosterGroup Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_RosterGroupDetails') AND type in ('U'))
BEGIN
	
	
CREATE TABLE [dbo].[S_RosterGroupDetails](
	[GroupDetId] [bigint] IDENTITY(1,1) NOT NULL,
	[RosterGroupId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_RosterGroupDetails] PRIMARY KEY CLUSTERED 
	(
		[GroupDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'S_RosterGroupDetails Table Exist'

GO
/****** Object:  Table [dbo].[S_SchedulePeriod]    Script Date: 6/19/2018 10:58:03 AM ******/
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_SchedulePeriod') AND type in ('U'))
begin

	CREATE TABLE [dbo].[S_SchedulePeriod](
	[SchedulePeriodId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[ScheduleRuleId] [bigint] NULL,
	[StartDate] [date] NULL,
	[EndDate] [date] NULL,
	[PeriodYear] [int] NULL,
	[PeriodNo] [int] NULL,
	[ReferenceNotes] [text] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_SchedulePeriod] PRIMARY KEY CLUSTERED 
	(
		[SchedulePeriodId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

end
else 
 Print 'S_SchedulePeriod Table Exist'

 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ScheduleRuleOU') AND type in ('U'))
BEGIN



	CREATE TABLE [dbo].[S_ScheduleRuleOU](
		[ScheduleRuleOU] [bigint] IDENTITY(1,1) NOT NULL,
		[ScheduleRuleId] [bigint] NULL,
		[OUId] [bigint] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ScheduleRuleOU] PRIMARY KEY CLUSTERED 
	(
		[ScheduleRuleOU] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]



END
ELSE 
 Print 'S_ScheduleRuleOU Table Exist'
GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ScheduleRulePeriod') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[S_ScheduleRulePeriod](
		[SCRPeriodId] [bigint]  IDENTITY(1,1) NOT NULL,
		[ScheduleRuleId] [bigint] NULL,
		[ContDaysOnMin] [int] NULL,
		[ContDaysOnMax] [int] NULL,
		[ContDaysOffMin] [int] NULL,
		[ContDaysOffMax] [int] NULL,
		[MinHourRest] [int] NULL,
		[OrderIndex] [int] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ScheduleRulePeriod] PRIMARY KEY CLUSTERED 
	(
		[SCRPeriodId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	
END
ELSE 
 Print 'S_ScheduleRulePeriod Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ScheduleRulePeriodShiftbands') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[S_ScheduleRulePeriodShiftbands](
		[SCRPeriodShiftId] [bigint] IDENTITY(1,1) NOT NULL,
		[SCRPeriodId] [bigint] NULL,
		[ShiftBandId] [bigint] NULL,
		[BandIndex] [int] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_ScheduleRulePeriodShiftbands] PRIMARY KEY CLUSTERED 
	(
				   [SCRPeriodShiftId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
	
	
END
ELSE 
 Print 'S_ScheduleRulePeriod Table Exist'


GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ScheduleRules') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[S_ScheduleRules](
		[ScheduleRuleId] [bigint] IDENTITY(1,1) NOT NULL,
		[Name] [nvarchar](500) NULL,
		[Description] [nvarchar](1000) NULL,
		[ValidFrom] [date] NULL,
		[ValidTo] [date] NULL,
		[PeriodLength] [int] NULL,
		[ShiftLengthMin] [int] NULL,
		[ShiftLengthMax] [int] NULL,
		[DaysPerPeriodMin] [int] NULL,
		[DaysPerPeriodMax] [int] NULL,
		[TimePerPeriodMin] [int] NULL,
		[TimePerPeriodMax] [int] NULL,
		[ContDaysScheduleOnMin] [int] NULL,
		[ContDaysScheduleOnMax] [int] NULL,
		[ContDaysScheduleOffMin] [int] NULL,
		[ContDaysScheduleOffMax] [int] NULL,
		[MinRestTime] [int] NULL,
		[RestDelimiter] [bit] NULL,
		[OffDaysPerPeriodMin] [int] NULL,
		[OffDaysPerPeriodMax] [int] NULL,
		[IsOffDaysMaxForced] [bit] NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ScheduleRules] PRIMARY KEY CLUSTERED 
	(
		[ScheduleRuleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'S_ScheduleRules Table Exist'
 
 GO
 

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ShiftExceptions') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[S_ShiftExceptions](
		[ShiftExceptionId] [bigint] IDENTITY(1,1) NOT NULL,
		[ShiftId] [bigint] NOT NULL,
		[ExceptionCodeId] [bigint] NOT NULL,
		[StartTime] [datetime] NOT NULL,
		[EndTime] [datetime] NOT NULL,
		[ApprovalStatus] [int] NULL,
		[Remarks] [nvarchar](max) NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ShiftExceptions] PRIMARY KEY CLUSTERED 
	(
		[ShiftExceptionId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = Pending Approval, 2 = Approved' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_ShiftExceptions', @level2type=N'COLUMN',@level2name=N'ApprovalStatus'	
END
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_Shifts') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[S_Shifts](
	[ShiftId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[TemplateId] [bigint] NULL,
	[RoleId] [bigint] NULL,
	[RosterGroupId] [bigint] NULL,
	[ShiftBandId] [bigint] NULL,
	[OTStartTime] [datetime] NULL,
	[ShiftStartTime] [datetime] NOT NULL,
	[ShiftEndTime] [datetime] NOT NULL,
	[OTEndTime] [datetime] NULL,
	[ActualStartTime] [datetime] NOT NULL,
	[ActualEndTime] [datetime] NOT NULL,
	[PreparationMins] [int] NULL,
	[DepreparationMins] [int] NULL,
	[OnCallShift] [bit] NULL,
	[Notes] [nvarchar](500) NULL,
	[CombinationShiftId] [bigint] NULL,
	[ReconTime] [datetime] NULL,
	[ReconStatusId] [int] NULL,
	[RPGId] [int] NULL,
	[ReconFailureReasonId] [int] NULL,
	[ReconFailureReasonDetail] [nvarchar](1000) NULL,
	[Reconciled] [bit] NULL,
	[InStatus] [int] NULL,
	[OutStatus] [int] NULL,
	[InTime]	[datetime] NULL,
	[OutTime]	[datetime] NULL,
	[PickedByTHP] [bit] NULL,
	[Deployed] [bit] NULL,
	[LeaveId] [bigint] NULL,
	[ShiftCost] [decimal](18, 4) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_Shifts] PRIMARY KEY CLUSTERED 
	(
		[ShiftId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_PreparationMins]  DEFAULT ((0)) FOR [PreparationMins]

	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_DepreparationMins]  DEFAULT ((0)) FOR [DepreparationMins]

	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_OnCallShift]  DEFAULT ((0)) FOR [OnCallShift]

	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_Reconciled]  DEFAULT ((0)) FOR [Reconciled]

	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_PickedByTHP]  DEFAULT ((0)) FOR [PickedByTHP]
	
	ALTER TABLE [dbo].[S_Shifts] ADD  CONSTRAINT [DF_S_Shifts_Deployed]  DEFAULT ((0)) FOR [Deployed]

	
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - not oncall chift, 1- oncall shift' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'OnCallShift'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Not Reconciled 1 - Reconciled' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'Reconciled'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Not Picked 1 - Picked' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'PickedByTHP'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - not deployed 1- deployed' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'Deployed'
	
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - OnTime, 1- EarlyIn, 2- LateIN=n' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'InStatus'
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - OnTime, 1- EarlyIn, 2- LateIN=n' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'OutStatus'
END
ELSE 
 Print 'S_Shifts Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ShiftValidationCodes') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_ShiftValidationCodes](
	[ErrorId] [int] IDENTITY(1,1) NOT NULL,
	[ValidationCode] [nvarchar](50) NULL,
	[ValidationDesc] [nvarchar](1000) NULL,
	[ValidationMessage] [text] NULL,
	[ColorCode] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ShiftValidationCodes] PRIMARY KEY CLUSTERED 
	(
		[ErrorId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]


END
ELSE 
 Print 'S_ShiftValidationCodes Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_ShiftValidations') AND type in ('U'))
BEGIN	
	CREATE TABLE [dbo].[S_ShiftValidations](
	[ValidationId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[SchedulePeriodId] [bigint] NULL,
	[ShiftDate] [datetime] NULL,
	[IsError] [bit] NULL,
	[ErrorId] [int] NULL,
	[ErrorDesc] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_ShiftValidations] PRIMARY KEY CLUSTERED 
	(
		[ValidationId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'S_ShiftValidations Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_TemplateRoster') AND type in ('U'))
BEGIN
	
	
CREATE TABLE [dbo].[S_TemplateRoster](
	[TemplateId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[TemplateName] [nvarchar](100) NULL,
	[TemplateDesc] [nvarchar](1000) NULL,
	[NoOfDays] [int] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[FirstPublishDate] [datetime] NULL,
	[LastPublishDate] [datetime] NULL,
	[PublishFrom] [datetime] NULL,
	[PublishTo] [datetime] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_TemplateRoster] PRIMARY KEY CLUSTERED 
	(
		[TemplateId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'S_TemplateRoster Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_TemplateRosterLine') AND type in ('U'))
BEGIN
	

 CREATE TABLE [dbo].[S_TemplateRosterLine](
	[TemplateLineId] [bigint] IDENTITY(1,1) NOT NULL,
	[TemplateId] [bigint] NULL,
	[LineType] [int] NULL,
	[LineNumber] [int] NULL,
	[RosterGroupId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[FirstPublishDate] [datetime] NULL,
	[LastPublishDate] [datetime] NULL,
	[PublishFrom] [datetime] NULL,
	[PublishTo] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_T_TemplateRosterLine] PRIMARY KEY CLUSTERED 
	(
		[TemplateLineId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Roster group, 2 - Employee' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_TemplateRosterLine', @level2type=N'COLUMN',@level2name=N'LineType'


END
ELSE 
 Print 'S_TemplateRosterLine Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_TemplateRoster_Shifts') AND type in ('U'))
BEGIN
	
	CREATE TABLE [dbo].[S_TemplateRoster_Shifts](
	[ShiftId] [bigint] IDENTITY(1,1) NOT NULL,
	[TemplateId] [bigint] NULL,
	[TemplateLineId] [bigint] NULL,
	[ShiftBandId] [bigint] NULL,
	[OnCallShift] [bit] NULL,
	[Notes] [nvarchar](1000) NULL,
	[RowNumber] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_TemplateRoster_Shifts] PRIMARY KEY CLUSTERED 
	(
		[ShiftId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'S_TemplateRoster_Shifts Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_THPEmployeeDetails') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPEmployeeDetails](
	[TranId] [bigint] IDENTITY(1,1) NOT NULL,
	[THPPeriodId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[ShiftDate] [datetime] NULL,
	[ShiftId] [bigint] NULL,
	[LeaveId] [bigint] NULL,
	[ShiftCounter] [decimal](18, 2) NULL,
	[ActivityCounter] [decimal](18, 2) NULL,
	[LeaveCounter] [decimal](18, 2) NULL,
	[NormalHour] [decimal](18, 2) NULL,
	[OTHour] [decimal](18, 2) NULL,
	[THPProcessDate] [datetime] NULL,
	[THPNotes] [text] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_THPEmployeeDetails] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE 
 Print 'S_THPEmployeeDetails Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_THPEmployeePeriods') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPEmployeePeriods](
	[THPPeriodId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[THPSettingsId] [bigint] NULL,
	[EmployeeId] [bigint] NULL,
	[PeriodStart] [date] NULL,
	[PeriodEnd] [date] NULL,
	[PeriodUnit] [int] NULL,
	[PeriodLength] [int] NULL,
	[ShiftCounter] [decimal](18, 2) NULL,
	[LeaveCounter] [decimal](18, 2) NULL,
	[ActivityCounter] [decimal](18, 2) NULL,
	[NormalHourCounter] [decimal](18, 2) NULL,
	[OTHourCounter] [decimal](18, 2) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_THPEmployeePeriods] PRIMARY KEY CLUSTERED 
	(
		[THPPeriodId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Days 2. Week 3 - Monthly' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_THPEmployeePeriods', @level2type=N'COLUMN',@level2name=N'PeriodUnit'

END
ELSE 
 Print 'S_THPEmployeePeriods Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_THPSettingRosterGroups') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPSettingRosterGroups](
	[THPEMPId] [bigint] IDENTITY(1,1) NOT NULL,
	[THPSettingId] [bigint] NULL,
	[RosterGroupId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_THPSettingRosterGroups] PRIMARY KEY CLUSTERED 
	(
		[THPEMPId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'S_THPSettingRosterGroups Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_THPSettings') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPSettings](
	[THPSettingId] [bigint] IDENTITY(1,1) NOT NULL,
	[OUId] [bigint] NULL,
	[THPSettingsName] [nvarchar](255) NOT NULL,
	[StartDate] [date] NULL,
	[PeriodUnit] [int] NULL,
	[PeriodLength] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_THPSettings] PRIMARY KEY CLUSTERED 
	(
		[THPSettingId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[S_THPSettings] ADD  CONSTRAINT [DF_S_THPSettings_PeriodUnit]  DEFAULT ((1)) FOR [PeriodUnit]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1- Days 2. Week 3 - Monthly' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_THPSettings', @level2type=N'COLUMN',@level2name=N'PeriodUnit'

END
ELSE 
 Print 'S_THPSettings Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TA_ExceptionCodes') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[TA_ExceptionCodes](
	[TAExceptionId] [int] IDENTITY(1,1) NOT NULL,
	[TAException] [nvarchar](1000) NULL,
	[ColorCode] [nvarchar](50) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_TA_Exceptions] PRIMARY KEY CLUSTERED 
	(
		[TAExceptionId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
ELSE 
 Print 'TA_ExceptionCodes Table Exist'
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TA_Rawclocking') AND type in ('U'))
begin

CREATE TABLE [dbo].[TA_Rawclocking](
	[ClockingId] [bigint] IDENTITY(1,1) NOT NULL,
	[TypeId] [int] NULL,
	[CardNo] [nvarchar](50) NULL,
	[TerminalName] [nvarchar](50) NULL,
	[SwipeDateTime] [datetime] NULL,
	[EmployeeNo] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[CollectionDateTime] [datetime] NULL,
	[Allocated] [bit] NULL,
	[ReconDate] [datetime] NULL,
	[ReconBy] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_TA_Rawclocking] PRIMARY KEY CLUSTERED 
	(
		[ClockingId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[TA_Rawclocking] ADD  CONSTRAINT [DF_TA_Rawclocking_Allocated]  DEFAULT ((0)) FOR [Allocated]


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 - IN, 2- Out ' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Rawclocking', @level2type=N'COLUMN',@level2name=N'TypeId'


	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Not Allocated 1 - Allocated' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'TA_Rawclocking', @level2type=N'COLUMN',@level2name=N'Allocated'



end
else 
 Print 'TA_Rawclocking Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TA_RPGConfig') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[TA_RPGConfig](
		[RPGId] [bigint] IDENTITY(1,1) NOT NULL,
		[RPGName] [nvarchar](500) NOT NULL,
		[Description] [nvarchar](1000) NULL,
		[ReconShiftInEarly] [int] NULL,
		[ReconShiftInLate] [int] NULL,
		[ReconShiftOutEarly] [int] NULL,
		[ReconShiftOutLate] [int] NULL,
		[ReconGranularShiftInEarly] [int] NULL,
		[ReconGranularShiftInLate] [int] NULL,
		[ReconGranularShiftOutEarly] [int] NULL,
		[ReconGranularShiftOutLate] [int] NULL,
		[ReconToPlanShiftInEarly] [int] NULL,
		[ReconToPlanShiftInLate] [int] NULL,
		[ReconToPlanShiftOutEarly] [int] NULL,
		[ReconToPlanShiftOutLate] [int] NULL,
		[RoundingGranularity] [int] NULL,
		[RoundingDirectionUp] [int] NULL,
		[ClockingIdentificationMethod] [int] NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_TA_RPGConfig] PRIMARY KEY CLUSTERED 
	(
		[RPGId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	ALTER TABLE [dbo].[TA_RPGConfig] ADD  CONSTRAINT [DF_TA_RPGConfig_RoundingGranularity]  DEFAULT ((0)) FOR [RoundingGranularity]
	
	ALTER TABLE [dbo].[TA_RPGConfig] ADD  CONSTRAINT [DF_TA_RPGConfig_RoundingDirectionUp]  DEFAULT ((0)) FOR [RoundingDirectionUp]
	
	ALTER TABLE [dbo].[TA_RPGConfig] ADD  CONSTRAINT [DF_TA_RPGConfig_ActiveStatus]  DEFAULT ((1)) FOR [ActiveStatus]

END
ELSE 
 Print 'TA_RPGConfig Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TA_RPGOU') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[TA_RPGOU](
		[RPGOUId] [bigint] IDENTITY(1,1) NOT NULL,
		[RPGId] [bigint] NOT NULL,
		[OUId] [bigint] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_TA_RPGOU] PRIMARY KEY CLUSTERED 
	(
		[RPGOUId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'TA_RPGOU Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.TA_RPGRoles') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[TA_RPGRoles](
		[RPGRoleId] [bigint] IDENTITY(1,1) NOT NULL,
		[RPGId] [bigint] NOT NULL,
		[RoleId] [bigint] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_TA_RPGRoles] PRIMARY KEY CLUSTERED 
	(
		[RPGRoleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'TA_RPGRoles Table Exist'
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.T_Attachments') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[T_Attachments](
		[AttachmentId] [bigint] IDENTITY(1,1) NOT NULL,
		[AttachmentSourceId] [bigint] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[AttachmentContents] [nvarchar](max) NULL,
		[AttachmentName] [nvarchar](255) NOT NULL,
		[AttachmentSavedAs] [nvarchar](255) NOT NULL,
		[AttachmentType] [nvarchar](100) NOT NULL,
		[ModuleName] [nvarchar](50) NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_T_Attachments] PRIMARY KEY CLUSTERED 
	(
		[AttachmentId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'For Now Only Referes to L_Leaves.LeaveId' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_Attachments', @level2type=N'COLUMN',@level2name=N'AttachmentSourceId'
END
ELSE 
 Print 'T_Attachments Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.T_SystemTask') AND type in ('U'))
begin
	
	CREATE TABLE [dbo].[T_SystemTask](
	[SystemTaskId] [int] IDENTITY(1,1) NOT NULL,
	[SystemTaskName] [nvarchar](500) NULL,
	[SystemTaskTypeId] [int] NULL,
	[InterfaceId] [int] NULL,
	[Description] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_T_SystemTask] PRIMARY KEY CLUSTERED 
	(
		[SystemTaskId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
	ALTER TABLE [dbo].[T_SystemTask] ADD  CONSTRAINT [DF_T_SystemTask_SystemTaskTypeId]  DEFAULT ((0)) FOR [SystemTaskTypeId]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Normal Process, 1- Interface' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_SystemTask', @level2type=N'COLUMN',@level2name=N'SystemTaskTypeId'

end
else 
 Print 'T_SystemTask Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.T_SystemTaskSchedule') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[T_SystemTaskSchedule](
		[SystemTaskScheduleId] [bigint] IDENTITY(1,1) NOT NULL,
		[SystemTaskId] [int] NOT NULL,
		[TaskType] [int] NOT NULL,
		[TaskInterval] [int] NOT NULL,
		[TaskFrequency] [int] NULL,
		[ScheduledMinute] [int] NULL,
		[ScheduledHour] [int] NULL,
		[ScheduledTime] [nvarchar](10) NULL,
		[CronExpression] [nvarchar](255) NULL,
		[StartDate] [datetime] NULL,
		[EndDate] [datetime] NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_T_SystemTaskSchedule] PRIMARY KEY CLUSTERED 
	(
		[SystemTaskScheduleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Once = 1, Daily = 2, Weekly = 3, Monthly = 4' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_SystemTaskSchedule', @level2type=N'COLUMN',@level2name=N'TaskType'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Minutes = 1, Hour = 2, Time = 3 ( Ex: Every 1 Min, Every 2 Hours, At 1330hrs)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_SystemTaskSchedule', @level2type=N'COLUMN',@level2name=N'TaskInterval'

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Jan - Dec = 1 - 2, Sun - Sat = 0 - 6' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'T_SystemTaskSchedule', @level2type=N'COLUMN',@level2name=N'TaskFrequency'
	
	Print 'T_SystemTaskSchedule Table Created'
END
Else
	Print 'T_SystemTaskSchedule Table Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_ApprovalStatus') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[W_ApprovalStatus](
	[ApprovalStatusId] [bigint] IDENTITY(1,1) NOT NULL,
	[ApprovalStatus] [nvarchar](50) NOT NULL,
	[ApprovalStatusDesc] [nvarchar](50) NULL
	 CONSTRAINT [PK_W_Approval_Status] PRIMARY KEY CLUSTERED 
	(
		[ApprovalStatusId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'W_ApprovalStatus Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_Modules') AND type in ('U'))
BEGIN
	

	CREATE TABLE [dbo].[W_Modules](
	[ModuleId] [int] IDENTITY(1,1) NOT NULL,
	[ModuleName] [nvarchar](500) NULL,
	[ModuleDesc] [nvarchar](1000) NULL,
	[TableName] [nvarchar](500) NULL,
	[TransIdName] [nvarchar](50) NULL,
	[ViewURL] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_Modules] PRIMARY KEY CLUSTERED 
	(
		[ModuleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

	
END
ELSE 
 Print 'W_Modules Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_TRN_ApprovalRoute') AND type in ('U'))
BEGIN	


	CREATE TABLE [dbo].[W_TRN_ApprovalRoute](
	[TransRouteID] [bigint] IDENTITY(1,1) NOT NULL,
	[ApprovalModuleID] [int] NULL,
	[RouteID] [bigint] NULL,
	[RequestTransId] [bigint] NULL, -- ID From Leave Request, Day In Lieu, Time Off Or Time Attendance Request
	[ApplicantId] [bigint] NULL,
	[AppliedEmployeeId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_TRN_ApprovalRoute] PRIMARY KEY CLUSTERED 
	(
		[TransRouteID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'W_TRN_ApprovalRoute Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_TRN_Approvals') AND type in ('U'))
BEGIN	


	CREATE TABLE [dbo].[W_TRN_Approvals](
	[TranId] [bigint] IDENTITY(1,1) NOT NULL,
	[TransRouteID] [bigint] NULL,
	[ApprovalModuleID] [int] NULL,
	[RequestTransID] [bigint] NULL,
	[RouteID] [bigint] NULL,
	[ApplicantId] [bigint] NULL,
	[ApproverId] [bigint] NULL,
	[RouteLevel] [int] NULL,
	[ApprovalRequirement] [int] NULL,
	[AppliedDate] [datetime] NULL,
	[AppliedEmployeeId] [bigint] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_TRN_Approvals] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE 
 Print 'W_TRN_Approvals Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_TRN_Approval_RouteDetails') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[W_TRN_Approval_RouteDetails](
	[TransRouteDetID] [bigint] IDENTITY(1,1) NOT NULL,
	[TransRouteID] [bigint] NULL,
	[ApprovalTransID] [bigint] NULL,
	[ApplicantId] [bigint] NULL,
	[AppliedDate] [datetime] NULL,
	[ApproverId] [bigint] NULL,
	[RouteLevel] [int] NULL,
	[ApprovalRequirement] [int] NULL,
	[UserAction] [int] NULL, -- Retrieve From Approval Status Enum
	[ActionDate] [datetime] NULL,
	[Remarks] [nvarchar](1000) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_TRN_APPROVAL_ROUTEDETAILS] PRIMARY KEY CLUSTERED 
	(
		[TransRouteDetID] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'W_TRN_Approval_RouteDetails Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_WorkflowRoute') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[W_WorkflowRoute](
		[RouteId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NULL,
		[RouteName] [nvarchar](500) NULL,
		[RouteDesc] [nvarchar](1000) NULL,
		[ActiveStatus] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_WorkflowRoute] PRIMARY KEY CLUSTERED 
	(
		[RouteId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

	
END
ELSE 
 Print 'W_WorkflowRoute Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.W_WorkflowRouteDetails') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[W_WorkflowRouteDetails](
		[RouteDetId] [bigint] IDENTITY(1,1) NOT NULL,
		[RouteId] [bigint] NULL,
		[EmployeeId] [bigint] NULL,
		[RouteLevel] [int] NULL,
		[ApprovalRequirement] [int] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_W_WorkflowRouteDetails] PRIMARY KEY CLUSTERED 
	(
		[RouteDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'W_WorkflowRouteDetails Table Exist'
 
 GO
-- Add [EmployeeId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_Shifts') AND Name = N'EmployeeId')
BEGIN
	ALTER TABLE [dbo].[A_Shifts] ADD [EmployeeId] [BigInt] NULL 
END
ELSE
	Print 'Column [A_Shifts.EmployeeId] Already Exists'
GO

-- Add [ActionBy] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_Shifts') AND Name = N'ActionBy')
BEGIN
	ALTER TABLE [dbo].[A_Shifts] ADD [ActionBy] nVarchar(50) NULL 
END
ELSE
	Print 'Column [A_Shifts.ActionBy] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_Employee_C_OrganizationNode') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_Employee]  WITH CHECK ADD  CONSTRAINT [FK_C_Employee_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[C_Employee] CHECK CONSTRAINT [FK_C_Employee_C_OrganizationNode]


END
ELSE 
 Print 'FK_C_Employee_C_OrganizationNode Table Exist'

GO 
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_Employee_D_EmploymentBasis') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[C_Employee]  WITH CHECK ADD  CONSTRAINT [FK_C_Employee_D_EmploymentBasis] FOREIGN KEY([EmploymentBasisId])
	REFERENCES [dbo].[D_EmploymentBasis] ([EmploymentBasisId])


	ALTER TABLE [dbo].[C_Employee] CHECK CONSTRAINT [FK_C_Employee_D_EmploymentBasis]

END
ELSE 
 Print 'FK_C_Employee_D_EmploymentBasis Table Exist'
 
GO


 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeDiciplinary_C_Employee') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeDiciplinary]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeDiciplinary_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])


	ALTER TABLE [dbo].[C_EmployeeDiciplinary] CHECK CONSTRAINT [FK_C_EmployeeDiciplinary_C_Employee]


END
ELSE 
 Print 'FK_C_EmployeeDiciplinary_C_Employee Table Exist'
 
 GO
 
  
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeDiciplinary_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[C_EmployeeDiciplinary]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeDiciplinary_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[C_EmployeeDiciplinary] CHECK CONSTRAINT [FK_C_EmployeeDiciplinary_C_OrganizationNode]	

END
ELSE 
 Print 'FK_C_EmployeeDiciplinary_C_OrganizationNode Table Exist'
 
GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeExcludeSkills_C_EmployeeExcludeSkills') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[C_EmployeeExcludeSkills]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeExcludeSkills_C_EmployeeExcludeSkills] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])


	ALTER TABLE [dbo].[C_EmployeeExcludeSkills] CHECK CONSTRAINT [FK_C_EmployeeExcludeSkills_C_EmployeeExcludeSkills]


END
ELSE 
 Print 'FK_C_EmployeeExcludeSkills_C_EmployeeExcludeSkills Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeExcludeSkills_D_Skill') AND type in ('F'))
BEGIN



	ALTER TABLE [dbo].[C_EmployeeExcludeSkills]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeExcludeSkills_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])
	

	ALTER TABLE [dbo].[C_EmployeeExcludeSkills] CHECK CONSTRAINT [FK_C_EmployeeExcludeSkills_D_Skill]
	

END
ELSE 
 Print 'FK_C_EmployeeExcludeSkills_D_Skill Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeMovement_C_EmployeeMovement') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeMovement]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])
	

	ALTER TABLE [dbo].[C_EmployeeMovement] CHECK CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement]


	ALTER TABLE [dbo].[C_EmployeeMovement]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement1] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[C_EmployeeMovement] CHECK CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement1]

END
ELSE 
 Print 'FK_C_EmployeeMovement_C_EmployeeMovement Table Exist'
 
 GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeMovement_C_EmployeeMovement1') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeMovement]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement1] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[C_EmployeeMovement] CHECK CONSTRAINT [FK_C_EmployeeMovement_C_EmployeeMovement1]

END
ELSE 
 Print 'FK_C_EmployeeMovement_C_EmployeeMovement1 Table Exist'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_C_EmployeeOU_IsPrimaryOU') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeOU] ADD  CONSTRAINT [DF_C_EmployeeOU_IsPrimaryOU]  DEFAULT ((0)) FOR [IsPrimaryOU]
END
ELSE
	Print 'DF_C_EmployeeOU_IsPrimaryOU Already Exists'

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_C_EmployeeOU_ActiveStatus') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeOU] ADD  CONSTRAINT [DF_C_EmployeeOU_ActiveStatus]  DEFAULT ((1)) FOR [ActiveStatus]
END
ELSE
	Print 'DF_C_EmployeeOU_ActiveStatus Already Exists'

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeOU_C_Employee') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeOU]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeOU_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])
END
ELSE
	Print 'FK_C_EmployeeOU_C_Employee Already Exists'

ALTER TABLE [dbo].[C_EmployeeOU] CHECK CONSTRAINT [FK_C_EmployeeOU_C_Employee]
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeOU]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
END
ELSE
	Print 'FK_C_EmployeeOU_C_OrganizationNode Already Exists'

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeOU] CHECK CONSTRAINT [FK_C_EmployeeOU_C_OrganizationNode]
END
ELSE
	Print 'FK_C_EmployeeOU_C_OrganizationNode Already Exists'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeRoles_C_Employee') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_EmployeeRoles]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeRoles_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])


	ALTER TABLE [dbo].[C_EmployeeRoles] CHECK CONSTRAINT [FK_C_EmployeeRoles_C_Employee]

END
ELSE 
 Print 'FK_C_EmployeeRoles_C_Employee Table Exist'
 
 GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeRoles_D_Roles') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_EmployeeRoles]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeRoles_D_Roles] FOREIGN KEY([RoleId])
	REFERENCES [dbo].[D_Roles] ([RoleId])


	ALTER TABLE [dbo].[C_EmployeeRoles] CHECK CONSTRAINT [FK_C_EmployeeRoles_D_Roles]


END
ELSE 
 Print 'FK_C_EmployeeRoles_D_Roles Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeSkills_C_Employee') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[C_EmployeeSkills]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeSkills_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])


	ALTER TABLE [dbo].[C_EmployeeSkills] CHECK CONSTRAINT [FK_C_EmployeeSkills_C_Employee]


	ALTER TABLE [dbo].[C_EmployeeSkills]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeSkills_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])


	ALTER TABLE [dbo].[C_EmployeeSkills] CHECK CONSTRAINT [FK_C_EmployeeSkills_D_Skill]

END
ELSE 
 Print 'FK_C_EmployeeSkills_C_Employee Table Exist'
 
 GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeSkills_D_Skill') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[C_EmployeeSkills]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeSkills_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])


	ALTER TABLE [dbo].[C_EmployeeSkills] CHECK CONSTRAINT [FK_C_EmployeeSkills_D_Skill]

END
ELSE 
 Print 'FK_C_EmployeeSkills_D_Skill Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.C_EmployeeSkills') AND Name = N'IsActingSkill')
BEGIN
	ALTER TABLE [dbo].[C_EmployeeSkills] ADD [IsActingSkill] [Bit] NULL
END
ELSE
	Print 'Column [IsActingSkill] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeWorkflow_C_Employee') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_EmployeeWorkflow]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeWorkflow_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])
END
ELSE 
	Print 'FK_C_EmployeeWorkflow_C_Employee Table Exist'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeWorkflow_W_Modules') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeWorkflow]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeWorkflow_W_Modules] FOREIGN KEY([ModuleId])
	REFERENCES [dbo].[W_Modules] ([ModuleId])
END
ELSE
	Print 'FK_C_EmployeeWorkflow_W_Modules Table Exist'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeWorkflow_W_WorkflowRoute') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeWorkflow]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeWorkflow_W_WorkflowRoute] FOREIGN KEY([RouteId])
	REFERENCES [dbo].[W_WorkflowRoute] ([RouteId])
END
ELSE
	Print 'FK_C_EmployeeWorkflow_W_WorkflowRoute Table Exist'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_InterfaceConfig_C_Interfaces') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_InterfaceConfig]  WITH CHECK ADD  CONSTRAINT [FK_C_InterfaceConfig_C_Interfaces] FOREIGN KEY([InterfaceId])
	REFERENCES [dbo].[C_Interfaces] ([InterfaceId])

	ALTER TABLE [dbo].[C_InterfaceConfig] CHECK CONSTRAINT [FK_C_InterfaceConfig_C_Interfaces]
	
END
Else
	Print 'FK_C_InterfaceConfig_C_Interfaces Constraint Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_InterfaceLog_C_Interfaces') AND type in ('F'))
begin

	ALTER TABLE [dbo].[C_InterfaceLog]  WITH CHECK ADD  CONSTRAINT [FK_C_InterfaceLog_C_Interfaces] FOREIGN KEY([InterfaceId])
	REFERENCES [dbo].[C_Interfaces] ([InterfaceId])

	ALTER TABLE [dbo].[C_InterfaceLog] CHECK CONSTRAINT [FK_C_InterfaceLog_C_Interfaces]

	
end
else 
 Print 'FK_C_InterfaceLog_C_Interfaces Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_InterfaceLog_C_InterfaceTransactions') AND type in ('F'))
begin
	ALTER TABLE [dbo].[C_InterfaceLog]  WITH CHECK ADD  CONSTRAINT [FK_C_InterfaceLog_C_InterfaceTransactions] FOREIGN KEY([TranId])
	REFERENCES [dbo].[C_InterfaceTransactions] ([TranId])

	ALTER TABLE [dbo].[C_InterfaceLog] CHECK CONSTRAINT [FK_C_InterfaceLog_C_InterfaceTransactions]


	
end
else 
 Print 'FK_C_InterfaceLog_C_InterfaceTransactions Table Exist'
 
 GO
 
 
 

 
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_InterfaceTransactions_C_Interfaces') AND type in ('F'))
begin

	ALTER TABLE [dbo].[C_InterfaceTransactions]  WITH CHECK ADD  CONSTRAINT [FK_C_InterfaceTransactions_C_Interfaces] FOREIGN KEY([InterfaceId])
	REFERENCES [dbo].[C_Interfaces] ([InterfaceId])

	ALTER TABLE [dbo].[C_InterfaceTransactions] CHECK CONSTRAINT [FK_C_InterfaceTransactions_C_Interfaces]

	
end
else 
 Print 'FK_C_InterfaceTransactions_C_Interfaces Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.C_Menu') AND Name = N'IsHorizontalMenuItem')
BEGIN
	ALTER TABLE [dbo].[C_Menu] ADD [IsHorizontalMenuItem] [bit] NULL 
END
ELSE
	Print 'Column [IsHorizontalMenuItem] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.default_constraints WHERE object_id = OBJECT_ID(N'dbo.DF_CHK_IsHorizontalMenuItem') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[C_Menu] ADD CONSTRAINT DF_CHK_IsHorizontalMenuItem DEFAULT 0 FOR IsHorizontalMenuItem
END
ELSE
	Print 'Check Constraint [DF_CHK_IsHorizontalMenuItem] Already Exists.'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_UserAudit_C_UserAudit') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_UserAudit]  WITH CHECK ADD  CONSTRAINT [FK_C_UserAudit_C_UserAudit] FOREIGN KEY([UserId])
	REFERENCES [dbo].[C_User] ([UserID])

	ALTER TABLE [dbo].[C_UserAudit] CHECK CONSTRAINT [FK_C_UserAudit_C_UserAudit]

END
ELSE
	Print 'FK_C_UserAudit_C_UserAudit Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_UserSecurityRoles_C_SecurityRole') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_UserSecurityRoles]  WITH CHECK ADD  CONSTRAINT [FK_C_UserSecurityRoles_C_SecurityRole] FOREIGN KEY([SecurityRoleId])
	REFERENCES [dbo].[C_SecurityRole] ([SecurityRoleID])


	ALTER TABLE [dbo].[C_UserSecurityRoles] CHECK CONSTRAINT [FK_C_UserSecurityRoles_C_SecurityRole]
	
END
ELSE 
 Print 'FK_C_UserSecurityRoles_C_SecurityRole Table Exist'
 
 GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_UserSecurityRoles_C_User') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[C_UserSecurityRoles]  WITH CHECK ADD  CONSTRAINT [FK_C_UserSecurityRoles_C_User] FOREIGN KEY([UserId])
	REFERENCES [dbo].[C_User] ([UserID])
	

	ALTER TABLE [dbo].[C_UserSecurityRoles] CHECK CONSTRAINT [FK_C_UserSecurityRoles_C_User]


END
ELSE 
 Print 'FK_C_UserSecurityRoles_C_User Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_EmploymentBasisOU_D_EmploymentBasis') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[D_EmploymentBasisOU]  WITH CHECK ADD  CONSTRAINT [FK_D_EmploymentBasisOU_D_EmploymentBasis] FOREIGN KEY([EmploymentBasisId])
	REFERENCES [dbo].[D_EmploymentBasis] ([EmploymentBasisId])
	

	ALTER TABLE [dbo].[D_EmploymentBasisOU] CHECK CONSTRAINT [FK_D_EmploymentBasisOU_D_EmploymentBasis]

END
ELSE 
 Print 'FK_D_EmploymentBasisOU_D_EmploymentBasis Table Exist'IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ExceptionCodes_D_ExceptionCodes') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ExceptionCodes]  WITH CHECK ADD  CONSTRAINT [FK_D_ExceptionCodes_D_ExceptionCodes] FOREIGN KEY([ExceptionTypeId])
	REFERENCES [dbo].[D_ExceptionType] ([ExceptionTypeId])
	
	ALTER TABLE [dbo].[D_ExceptionCodes] CHECK CONSTRAINT [FK_D_ExceptionCodes_D_ExceptionCodes]
END
ELSE 
 Print 'FK_D_ExceptionCodes_D_ExceptionCodes Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ExceptionCodesOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ExceptionCodesOU]  WITH CHECK ADD  CONSTRAINT [FK_D_ExceptionCodesOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_ExceptionCodesOU] CHECK CONSTRAINT [FK_D_ExceptionCodesOU_C_OrganizationNode]

END
ELSE 
 Print 'FK_D_ExceptionCodesOU_C_OrganizationNode Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ExceptionCodesOU_D_ExceptionCodes') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ExceptionCodesOU]  WITH CHECK ADD  CONSTRAINT [FK_D_ExceptionCodesOU_D_ExceptionCodes] FOREIGN KEY([ExceptionCodeId])
	REFERENCES [dbo].[D_ExceptionCodes] ([ExceptionCodeId])


	ALTER TABLE [dbo].[D_ExceptionCodesOU] CHECK CONSTRAINT [FK_D_ExceptionCodesOU_D_ExceptionCodes]
	
END
ELSE 
 Print 'FK_D_ExceptionCodesOU_D_ExceptionCodes Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_PayCodeOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_PayCodeOU]  WITH CHECK ADD  CONSTRAINT [FK_D_PayCodeOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_PayCodeOU] CHECK CONSTRAINT [FK_D_PayCodeOU_C_OrganizationNode]

END
ELSE 
 Print 'FK_D_PayCodeOU_C_OrganizationNode Table Exist'
 
GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_PayCodeOU_D_PayCodes') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_PayCodeOU]  WITH CHECK ADD  CONSTRAINT [FK_D_PayCodeOU_D_PayCodes] FOREIGN KEY([PayCodeId])
	REFERENCES [dbo].[D_PayCodes] ([PayCodeId])


	ALTER TABLE [dbo].[D_PayCodeOU] CHECK CONSTRAINT [FK_D_PayCodeOU_D_PayCodes]

END
ELSE 
 Print 'FK_D_PayCodeOU_D_PayCodes Table Exist'
 
 GO
 -- Add [DayStartTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PayCodes') AND Name = N'IsEditable')
BEGIN
	ALTER TABLE [dbo].[D_PayCodes] ADD [IsEditable] BIT DEFAULT(0)

	UPDATE D_PayCodes SET IsEditable = 1
END
ELSE
	Print 'Column [IsEditable] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_PayGroupOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_PayGroupOU]  WITH CHECK ADD  CONSTRAINT [FK_D_PayGroupOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_PayGroupOU] CHECK CONSTRAINT [FK_D_PayGroupOU_C_OrganizationNode]


END
ELSE 
 Print 'FK_D_PayGroupOU_C_OrganizationNode Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_PayGroupOU_D_PayGroup') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_PayGroupOU]  WITH CHECK ADD  CONSTRAINT [FK_D_PayGroupOU_D_PayGroup] FOREIGN KEY([PayGroupId])
	REFERENCES [dbo].[D_PayGroup] ([PayGroupId])


	ALTER TABLE [dbo].[D_PayGroupOU] CHECK CONSTRAINT [FK_D_PayGroupOU_D_PayGroup]

END
ELSE 
 Print 'FK_D_PayGroupOU_D_PayGroup Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PublicHolidays') AND Name = N'IsLeaveProcess')
BEGIN
	ALTER TABLE [dbo].[D_PublicHolidays] ADD [IsLeaveProcess] [bit] NULL 
END
ELSE
	Print 'Column [IsLeaveProcess] Already Exists'
GO
				
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_D_PublicHolidays_IsLeaveProcess') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[D_PublicHolidays] ADD CONSTRAINT DF_D_PublicHolidays_IsLeaveProcess DEFAULT 0 FOR IsLeaveProcess
END
ELSE
	Print 'DEFAULT Constraint [DF_D_PublicHolidays_IsShiftProcess] Already Exists.'
GO


IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PublicHolidays') AND Name = N'IsShiftProcess')
BEGIN
	ALTER TABLE [dbo].[D_PublicHolidays] ADD [IsShiftProcess] [bit] NULL 
END
ELSE
	Print 'Column [IsShiftProcess] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_D_PublicHolidays_IsShiftProcess') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[D_PublicHolidays] ADD CONSTRAINT DF_D_PublicHolidays_IsShiftProcess DEFAULT 0 FOR IsShiftProcess
END
ELSE
	Print 'DEFAULT Constraint [DF_D_PublicHolidays_IsShiftProcess] Already Exists.'
GO
-- Add [DayStartTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'DayStartTime')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [DayStartTime] DATETIME DEFAULT('08:00:00')  
END
ELSE
	Print 'Column [DayStartTime] Already Exists'
GO

-- Add [DayEndTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'DayEndTime')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [DayEndTime] DATETIME NULL  DEFAULT('20:00:00')  
END
ELSE
	Print 'Column [DayEndTime] Already Exists'
GO

-- Add [NightStartTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'NightStartTime')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [NightStartTime] DATETIME NULL  DEFAULT('20:00:00')  
END
ELSE
	Print 'Column [NightStartTime] Already Exists'
GO

-- Add [NightEndTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'NightEndTime')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [NightEndTime] DATETIME NULL  DEFAULT('08:00:00')  
END
ELSE
	Print 'Column [NightEndTime] Already Exists'
GO

-- Add [MaxDailyOvertimeHours] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'MaxDailyOvertimeHours')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [MaxDailyOvertimeHours] [decimal](18, 2)  DEFAULT(0)  
END
ELSE
	Print 'Column [MaxDailyOvertimeHours] Already Exists'
GO

-- Add [IsAutoApproveOvertime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_RamadanPeriod') AND Name = N'IsAutoApproveOvertime')
BEGIN
	ALTER TABLE [dbo].[D_RamadanPeriod] ADD [IsAutoApproveOvertime] BIT  DEFAULT(1)  
END
ELSE
	Print 'Column [IsAutoApproveOvertime] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ReliefRule_C_OrganizationNode') AND type in ('F'))
BEGIN	
	ALTER TABLE [dbo].[D_ReliefRule]  WITH CHECK ADD  CONSTRAINT [FK_D_ReliefRule_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
	

	ALTER TABLE [dbo].[D_ReliefRule] CHECK CONSTRAINT [FK_D_ReliefRule_C_OrganizationNode]

END
ELSE 
 Print 'D_ReliefRule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ReliefRuleSkill_D_ReliefRule') AND type in ('F'))
BEGIN	


ALTER TABLE [dbo].[D_ReliefRuleSkill]  WITH CHECK ADD  CONSTRAINT [FK_D_ReliefRuleSkill_D_ReliefRule] FOREIGN KEY([RuleId])
REFERENCES [dbo].[D_ReliefRule] ([RuleId])


ALTER TABLE [dbo].[D_ReliefRuleSkill] CHECK CONSTRAINT [FK_D_ReliefRuleSkill_D_ReliefRule]


ALTER TABLE [dbo].[D_ReliefRuleSkill]  WITH CHECK ADD  CONSTRAINT [FK_D_ReliefRuleSkill_D_Skill] FOREIGN KEY([SkillId])
REFERENCES [dbo].[D_Skill] ([SkillId])


ALTER TABLE [dbo].[D_ReliefRuleSkill] CHECK CONSTRAINT [FK_D_ReliefRuleSkill_D_Skill]




END
ELSE 
 Print 'D_ReliefRuleSkill Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_RoleGroup_C_OrganizationNode') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[D_RoleGroup]  WITH CHECK ADD  CONSTRAINT [FK_D_RoleGroup_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_RoleGroup] CHECK CONSTRAINT [FK_D_RoleGroup_C_OrganizationNode]

END
ELSE 
 Print 'FK_D_RoleGroup_C_OrganizationNode Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_RoleOU_C_OrganizationNode') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[D_RoleOU]  WITH CHECK ADD  CONSTRAINT [FK_D_RoleOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_RoleOU] CHECK CONSTRAINT [FK_D_RoleOU_C_OrganizationNode]

END
ELSE 
 Print 'FK_D_RoleOU_C_OrganizationNode Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_RoleOU_D_RoleOU') AND type in ('F'))
BEGIN

	


	ALTER TABLE [dbo].[D_RoleOU]  WITH CHECK ADD  CONSTRAINT [FK_D_RoleOU_D_RoleOU] FOREIGN KEY([RoleId])
	REFERENCES [dbo].[D_Roles] ([RoleId])


	ALTER TABLE [dbo].[D_RoleOU] CHECK CONSTRAINT [FK_D_RoleOU_D_RoleOU]

END
ELSE 
 Print 'FK_D_RoleOU_D_RoleOU Table Exist'
 
GO

-- Add Role Priority Seq 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_Roles') AND Name = N'RolePrioritySeq')
BEGIN
	ALTER TABLE [dbo].[D_Roles] ADD [RolePrioritySeq] [int] DEFAULT(0) 
END
ELSE
	Print 'Column [RolePrioritySeq] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_RoleSkill_D_Roles') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[D_RoleSkill]  WITH CHECK ADD  CONSTRAINT [FK_D_RoleSkill_D_Roles] FOREIGN KEY([RoleId])
	REFERENCES [dbo].[D_Roles] ([RoleId])


	ALTER TABLE [dbo].[D_RoleSkill] CHECK CONSTRAINT [FK_D_RoleSkill_D_Roles]
	

END
ELSE 
 Print 'FK_D_RoleSkill_D_Roles Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_RoleSkill_D_Skill') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[D_RoleSkill]  WITH CHECK ADD  CONSTRAINT [FK_D_RoleSkill_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])
	

	ALTER TABLE [dbo].[D_RoleSkill] CHECK CONSTRAINT [FK_D_RoleSkill_D_Skill]

END
ELSE 
 Print 'FK_D_RoleSkill_D_Skill Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ShiftBand_D_ShiftBand') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ShiftBand]  WITH CHECK ADD  CONSTRAINT [FK_D_ShiftBand_D_ShiftBand] FOREIGN KEY([ShiftTypeId])
	REFERENCES [dbo].[D_ShiftBandType] ([ShiftTypeId])
	

	ALTER TABLE [dbo].[D_ShiftBand] CHECK CONSTRAINT [FK_D_ShiftBand_D_ShiftBand]



END
ELSE 
 Print 'FK_D_ShiftBand_D_ShiftBand Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ShiftBandCombination_D_ShiftBand') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ShiftBandCombination]  WITH CHECK ADD  CONSTRAINT [FK_D_ShiftBandCombination_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])
	

	ALTER TABLE [dbo].[D_ShiftBandCombination] CHECK CONSTRAINT [FK_D_ShiftBandCombination_D_ShiftBand]

END
ELSE 
 Print 'FK_D_ShiftBandCombination_D_ShiftBand Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ShiftBandCombination_D_ShiftBand1') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[D_ShiftBandCombination]  WITH CHECK ADD  CONSTRAINT [FK_D_ShiftBandCombination_D_ShiftBand1] FOREIGN KEY([ComboShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])


	ALTER TABLE [dbo].[D_ShiftBandCombination] CHECK CONSTRAINT [FK_D_ShiftBandCombination_D_ShiftBand1]


END
ELSE 
 Print 'FK_D_ShiftBandCombination_D_ShiftBand1 Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ShiftBandOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ShiftBandOU]  WITH CHECK ADD  CONSTRAINT [FK_D_ShiftBandOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[D_ShiftBandOU] CHECK CONSTRAINT [FK_D_ShiftBandOU_C_OrganizationNode]


END
ELSE 
 Print 'FK_D_ShiftBandOU_C_OrganizationNode Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_ShiftBandOU_D_ShiftBand') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_ShiftBandOU]  WITH CHECK ADD  CONSTRAINT [FK_D_ShiftBandOU_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])


	ALTER TABLE [dbo].[D_ShiftBandOU] CHECK CONSTRAINT [FK_D_ShiftBandOU_D_ShiftBand]
	

END
ELSE 
 Print 'FK_D_ShiftBandOU_D_ShiftBand Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_D_SkillOU_D_Skill') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[D_SkillOU]  WITH CHECK ADD  CONSTRAINT [FK_D_SkillOU_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])	

	ALTER TABLE [dbo].[D_SkillOU] CHECK CONSTRAINT [FK_D_SkillOU_D_Skill]

END
ELSE 
 Print 'FK_D_SkillOU_D_Skill Table Exist'
 
GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_E_EqipmentMatrix_Schedule_E_EquipmentMatrix') AND type in ('F'))
BEGIN	

	ALTER TABLE [dbo].[E_EqipmentMatrix_Schedule]  WITH CHECK ADD  CONSTRAINT [FK_E_EqipmentMatrix_Schedule_E_EquipmentMatrix] FOREIGN KEY([MatrixId])
	REFERENCES [dbo].[E_EquipmentMatrix] ([MatrixId])


	ALTER TABLE [dbo].[E_EqipmentMatrix_Schedule] CHECK CONSTRAINT [FK_E_EqipmentMatrix_Schedule_E_EquipmentMatrix]

END
ELSE 
 Print 'FK_E_EqipmentMatrix_Schedule_E_EquipmentMatrix Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_E_EquipmentMatrix_C_OrganizationNode') AND type in ('F'))
BEGIN	
	
	ALTER TABLE [dbo].[E_EquipmentMatrix]  WITH CHECK ADD  CONSTRAINT [FK_E_EquipmentMatrix_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[E_EquipmentMatrix] CHECK CONSTRAINT [FK_E_EquipmentMatrix_C_OrganizationNode]
	
END
ELSE 
 Print 'FK_E_EquipmentMatrix_C_OrganizationNode Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EquipmentType_Matrix_Det') AND type in ('U'))
BEGIN	


	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Det]  WITH CHECK ADD  CONSTRAINT [FK_E_EquipmentType_Matrix_Det_E_EquipmentType_Matrix_Template] FOREIGN KEY([MatrixEQTypeId])
	REFERENCES [dbo].[E_EquipmentType_Matrix_Template] ([MatrixEQTypeId])


	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Det] CHECK CONSTRAINT [FK_E_EquipmentType_Matrix_Det_E_EquipmentType_Matrix_Template]

	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Det]  WITH CHECK ADD  CONSTRAINT [FK_E_EquipmentType_Matrix_Det_M_EquipmentType] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_EquipmentType] ([EquipmentTypeId])

	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Det] CHECK CONSTRAINT [FK_E_EquipmentType_Matrix_Det_M_EquipmentType]


END
ELSE 
 Print 'E_EquipmentType_Matrix_Det Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_E_EquipmentType_Matrix_Template_C_OrganizationNode') AND type in ('F'))
BEGIN	

	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Template]  WITH CHECK ADD  CONSTRAINT [FK_E_EquipmentType_Matrix_Template_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[E_EquipmentType_Matrix_Template] CHECK CONSTRAINT [FK_E_EquipmentType_Matrix_Template_C_OrganizationNode]

END
ELSE 
 Print 'FK_E_EquipmentType_Matrix_Template_C_OrganizationNode Table Exist'
 
GO
 
 -- Add Foreign Key Constraint To Shift Band Id Column
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_I_BoxMovementSummary_D_ShiftBand') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[I_BoxMovementSummary]  WITH CHECK ADD  CONSTRAINT [FK_I_BoxMovementSummary_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])

	ALTER TABLE [dbo].[I_BoxMovementSummary] CHECK CONSTRAINT [FK_I_BoxMovementSummary_D_ShiftBand]
END
ELSE
	Print 'Column [FK_I_BoxMovementSummary_D_ShiftBand] Already Exists'
GO
-- Add [WorkloadId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_Activity') AND Name = N'WorkloadId')
BEGIN
	ALTER TABLE [dbo].[J_Activity] ADD [WorkloadId] [BigInt] NULL 
END
ELSE
	Print 'Column [J_Activity.WorkloadId] Already Exists'
GO
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_AllocationRuleEmploymentBasis') 
		   AND Name = N'PrioritySeq' AND system_type_id = 56)
BEGIN
	ALTER TABLE [dbo].[J_AllocationRuleEmploymentBasis] ALTER COLUMN [PrioritySeq] BigInt NULL
END
ELSE
	Print 'Column [PrioritySeq] Already Updated.'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_J_PlanningEquipmentRequirements_DeployedCount') AND type in ('D'))
BEGIN
	ALTER TABLE [dbo].[J_PlanningEquipmentRequirements] ADD  CONSTRAINT [DF_J_PlanningEquipmentRequirements_DeployedCount]  DEFAULT ((0)) FOR [DeployedCount]
END
ELSE
	Print 'DF_J_PlanningEquipmentRequirements_DeployedCount Exists'

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_J_PlanningEquipmentRequirements_D_ShiftBand') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[J_PlanningEquipmentRequirements]  WITH CHECK ADD  CONSTRAINT [FK_J_PlanningEquipmentRequirements_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])

	ALTER TABLE [dbo].[J_PlanningEquipmentRequirements] CHECK CONSTRAINT [FK_J_PlanningEquipmentRequirements_D_ShiftBand]
END
ELSE
	Print 'FK_J_PlanningEquipmentRequirements_D_ShiftBand Exists'

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_J_PlanningEquipmentRequirements_C_OrganizationNode') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[J_PlanningEquipmentRequirements]  WITH CHECK ADD  CONSTRAINT [FK_J_PlanningEquipmentRequirements_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[J_PlanningEquipmentRequirements] CHECK CONSTRAINT [FK_J_PlanningEquipmentRequirements_C_OrganizationNode]
END
ELSE Print 'FK_J_PlanningEquipmentRequirements_C_OrganizationNode Exists'

GO
-- Add [LastViewDateTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_Leaves') AND Name = N'LastViewDateTime')
BEGIN
	ALTER TABLE [dbo].[L_Leaves] ADD [LastViewDateTime] [DATETIME] NULL 
END
ELSE
	Print 'Column [L_Leaves.LastViewDateTime] Already Exists'
GO

-- Add [LastViewedUser] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_Leaves') AND Name = N'LastViewedUser')
BEGIN
	ALTER TABLE [dbo].[L_Leaves] ADD [LastViewedUser] nVarchar(255) NULL 
END
ELSE
	Print 'Column [L_Leaves.LastViewedUser] Already Exists'
GO

-- Add [LastViewDateTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_RequestDaysInLieu') AND Name = N'LastViewDateTime')
BEGIN
	ALTER TABLE [dbo].[L_RequestDaysInLieu] ADD [LastViewDateTime] [DATETIME] NULL 
END
ELSE
	Print 'Column [L_RequestDaysInLieu.LastViewDateTime] Already Exists'
GO

-- Add [LastViewedUser] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_RequestDaysInLieu') AND Name = N'LastViewedUser')
BEGIN
	ALTER TABLE [dbo].[L_RequestDaysInLieu] ADD [LastViewedUser] nVarchar(255) NULL 
END
ELSE
	Print 'Column [L_RequestDaysInLieu.LastViewedUser] Already Exists'
GO

-- Add [LastViewDateTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_TimeOff') AND Name = N'LastViewDateTime')
BEGIN
	ALTER TABLE [dbo].[L_TimeOff] ADD [LastViewDateTime] [DATETIME] NULL 
END
ELSE
	Print 'Column [L_TimeOff.LastViewDateTime] Already Exists'
GO

-- Add [LastViewedUser] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_TimeOff') AND Name = N'LastViewedUser')
BEGIN
	ALTER TABLE [dbo].[L_TimeOff] ADD [LastViewedUser] nVarchar(255) NULL 
END
ELSE
	Print 'Column [L_TimeOff.LastViewedUser] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_AuxiliaryWork_C_OrganizationNode') AND type in ('F'))
BEGIN	

	ALTER TABLE [dbo].[M_AuxiliaryWork]  WITH CHECK ADD  CONSTRAINT [FK_M_AuxiliaryWork_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[M_AuxiliaryWork] CHECK CONSTRAINT [FK_M_AuxiliaryWork_C_OrganizationNode]

	ALTER TABLE [dbo].[M_AuxiliaryWork]  WITH CHECK ADD  CONSTRAINT [FK_M_AuxiliaryWork_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])

	ALTER TABLE [dbo].[M_AuxiliaryWork] CHECK CONSTRAINT [FK_M_AuxiliaryWork_D_Skill]

END
ELSE 
 Print 'FK_M_AuxiliaryWork_C_OrganizationNode Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Berth_C_OrganizationNode') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[M_Berth]  WITH CHECK ADD  CONSTRAINT [FK_M_Berth_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_Berth] CHECK CONSTRAINT [FK_M_Berth_C_OrganizationNode]

END
ELSE 
 Print 'FK_M_Berth_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_BerthCranes_M_Berth') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[M_BerthCranes]  WITH CHECK ADD  CONSTRAINT [FK_M_BerthCranes_M_Berth] FOREIGN KEY([BerthId])
	REFERENCES [dbo].[M_Berth] ([BerthId])


	ALTER TABLE [dbo].[M_BerthCranes] CHECK CONSTRAINT [FK_M_BerthCranes_M_Berth]

END
ELSE 
 Print 'FK_M_BerthCranes_M_Berth Table Exist'
 
 GO
 
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_BerthCranes_M_Cranes') AND type in ('F'))
BEGIN

	
	ALTER TABLE [dbo].[M_BerthCranes]  WITH CHECK ADD  CONSTRAINT [FK_M_BerthCranes_M_Cranes] FOREIGN KEY([CraneId])
	REFERENCES [dbo].[M_Cranes] ([CraneId])

	ALTER TABLE [dbo].[M_BerthCranes] CHECK CONSTRAINT [FK_M_BerthCranes_M_Cranes]

END
ELSE 
 Print 'FK_M_BerthCranes_M_Cranes Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Cranes_C_OrganizationNode') AND type in ('F'))
begin
	ALTER TABLE [dbo].[M_Cranes]  WITH CHECK ADD  CONSTRAINT [FK_M_Cranes_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_Cranes] CHECK CONSTRAINT [FK_M_Cranes_C_OrganizationNode]

end
else 
 Print 'FK_M_Cranes_C_OrganizationNode Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Cranes_M_Locations') AND type in ('F'))
begin

	ALTER TABLE [dbo].[M_Cranes]  WITH CHECK ADD  CONSTRAINT [FK_M_Cranes_M_Locations] FOREIGN KEY([LocationId])
	REFERENCES [dbo].[M_Locations] ([LocationId])


	ALTER TABLE [dbo].[M_Cranes] CHECK CONSTRAINT [FK_M_Cranes_M_Locations]
	

end
else 
 Print 'FK_M_Cranes_M_Locations Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_CraneSchedule_C_OrganizationNode') AND type in ('F'))
BEGIN	

	ALTER TABLE [dbo].[M_CraneSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_CraneSchedule_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_CraneSchedule] CHECK CONSTRAINT [FK_M_CraneSchedule_C_OrganizationNode]


	ALTER TABLE [dbo].[M_CraneSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_CraneSchedule_M_Cranes] FOREIGN KEY([CraneId])
	REFERENCES [dbo].[M_Cranes] ([CraneId])


	ALTER TABLE [dbo].[M_CraneSchedule] CHECK CONSTRAINT [FK_M_CraneSchedule_M_Cranes]


	ALTER TABLE [dbo].[M_CraneSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_CraneSchedule_M_Locations] FOREIGN KEY([LocationId])
	REFERENCES [dbo].[M_Locations] ([LocationId])


	ALTER TABLE [dbo].[M_CraneSchedule] CHECK CONSTRAINT [FK_M_CraneSchedule_M_Locations]


	ALTER TABLE [dbo].[M_CraneSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_CraneSchedule_M_VesselSchedule] FOREIGN KEY([VesselScheduleId])
	REFERENCES [dbo].[M_VesselSchedule] ([VesselScheduleId])


	ALTER TABLE [dbo].[M_CraneSchedule] CHECK CONSTRAINT [FK_M_CraneSchedule_M_VesselSchedule]	

END
ELSE 
 Print 'M_CraneSchedule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Crane_Requirement_C_OrganizationNode') AND type in ('F'))
begin
	

	ALTER TABLE [dbo].[M_Crane_Requirement]  WITH CHECK ADD  CONSTRAINT [FK_M_Crane_Requirement_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_Crane_Requirement] CHECK CONSTRAINT [FK_M_Crane_Requirement_C_OrganizationNode]

end
else 
 Print 'M_Crane_Requirement Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Crane_Requirement_D_Skill') AND type in ('F'))
begin
	

	ALTER TABLE [dbo].[M_Crane_Requirement]  WITH CHECK ADD  CONSTRAINT [FK_M_Crane_Requirement_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])


	ALTER TABLE [dbo].[M_Crane_Requirement] CHECK CONSTRAINT [FK_M_Crane_Requirement_D_Skill]



end
else 
 Print 'FK_M_Crane_Requirement_D_Skill Table Exist'
 
 GO
 
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_EquipmentMaintenance_M_Equipments') AND type in ('F'))
begin

	ALTER TABLE [dbo].[M_EquipmentMaintenance]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentMaintenance_M_Equipments] FOREIGN KEY([EquipmentId])
	REFERENCES [dbo].[M_Equipments] ([EquipmentId])
	

	ALTER TABLE [dbo].[M_EquipmentMaintenance] CHECK CONSTRAINT [FK_M_EquipmentMaintenance_M_Equipments]


end
else 
 Print 'FK_M_EquipmentMaintenance_M_Equipments Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Equipments_C_OrganizationNode') AND type in ('F'))
begin
	

	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_C_OrganizationNode]


	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_M_EquipmentType] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_EquipmentType] ([EquipmentTypeId])
	

	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_M_EquipmentType]

	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_M_Locations] FOREIGN KEY([LocationId])
	REFERENCES [dbo].[M_Locations] ([LocationId])


	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_M_Locations]


end
else 
 Print 'FK_M_Equipments_C_OrganizationNode Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Equipments_M_EquipmentType') AND type in ('F'))
begin
	
	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_M_EquipmentType] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_EquipmentType] ([EquipmentTypeId])
	

	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_M_EquipmentType]

	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_M_Locations] FOREIGN KEY([LocationId])
	REFERENCES [dbo].[M_Locations] ([LocationId])


	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_M_Locations]


end
else 
 Print 'FK_M_Equipments_M_EquipmentType Table Exist'
 
 GO
 
  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Equipments_M_Locations') AND type in ('F'))
begin
	
	
	ALTER TABLE [dbo].[M_Equipments]  WITH CHECK ADD  CONSTRAINT [FK_M_Equipments_M_Locations] FOREIGN KEY([LocationId])
	REFERENCES [dbo].[M_Locations] ([LocationId])


	ALTER TABLE [dbo].[M_Equipments] CHECK CONSTRAINT [FK_M_Equipments_M_Locations]


end
else 
 Print 'FK_M_Equipments_M_Locations Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_EquipmentSchedule_M_Equipments') AND type in ('F'))
BEGIN	


	ALTER TABLE [dbo].[M_EquipmentSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentSchedule_M_Equipments] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_Equipments] ([EquipmentId])
	

	ALTER TABLE [dbo].[M_EquipmentSchedule] CHECK CONSTRAINT [FK_M_EquipmentSchedule_M_Equipments]
	

	ALTER TABLE [dbo].[M_EquipmentSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentSchedule_M_EquipmentSchedule] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
	

	ALTER TABLE [dbo].[M_EquipmentSchedule] CHECK CONSTRAINT [FK_M_EquipmentSchedule_M_EquipmentSchedule]
	

	ALTER TABLE [dbo].[M_EquipmentSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentSchedule_M_EquipmentType] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_EquipmentType] ([EquipmentTypeId])
	

	ALTER TABLE [dbo].[M_EquipmentSchedule] CHECK CONSTRAINT [FK_M_EquipmentSchedule_M_EquipmentType]
	

END
ELSE 
 Print 'M_EquipmentSchedule Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_EquipmentType_C_OrganizationNode') AND type in ('F'))
begin

	ALTER TABLE [dbo].[M_EquipmentType]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentType_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_EquipmentType] CHECK CONSTRAINT [FK_M_EquipmentType_C_OrganizationNode]

	
end
else 
 Print 'FK_M_EquipmentType_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_EquipmentType_Requirement_D_Skill') AND type in ('F'))
begin
	
	ALTER TABLE [dbo].[M_EquipmentType_Requirement]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentType_Requirement_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])


	ALTER TABLE [dbo].[M_EquipmentType_Requirement] CHECK CONSTRAINT [FK_M_EquipmentType_Requirement_D_Skill]
	

end
else 
 Print 'FK_M_EquipmentType_Requirement_D_Skill Table Exist'
 
 GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_EquipmentType_Requirement_M_EquipmentType') AND type in ('F'))
begin
	

	ALTER TABLE [dbo].[M_EquipmentType_Requirement]  WITH CHECK ADD  CONSTRAINT [FK_M_EquipmentType_Requirement_M_EquipmentType] FOREIGN KEY([EquipmentTypeId])
	REFERENCES [dbo].[M_EquipmentType] ([EquipmentTypeId])
	

	ALTER TABLE [dbo].[M_EquipmentType_Requirement] CHECK CONSTRAINT [FK_M_EquipmentType_Requirement_M_EquipmentType]


end
else 
 Print 'FK_M_EquipmentType_Requirement_M_EquipmentType Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Locations_C_OrganizationNode') AND type in ('F'))
begin

	ALTER TABLE [dbo].[M_Locations]  WITH CHECK ADD  CONSTRAINT [FK_M_Locations_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_Locations] CHECK CONSTRAINT [FK_M_Locations_C_OrganizationNode]
	
end
else 
 Print 'FK_M_Locations_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'DeployedBy')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [DeployedBy] [nvarchar](50) NULL
END
ELSE
	Print 'Column [DeployedBy] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'DeployedDate')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [DeployedDate] [DateTime] NULL
END
ELSE
	Print 'Column [DeployedDate] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'DeploymentPublishedBy')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [DeploymentPublishedBy] [nvarchar](50) NULL
END
ELSE
	Print 'Column [DeploymentPublishedBy] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'DeploymentPublishedDate')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [DeploymentPublishedDate] [DateTime] NULL
END
ELSE
	Print 'Column [DeploymentPublishedDate] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_SkillMatrix_C_OrganizationNode') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[M_SkillMatrix]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[M_SkillMatrix] CHECK CONSTRAINT [FK_M_SkillMatrix_C_OrganizationNode]

	ALTER TABLE [dbo].[M_SkillMatrix]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_M_Skill_Matrix_Template] FOREIGN KEY([MatrixSkillId])
	REFERENCES [dbo].[M_Skill_Matrix_Template] ([MatrixSkillId])

	ALTER TABLE [dbo].[M_SkillMatrix] CHECK CONSTRAINT [FK_M_SkillMatrix_M_Skill_Matrix_Template]
END
Else 
	Print 'FK_M_SkillMatrix_C_OrganizationNode Already Exists.'
GO






IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_SkillMatrix_Schedule') AND type in ('U'))
BEGIN

	ALTER TABLE [dbo].[M_SkillMatrix_Schedule]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_Schedule_M_SkillMatrix] FOREIGN KEY([SkillMatrixId])
	REFERENCES [dbo].[M_SkillMatrix] ([SkillMatrixId])

	ALTER TABLE [dbo].[M_SkillMatrix_Schedule] CHECK CONSTRAINT [FK_M_SkillMatrix_Schedule_M_SkillMatrix]
END
Else 
	Print 'M_SkillMatrix_Schedule Already Exists.'
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_SkillMatrix_Skills_D_Skill') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[M_SkillMatrix_Skills]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_Skills_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])

	ALTER TABLE [dbo].[M_SkillMatrix_Skills] CHECK CONSTRAINT [FK_M_SkillMatrix_Skills_D_Skill]

	ALTER TABLE [dbo].[M_SkillMatrix_Skills]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_Skills_M_SkillMatrix] FOREIGN KEY([SkillMatrixId])
	REFERENCES [dbo].[M_SkillMatrix] ([SkillMatrixId])

	ALTER TABLE [dbo].[M_SkillMatrix_Skills] CHECK CONSTRAINT [FK_M_SkillMatrix_Skills_M_SkillMatrix]

	ALTER TABLE [dbo].[M_SkillMatrix_Skills]  WITH CHECK ADD  CONSTRAINT [FK_M_SkillMatrix_Skills_M_SkillMatrix_Schedule] FOREIGN KEY([SkillMatrixScheduleId])
	REFERENCES [dbo].[M_SkillMatrix_Schedule] ([SkillMatrixScheduleId])

	ALTER TABLE [dbo].[M_SkillMatrix_Skills] CHECK CONSTRAINT [FK_M_SkillMatrix_Skills_M_SkillMatrix_Schedule]

	
END
Else 
	Print 'FK_M_SkillMatrix_Skills_D_Skill Already Exists.'
GO





IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_Skill_Matrix_Det_D_Skill') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[M_Skill_Matrix_Det]  WITH CHECK ADD  CONSTRAINT [FK_M_Skill_Matrix_Det_D_Skill] FOREIGN KEY([SkillId])
	REFERENCES [dbo].[D_Skill] ([SkillId])

	ALTER TABLE [dbo].[M_Skill_Matrix_Det] CHECK CONSTRAINT [FK_M_Skill_Matrix_Det_D_Skill]

	ALTER TABLE [dbo].[M_Skill_Matrix_Det]  WITH CHECK ADD  CONSTRAINT [FK_M_Skill_Matrix_Det_M_Skill_Matrix_Template] FOREIGN KEY([MatrixSkillId])
	REFERENCES [dbo].[M_Skill_Matrix_Template] ([MatrixSkillId])

	ALTER TABLE [dbo].[M_Skill_Matrix_Det] CHECK CONSTRAINT [FK_M_Skill_Matrix_Det_M_Skill_Matrix_Template]
END
Else 
	Print 'FK_M_Skill_Matrix_Det_D_Skill Already Exists.'
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_M_VesselSchedule_C_OrganizationNode') AND type in ('F'))
BEGIN	
	ALTER TABLE [dbo].[M_VesselSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_VesselSchedule_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[M_VesselSchedule] CHECK CONSTRAINT [FK_M_VesselSchedule_C_OrganizationNode]


	ALTER TABLE [dbo].[M_VesselSchedule]  WITH CHECK ADD  CONSTRAINT [FK_M_VesselSchedule_M_Berth] FOREIGN KEY([BerthId])
	REFERENCES [dbo].[M_Berth] ([BerthId])


	ALTER TABLE [dbo].[M_VesselSchedule] CHECK CONSTRAINT [FK_M_VesselSchedule_M_Berth]	

END
ELSE 
 Print 'FK_M_VesselSchedule_C_OrganizationNode Table Exist'
 
GO

-- Add Vessl Type If Not Exists
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_VesselSchedule') AND Name = N'VesselType')
BEGIN
	ALTER TABLE [dbo].[M_VesselSchedule] ADD [VesselType] [nvarchar](100) NULL 
END
ELSE
	Print 'Column [VesselType] Already Exists'
GO

-- Add Vessl Remarks If Not Exists
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_VesselSchedule') AND Name = N'Remarks')
BEGIN
	ALTER TABLE [dbo].[M_VesselSchedule] ADD [Remarks] [nvarchar](500) NULL 
END
ELSE
	Print 'Column [Remarks] Already Exists'
GO
-- Add [MaxOvertimeHours] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_OvertimeSettings') AND Name = N'MaxOvertimeHours')
BEGIN
	ALTER TABLE [dbo].[P_OvertimeSettings] ADD [MaxOvertimeHours] [decimal](18, 2)  DEFAULT(0)  
END
ELSE
	Print 'Column [MaxOvertimeHours] Already Exists'
GO-- Add [ApprovalStatus] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'ApprovalStatus')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ADD [ApprovalStatus] [int] DEFAULT(1) 

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = Pending Approval, 2 = Approved, Others Retrieve From W_ApprovalStatus Table' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'P_ShiftCosts', @level2type=N'COLUMN',@level2name=N'ApprovalStatus'	

END
ELSE
	Print 'Column [ApprovalStatus] Already Exists'
GO

-- Add [ApprovedHours] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'ApprovedHours')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ADD [ApprovedHours] [decimal] (18,5) DEFAULT(0.00) 
END
ELSE
	Print 'Column [ApprovedHours] Already Exists'
GO

UPDATE P_ShiftCosts SET ApprovalStatus = 1, ApprovedHours = ActualHour Where ApprovalStatus IS NULL
GO

-- Alter Column [ActualHours] Column To Decimal From Int
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'ActualHour')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ALTER COLUMN [ActualHour] [Float]
	Print 'Successfully Modified Column [ActualHour]'
END	
GO

-- Alter Column [ApprovedHours] Column To Decimal From Int
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'ApprovedHours')
BEGIN
	--ALTER TABLE [dbo].[P_ShiftCosts] DROP CONSTRAINT [DF__P_ShiftCo__Appro__7899839A]
	ALTER TABLE [dbo].[P_ShiftCosts] ALTER COLUMN [ApprovedHours] [Float]
	Print 'Successfully Modified Column [ApprovedHours]'
END	
GO

-- Alter Column [ShiftCost] Column To Decimal From Int
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'ShiftCost')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ALTER COLUMN [ShiftCost] [Float]
	Print 'Successfully Modified Column [ShiftCost]'
END	
GO

-- Alter Column [AdjustmentCost] Column To Decimal From Int
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'AdjustmentCost')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ALTER COLUMN [AdjustmentCost] [Float]
	Print 'Successfully Modified Column [AdjustmentCost]'
END	
GO

-- Alter Column [TotalCost] Column To Decimal From Int
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'TotalCost')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ALTER COLUMN [TotalCost] [Float]
	Print 'Successfully Modified Column [TotalCost]'
END	
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_EmployeeLeaves_C_Employee') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_EmployeeLeaves]  WITH CHECK ADD  CONSTRAINT [FK_S_EmployeeLeaves_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])


	ALTER TABLE [dbo].[S_EmployeeLeaves] CHECK CONSTRAINT [FK_S_EmployeeLeaves_C_Employee]

END
ELSE 
 Print 'FK_S_EmployeeLeaves_C_Employee Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_EmployeeLeaves_C_OrganizationNode') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_EmployeeLeaves]  WITH CHECK ADD  CONSTRAINT [FK_S_EmployeeLeaves_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[S_EmployeeLeaves] CHECK CONSTRAINT [FK_S_EmployeeLeaves_C_OrganizationNode]

END
ELSE 
 Print 'FK_S_EmployeeLeaves_C_OrganizationNode Table Exist'
 
 GO
 
  IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_EmployeeLeaves_S_EmployeeLeaves') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_EmployeeLeaves]  WITH CHECK ADD  CONSTRAINT [FK_S_EmployeeLeaves_S_EmployeeLeaves] FOREIGN KEY([ExceptionCodeId])
	REFERENCES [dbo].[D_ExceptionCodes] ([ExceptionCodeId])


	ALTER TABLE [dbo].[S_EmployeeLeaves] CHECK CONSTRAINT [FK_S_EmployeeLeaves_S_EmployeeLeaves]


END
ELSE 
 Print 'FK_S_EmployeeLeaves_S_EmployeeLeaves Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_PublishRoster_S_TemplateRoster') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[S_PublishRoster]  WITH CHECK ADD  CONSTRAINT [FK_S_PublishRoster_S_TemplateRoster] FOREIGN KEY([TemplateId])
	REFERENCES [dbo].[S_TemplateRoster] ([TemplateId])


	ALTER TABLE [dbo].[S_PublishRoster] CHECK CONSTRAINT [FK_S_PublishRoster_S_TemplateRoster]

END
ELSE 
 Print 'FK_S_PublishRoster_S_TemplateRoster Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_PublishRosterDetails_S_PublishRoster') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_PublishRosterDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_PublishRosterDetails_S_PublishRoster] FOREIGN KEY([PublishId])
	REFERENCES [dbo].[S_PublishRoster] ([PublishId])


	ALTER TABLE [dbo].[S_PublishRosterDetails] CHECK CONSTRAINT [FK_S_PublishRosterDetails_S_PublishRoster]

END
ELSE 
 Print 'FK_S_PublishRosterDetails_S_PublishRoster Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_PublishRosterDetails_S_TemplateRosterLine') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_PublishRosterDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_PublishRosterDetails_S_TemplateRosterLine] FOREIGN KEY([TemplateLineId])
	REFERENCES [dbo].[S_TemplateRosterLine] ([TemplateLineId])


	ALTER TABLE [dbo].[S_PublishRosterDetails] CHECK CONSTRAINT [FK_S_PublishRosterDetails_S_TemplateRosterLine]

END
ELSE 
 Print 'FK_S_PublishRosterDetails_S_TemplateRosterLine Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_RosterGroup_C_OrganizationNode') AND type in ('f'))
BEGIN
	
	ALTER TABLE [dbo].[S_RosterGroup]  WITH CHECK ADD  CONSTRAINT [FK_S_RosterGroup_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
	

	ALTER TABLE [dbo].[S_RosterGroup] CHECK CONSTRAINT [FK_S_RosterGroup_C_OrganizationNode]

END
ELSE 
 Print 'FK_S_RosterGroup_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_RosterGroupDetails_C_Employee') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[S_RosterGroupDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_RosterGroupDetails_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])
	

	ALTER TABLE [dbo].[S_RosterGroupDetails] CHECK CONSTRAINT [FK_S_RosterGroupDetails_C_Employee]
	

	ALTER TABLE [dbo].[S_RosterGroupDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_RosterGroupDetails_S_RosterGroup] FOREIGN KEY([RosterGroupId])
	REFERENCES [dbo].[S_RosterGroup] ([RosterGroupId])
	

	ALTER TABLE [dbo].[S_RosterGroupDetails] CHECK CONSTRAINT [FK_S_RosterGroupDetails_S_RosterGroup]


END
ELSE 
 Print 'FK_S_RosterGroupDetails_C_Employee Table Exist'

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_RosterGroupDetails_S_RosterGroup') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[S_RosterGroupDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_RosterGroupDetails_S_RosterGroup] FOREIGN KEY([RosterGroupId])
	REFERENCES [dbo].[S_RosterGroup] ([RosterGroupId])
	

	ALTER TABLE [dbo].[S_RosterGroupDetails] CHECK CONSTRAINT [FK_S_RosterGroupDetails_S_RosterGroup]


END
ELSE 
 Print 'FK_S_RosterGroupDetails_S_RosterGroup Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_SchedulePeriod_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	ALTER TABLE [dbo].[S_SchedulePeriod]  WITH CHECK ADD  CONSTRAINT [FK_S_SchedulePeriod_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
	

	ALTER TABLE [dbo].[S_SchedulePeriod] CHECK CONSTRAINT [FK_S_SchedulePeriod_C_OrganizationNode]
	

	ALTER TABLE [dbo].[S_SchedulePeriod]  WITH CHECK ADD  CONSTRAINT [FK_S_SchedulePeriod_S_ScheduleRules] FOREIGN KEY([ScheduleRuleId])
	REFERENCES [dbo].[S_ScheduleRules] ([ScheduleRuleId])
	

	ALTER TABLE [dbo].[S_SchedulePeriod] CHECK CONSTRAINT [FK_S_SchedulePeriod_S_ScheduleRules]
	

END
ELSE 
 Print 'FK_S_SchedulePeriod_C_OrganizationNode Table Exist'

GO 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_ScheduleRuleOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	
	ALTER TABLE [dbo].[S_ScheduleRuleOU]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRuleOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[S_ScheduleRuleOU] CHECK CONSTRAINT [FK_S_ScheduleRuleOU_C_OrganizationNode]

	ALTER TABLE [dbo].[S_ScheduleRuleOU]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRuleOU_S_ScheduleRules] FOREIGN KEY([ScheduleRuleId])
	REFERENCES [dbo].[S_ScheduleRules] ([ScheduleRuleId])

	ALTER TABLE [dbo].[S_ScheduleRuleOU] CHECK CONSTRAINT [FK_S_ScheduleRuleOU_S_ScheduleRules]

END
ELSE 
 Print 'FK_S_ScheduleRuleOU_C_OrganizationNode Table Exist'
 
 GO

 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_ScheduleRuleOU_C_OrganizationNode') AND type in ('F'))
BEGIN
	
	
	ALTER TABLE [dbo].[S_ScheduleRuleOU]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRuleOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[S_ScheduleRuleOU] CHECK CONSTRAINT [FK_S_ScheduleRuleOU_C_OrganizationNode]

	ALTER TABLE [dbo].[S_ScheduleRuleOU]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRuleOU_S_ScheduleRules] FOREIGN KEY([ScheduleRuleId])
	REFERENCES [dbo].[S_ScheduleRules] ([ScheduleRuleId])

	ALTER TABLE [dbo].[S_ScheduleRuleOU] CHECK CONSTRAINT [FK_S_ScheduleRuleOU_S_ScheduleRules]

END
ELSE 
 Print 'FK_S_ScheduleRuleOU_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_ScheduleRulePeriod_S_ScheduleRules') AND type in ('f'))
BEGIN
		
	ALTER TABLE [dbo].[S_ScheduleRulePeriod]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRulePeriod_S_ScheduleRules] FOREIGN KEY([ScheduleRuleId])
	REFERENCES [dbo].[S_ScheduleRules] ([ScheduleRuleId])

	ALTER TABLE [dbo].[S_ScheduleRulePeriod] CHECK CONSTRAINT [FK_S_ScheduleRulePeriod_S_ScheduleRules]

END
ELSE 
	Print 'FK_S_ScheduleRulePeriod_S_ScheduleRules Table Exist'
GO

-- Add [ShiftBandPerPeriodMin] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_ScheduleRulePeriod') AND Name = N'ShiftBandPerPeriodMin')
BEGIN
	ALTER TABLE [dbo].[S_ScheduleRulePeriod] ADD [ShiftBandPerPeriodMin] [int] DEFAULT(0) 
END
ELSE
	Print 'Column [ShiftBandPerPeriodMin] Already Exists'
GO

-- Add [ShiftBandPerPeriodMax] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_ScheduleRulePeriod') AND Name = N'ShiftBandPerPeriodMax')
BEGIN
	ALTER TABLE [dbo].[S_ScheduleRulePeriod] ADD [ShiftBandPerPeriodMax] [int] DEFAULT(0) 
END
ELSE
	Print 'Column [ShiftBandPerPeriodMax] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_ScheduleRulePeriodShiftbands_D_ShiftBand') AND type in ('F'))
BEGIN
		
	ALTER TABLE [dbo].[S_ScheduleRulePeriodShiftbands]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRulePeriodShiftbands_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])

	ALTER TABLE [dbo].[S_ScheduleRulePeriodShiftbands] CHECK CONSTRAINT [FK_S_ScheduleRulePeriodShiftbands_D_ShiftBand]

END
ELSE 
 Print 'FK_S_ScheduleRulePeriodShiftbands_D_ShiftBand Table Exist'

 GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_ScheduleRulePeriodShiftbands_S_ScheduleRulePeriod') AND type in ('F'))
BEGIN
		
	
	ALTER TABLE [dbo].[S_ScheduleRulePeriodShiftbands]  WITH CHECK ADD  CONSTRAINT [FK_S_ScheduleRulePeriodShiftbands_S_ScheduleRulePeriod] FOREIGN KEY([SCRPeriodId])
	REFERENCES [dbo].[S_ScheduleRulePeriod] ([SCRPeriodId])

	ALTER TABLE [dbo].[S_ScheduleRulePeriodShiftbands] CHECK CONSTRAINT [FK_S_ScheduleRulePeriodShiftbands_S_ScheduleRulePeriod]

END
ELSE 
 Print 'FK_S_ScheduleRulePeriodShiftbands_S_ScheduleRulePeriod Table Exist'

 GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_Shifts_C_Employee') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[S_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_Shifts_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])

	ALTER TABLE [dbo].[S_Shifts] CHECK CONSTRAINT [FK_S_Shifts_C_Employee]
	
	ALTER TABLE [dbo].[S_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_Shifts_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[S_Shifts] CHECK CONSTRAINT [FK_S_Shifts_C_OrganizationNode]
	
	ALTER TABLE [dbo].[S_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_Shifts_D_Roles] FOREIGN KEY([RoleId])
	REFERENCES [dbo].[D_Roles] ([RoleId])

	ALTER TABLE [dbo].[S_Shifts] CHECK CONSTRAINT [FK_S_Shifts_D_Roles]

	ALTER TABLE [dbo].[S_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_Shifts_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])

	ALTER TABLE [dbo].[S_Shifts] CHECK CONSTRAINT [FK_S_Shifts_D_ShiftBand]

	
END
ELSE 
 Print 'FK_S_Shifts_C_Employee Table Exist'

GO

-- Add [ApprovalStatus] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_Shifts') AND Name = N'ApprovalStatus')
BEGIN
	ALTER TABLE [dbo].[S_Shifts] ADD [ApprovalStatus] [int] DEFAULT(1) 

	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = Pending Approval, 2 = Approved, Others Retrieve From W_ApprovalStatus Table' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'S_Shifts', @level2type=N'COLUMN',@level2name=N'ApprovalStatus'	

END
ELSE
	Print 'Column [ApprovalStatus] Already Exists'
GO

-- Add [Remarks] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_Shifts') AND Name = N'Remarks')
BEGIN
	ALTER TABLE [dbo].[S_Shifts] ADD [Remarks] nVarchar(max) NULL 
END
ELSE
	Print 'Column [Remarks] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_TemplateRoster_C_OrganizationNode') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[S_TemplateRoster]  WITH CHECK ADD  CONSTRAINT [FK_S_TemplateRoster_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])


	ALTER TABLE [dbo].[S_TemplateRoster] CHECK CONSTRAINT [FK_S_TemplateRoster_C_OrganizationNode]
	

END
ELSE 
 Print 'FK_S_TemplateRoster_C_OrganizationNode Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_T_TemplateRosterLine_LineType') AND type in ('D'))
BEGIN
	

	ALTER TABLE [dbo].[S_TemplateRosterLine] ADD  CONSTRAINT [DF_T_TemplateRosterLine_LineType]  DEFAULT ((1)) FOR [LineType]

	ALTER TABLE [dbo].[S_TemplateRosterLine]  WITH CHECK ADD  CONSTRAINT [FK_S_TemplateRosterLine_S_TemplateRoster] FOREIGN KEY([TemplateId])
	REFERENCES [dbo].[S_TemplateRoster] ([TemplateId])

	ALTER TABLE [dbo].[S_TemplateRosterLine] CHECK CONSTRAINT [FK_S_TemplateRosterLine_S_TemplateRoster]	

END
ELSE 
 Print 'DF_T_TemplateRosterLine_LineType Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_TemplateRoster_Shifts_D_ShiftBand') AND type in ('f'))
BEGIN
	
	ALTER TABLE [dbo].[S_TemplateRoster_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_TemplateRoster_Shifts_D_ShiftBand] FOREIGN KEY([ShiftBandId])
	REFERENCES [dbo].[D_ShiftBand] ([ShiftBandId])

	ALTER TABLE [dbo].[S_TemplateRoster_Shifts] CHECK CONSTRAINT [FK_S_TemplateRoster_Shifts_D_ShiftBand]	

	ALTER TABLE [dbo].[S_TemplateRoster_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_TemplateRoster_Shifts_S_TemplateRoster] FOREIGN KEY([TemplateId])
	REFERENCES [dbo].[S_TemplateRoster] ([TemplateId])	

	ALTER TABLE [dbo].[S_TemplateRoster_Shifts] CHECK CONSTRAINT [FK_S_TemplateRoster_Shifts_S_TemplateRoster]	

	ALTER TABLE [dbo].[S_TemplateRoster_Shifts]  WITH CHECK ADD  CONSTRAINT [FK_S_TemplateRoster_Shifts_S_TemplateRosterLine] FOREIGN KEY([TemplateLineId])
	REFERENCES [dbo].[S_TemplateRosterLine] ([TemplateLineId])

	ALTER TABLE [dbo].[S_TemplateRoster_Shifts] CHECK CONSTRAINT [FK_S_TemplateRoster_Shifts_S_TemplateRosterLine]

END
ELSE 
 Print 'FK_S_TemplateRoster_Shifts_D_ShiftBand Table Exist'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_THPSettingRosterGroups_S_THPSettings') AND type in ('F'))
BEGIN	


	ALTER TABLE [dbo].[S_THPSettingRosterGroups]  WITH CHECK ADD  CONSTRAINT [FK_S_THPSettingRosterGroups_S_THPSettings] FOREIGN KEY([THPSettingId])
	REFERENCES [dbo].[S_THPSettings] ([THPSettingId])


	ALTER TABLE [dbo].[S_THPSettingRosterGroups] CHECK CONSTRAINT [FK_S_THPSettingRosterGroups_S_THPSettings]

END
ELSE 
 Print 'FK_S_THPSettingRosterGroups_S_THPSettings Table Exist'
 
GO
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_TA_RPGOU_C_OrganizationNode') AND type in ('f'))
BEGIN
	

	ALTER TABLE [dbo].[TA_RPGOU]  WITH CHECK ADD  CONSTRAINT [FK_TA_RPGOU_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])

	ALTER TABLE [dbo].[TA_RPGOU] CHECK CONSTRAINT [FK_TA_RPGOU_C_OrganizationNode]

	ALTER TABLE [dbo].[TA_RPGOU]  WITH CHECK ADD  CONSTRAINT [FK_TA_RPGOU_TA_RPGConfig] FOREIGN KEY([RPGId])
	REFERENCES [dbo].[TA_RPGConfig] ([RPGId])

	ALTER TABLE [dbo].[TA_RPGOU] CHECK CONSTRAINT [FK_TA_RPGOU_TA_RPGConfig]


END
ELSE 
 Print 'FK_TA_RPGOU_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_TA_RPGRoles_D_Roles') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[TA_RPGRoles]  WITH CHECK ADD  CONSTRAINT [FK_TA_RPGRoles_D_Roles] FOREIGN KEY([RoleId])
	REFERENCES [dbo].[D_Roles] ([RoleId])

	ALTER TABLE [dbo].[TA_RPGRoles] CHECK CONSTRAINT [FK_TA_RPGRoles_D_Roles]

	ALTER TABLE [dbo].[TA_RPGRoles]  WITH CHECK ADD  CONSTRAINT [FK_TA_RPGRoles_TA_RPGConfig] FOREIGN KEY([RPGId])
	REFERENCES [dbo].[TA_RPGConfig] ([RPGId])

	ALTER TABLE [dbo].[TA_RPGRoles] CHECK CONSTRAINT [FK_TA_RPGRoles_TA_RPGConfig]

END
ELSE 
 Print 'FK_TA_RPGRoles_D_Roles Table Exist'
 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_T_SystemTaskSchedule_T_SystemTaskSchedule') AND type in ('F'))
BEGIN

	ALTER TABLE [dbo].[T_SystemTaskSchedule]  WITH CHECK ADD  CONSTRAINT [FK_T_SystemTaskSchedule_T_SystemTaskSchedule] FOREIGN KEY([SystemTaskId])
	REFERENCES [dbo].[T_SystemTask] ([SystemTaskId])
	
	ALTER TABLE [dbo].[T_SystemTaskSchedule] CHECK CONSTRAINT [FK_T_SystemTaskSchedule_T_SystemTaskSchedule]
	
END
Else
	Print 'FK_T_SystemTaskSchedule_T_SystemTaskSchedule Constraint Exist'
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_W_WorkflowRoute_C_OrganizationNode') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[W_WorkflowRoute]  WITH CHECK ADD  CONSTRAINT [FK_W_WorkflowRoute_C_OrganizationNode] FOREIGN KEY([OUId])
	REFERENCES [dbo].[C_OrganizationNode] ([OUId])
	
	ALTER TABLE [dbo].[W_WorkflowRoute] CHECK CONSTRAINT [FK_W_WorkflowRoute_C_OrganizationNode]
	
END
ELSE 
 Print 'FK_W_WorkflowRoute_C_OrganizationNode Table Exist'
 
 GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_W_WorkflowRouteDetails_W_WorkflowRoute') AND type in ('F'))
BEGIN
	

	ALTER TABLE [dbo].[W_WorkflowRouteDetails]  WITH CHECK ADD  CONSTRAINT [FK_W_WorkflowRouteDetails_W_WorkflowRoute] FOREIGN KEY([RouteId])
	REFERENCES [dbo].[W_WorkflowRoute] ([RouteId])

	ALTER TABLE [dbo].[W_WorkflowRouteDetails] CHECK CONSTRAINT [FK_W_WorkflowRouteDetails_W_WorkflowRoute]

END
ELSE 
 Print 'FK_W_WorkflowRouteDetails_W_WorkflowRoute Table Exist'SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Dashboard Child Menu Items
-- Access & Security
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 228)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(228, 108, N'Dashboards',NULL, 1, N'sidenav-icon fas fa-chart-line', 1, N'System',GETDATE(), 9, 0, 0)		

	-- Operations Dashboard
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 411)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(411, 228, N'Operations', N'Dashboard/Dashboard/Index', 2, N'', 1, N'System',GETDATE(), 10, 0, 0)

	-- Productivity Dashboard
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 415)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(415, 228, N'Productivity', N'Dashboard/Productivity/Index', 3, N'', 1, N'System',GETDATE(), 11, 0, 0)

-- /End Dashboard Child Menu Items

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Insert Horizontal Menu Items
-- Dashboard
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 108)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(108, NULL, N'Dashboard',NULL, 1, N'sidenav-icon fas fa-tachometer-alt', 1, N'System',GETDATE(), 1, 0, 1)			

-- System Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 100)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(100, NULL, N'System Setup',NULL, 1, N'sidenav-icon fas fa-user-cog', 1, N'System',GETDATE(), 1, 0, 1)			

-- System Definitions
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 101)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(101, NULL, N'System Definitions',NULL, 2, N'sidenav-icon fas fa-tools', 1, N'System',GETDATE(), 2, 0, 1)			

-- Employee Administration
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 102)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(102, NULL, N'Employee Administration',NULL, 3, N'sidenav-icon fas fa-users', 1, N'System',GETDATE(), 3, 0, 1)			
	
-- Workforce Scheduling
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 103)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(103, NULL, N'Workforce Scheduling',NULL, 4, N'sidenav-icon fas fa-calendar-alt', 1, N'System',GETDATE(), 4, 0, 1)
	
-- Employee Self Service
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 104)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(104, NULL, N'Employee Self Service',NULL, 5, N'sidenav-icon fas fa-flag', 1, N'System',GETDATE(), 5, 1, 1)

-- Operation Planning & Execution
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 105)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(105, NULL, N'Operation Planning & Execution',NULL, 6, N'sidenav-icon fas fa-list-alt', 1, N'System',GETDATE(), 6, 0, 1)

-- Time & Attendance
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 106)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(106, NULL, N'Time & Attendance',NULL, 7, N'sidenav-icon fas fa-clock', 1, N'System',GETDATE(), 7, 0, 1)
			
-- Reports
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 107)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(107, NULL, N'Reports',NULL, 8, N'sidenav-icon fas fa-print', 1, N'System',GETDATE(), 8, 0, 1)

-- Dashboard
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 108)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(108, NULL, N'Dashboard',NULL, 8, N'sidenav-icon fas fa-tachometer-alt', 1, N'System',GETDATE(), 0, 0, 1)

-- /End Horizontal Menu Items
SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO

SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- System Setup Child Menu Items

-- Access & Security
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 200)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(200, 100, N'Access & Security',NULL, 1, N'sidenav-icon fas fa-key', 1, N'System',GETDATE(), 9, 0, 0)			

	-- Access & Security Child Menu Items

	-- User Access
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 300)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(300, 200, N'User Access', N'Admin/User', 2, N'', 1, N'System',GETDATE(), 10, 0, 0)			

	-- Security Role Definition
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 301)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(301, 200, N'Security Role',N'Admin/SecurityRole', 3, N'', 1, N'System',GETDATE(), 11, 0, 0)			

-- /End Access & Security Child Menu Items

--Organisation Structure
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 201)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(201, 100, N'Organisation Structure',NULL, 4, N'sidenav-icon fas fa-building', 1, N'System',GETDATE(), 12, 0, 0)			

	--Organisation Structure Child Menu Items

	--Organisation Unit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 302)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(302, 201, N'Organisation Unit',N'Setup/OrganizationUnit', 5, N'', 1, N'System',GETDATE(), 13, 0, 0)			

	-- System Parameters
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 303)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(303, 201, N'System Parameters',N'Setup/SystemParams', 6, N'', 1, N'System',GETDATE(), 14, 0, 0)			
-- /End Organisation Structure

-- Process Administration
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 202)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(202, 100, N'Process Administration',NULL, 7, N'sidenav-icon fas fa-microchip', 1, N'System',GETDATE(), 15, 0, 0)			

	-- Interface Configuration
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 304)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(304, 202, N'Interface Configuration',N'Process/Interfaces', 8, N'', 1, N'System',GETDATE(), 16, 0, 0)			

	-- System Task Configuration
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 305)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(305, 202, N'System Task Configuration',N'Process/SystemTask', 9, N'', 1, N'System',GETDATE(), 17, 0, 0)			
-- /End Process Administration

-- /End System Setup Child Menu Items

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- System Definitions Child Menu Items [101]

-- Employee Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 203)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(203, 101, N'Employee Setup',NULL, 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 18, 0, 0)			

	-- Employment Category (306)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 306)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(306, 203, N'Employment Category',  N'Definitions/EmploymentBasis', 2, N'', 1, N'System',GETDATE(), 19, 0, 0)			
	-- /End Employment Category

	-- Skills (307)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 307)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(307, 203, N'Skills',  N'Definitions/Skill', 3, N'', 1, N'System',GETDATE(), 20, 0, 0)	
	-- /End Skills

	-- Roles (308)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 308)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(308, 203, N'Roles',  N'Definitions/Roles', 4, N'', 1, N'System',GETDATE(), 21, 0, 0)	
	-- /End Roles

	-- Role Groups (309)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 309)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(309, 203, N'Role Groups', N'Definitions/RoleGroup', 5, N'', 1, N'System',GETDATE(), 22, 0, 0)	
	-- /End Role Groups

-- /End Employee Setup

-- Roster Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 204)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(204, 101, N'Roster Setup',NULL, 6, N'sidenav-icon fas fa-calendar-day', 1, N'System',GETDATE(), 23, 0, 0)			

	-- Shift Band Definition (310)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 310)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(310, 204, N'Shift Band Definition', N'Definitions/Shiftband', 7, N'', 1, N'System',GETDATE(), 24, 0, 0)	
	-- /End Shift Band Definition 

	-- Schedule Creation Rules (311)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 311)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(311, 204, N'Schedule Creation Rules', N'Definitions/ScheduleCreationRules', 8, N'', 1, N'System',GETDATE(), 25, 0, 0)	
	-- /End Schedule Creation Rules 

	-- Roster Creation (Template Roster) (312)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 312)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(312, 204, N'Roster Creation ',N'Scheduler/TemplateRoster', 9, N'', 1, N'System',GETDATE(), 26, 0, 0)	
	-- /End Roster Creation (Template Roster) 

	-- Public Holiday (313)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 313)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(313, 204, N'Public Holiday',N'Definitions/PublicHoliday', 10, N'', 1, N'System',GETDATE(), 27, 0, 0)	
	-- /End Public Holiday 

-- /End Roster Setup

-- Leave Administration (205)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 205)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(205, 101, N'Leave Administration',NULL, 11, N'sidenav-icon fas fa-snowman', 1, N'System',GETDATE(), 28, 0, 0)			


	-- Leave & Attendance Codes (314) Exception Codes
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 314)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(314, 205, N'Leave & Attendance Codes', N'Definitions/ExceptionCodes', 12, N'', 1, N'System',GETDATE(), 29, 0, 0)	
	-- /End Leave & Attendance Codes 

	-- Leave Profile (315)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 315)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(315, 205, N'Leave Profile', N'LeaveManagement/LeaveProfile', 13, N'', 1, N'System',GETDATE(), 30, 0, 0)	
	-- /End Leave Profile 

	-- Threshold Limit (316)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 316)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(316, 205, N'Threshold Limit', N'LeaveManagement/ThresholdLimit', 14, N'', 1, N'System',GETDATE(), 31, 0, 0)	
	-- /End Threshold Limit 

	-- Entitlement & Rules (317)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 317)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(317, 205, N'Entitlement & Rules', N'LeaveManagement/Entitlement', 15, N'', 0, N'System',GETDATE(), 32, 0, 0)	
	-- /End Entitlement & Rules

	-- Public Holiday Benifit Employees (401)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 401)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(401, 205, N'Public Holiday Benifit', N'LeaveManagement/PublicHolidayBenifitEmployees', 15, N'', 1, N'System',GETDATE(), 32, 0, 0)	

	-- Email Template (414)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 414)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(414, 205, N'Email Template', N'LeaveManagement/EmailTemplate', 16, N'', 1, N'System',GETDATE(), 33, 0, 0)	

-- /End Leave Administration

-- Time & Attendance
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 206)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(206, 101, N'Time & Attendance',NULL, 16, N'sidenav-icon fas fa-hourglass-half', 1, N'System',GETDATE(), 33, 0, 0)			

	-- T&A Exception Codes (318)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 318)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(318, 206, N'T&A Exception Codes', N'Definitions/ExceptionType', 17, N'', 1, N'System',GETDATE(), 34, 0, 0)	
	-- /End T&A Exception Codes

	-- Reconciliation Parameter Group (319)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 319)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(319, 206, N'Reconciliation Parameter Group',N'Definitions/ReconciliationParameterGroup', 18, N'', 1, N'System',GETDATE(), 35, 0, 0)	
	-- /End Reconciliation Parameter Group 

	-- Overtime Definitions (320)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 320)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(320, 206, N'Overtime Definitions', N'Rules/OvertimeSettings', 19, N'', 1, N'System',GETDATE(), 36, 0, 0)	
	-- /End Overtime Definitions 

	-- Pay Codes (321)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 321)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(321, 206, N'Pay Codes', N'Definitions/Paycode', 20, N'', 1, N'System',GETDATE(), 37, 0, 0)	
	-- /End Pay Codes

	-- Pay Group (322)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 322)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(322, 206, N'Pay Group', N'Definitions/Paygroup', 21, N'', 1, N'System',GETDATE(), 38, 0, 0)	
	-- /End Pay Group
-- /End Time & Attendance

-- Maritime Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 207)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(207, 101, N'Maritime Setup',NULL, 22, N'sidenav-icon fas fa-anchor', 1, N'System',GETDATE(), 39, 0, 0)			


	-- Berth Setup (323)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 323)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(323, 207, N'Berth Setup', N'MariTime/Berth', 23, N'', 1, N'System',GETDATE(), 40, 0, 0)
	-- /End Berth Setup

	-- Location Definitions (334)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 334)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(334, 207, N'Location Definitions', N'MariTime/Locations', 24, N'', 1, N'System',GETDATE(), 41, 0, 0)
	-- /End Location Definitions (334)

	-- Crane Setup (335)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 335)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(335, 207, N'Crane Setup', N'MariTime/CraneSetup', 25, N'', 1, N'System',GETDATE(), 42, 0, 0)
	-- /End Crane Setup (335)

	-- Equipment Types (336)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 336)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(336, 207, N'Equipment Types', N'MariTime/EquipmentTypes', 26, N'', 1, N'System',GETDATE(), 43, 0, 0)
	-- /End Equipment Types (336)

	-- Equipment Setup (337)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 337)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(337, 207, N'Equipment Setup', N'MariTime/Equipment', 27, N'', 1, N'System',GETDATE(), 44, 0, 0)
	-- /End Equipment Setup (337)

	-- Equipment Requirement Matrix (338)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 338)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(338, 207, N'Equipment Requirement Matrix', N'MariTime/EquipmentRequirementMatrix', 28, N'', 1, N'System',GETDATE(), 45, 0, 0)
	-- /End Equipment Requirement Matrix

	-- Equipment Requirement Matrix Template (339)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 339)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(339, 207, N'Equipment Requirement Matrix Template', N'MariTime/EquipmentRequirementMatrixTemplate', 29, N'', 1, N'System',GETDATE(), 46, 0, 0)
	-- /End Equipment Requirement Matrix Template (338)

		
	-- Skill Requirement Matrix Template (340)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 340)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(340, 207, N'Skill Requirement Matrix Template', N'MariTime/SkillRequirementMatrixTemplate', 30, N'', 1, N'System',GETDATE(), 47, 0, 0)
	--/ End Skill Requirement Matrix Template (339)

-- /End Maritime Setup

-- Operations Deployment Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 208)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(208, 101, N'Operations Deployment Setup',NULL, 31, N'sidenav-icon fas fa-chalkboard-teacher', 1, N'System',GETDATE(), 48, 0, 0)			

	-- Relief Rule Setup (341)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 341)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(341, 208, N'Relief Rule Setup', N'MariTime/ReliefRuleSetup', 32, N'', 1, N'System',GETDATE(), 49, 0, 0)
	-- /End Relief Rule Setup

	-- THP Setting (342)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 342)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(342, 208, N'THP Setting', N'Rules/THPSettings', 33, N'', 1, N'System',GETDATE(), 50, 0, 0)
	-- /End THP Setting

	-- Allocation Rules (343)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 343)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(343, 208, N'Allocation Rules', N'Rules/AllocationRule', 34, N'', 1, N'System',GETDATE(), 51, 0, 0)
	-- /End Allocation Rules

-- /End Operations Deployment Setup

-- ESS Workflow Setup
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 209)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(209, 101, N'ESS Workflow Setup',NULL, 35, N'sidenav-icon fas fa-portrait', 1, N'System',GETDATE(), 52, 0, 0)			

	-- ESS Function Definition (344)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 344)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(344, 209, N'ESS Function Definition', N'Workflow/WorkflowModule', 36, N'', 1, N'System',GETDATE(), 53, 0, 0)
	-- /End ESS Function Definition

	-- Approval Routing Definition (344)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 345)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(345, 209, N'Approval Routing Definition', N'Workflow/WorkflowRoute', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	-- /End Approval Routing Definition

-- /End ESS Workflow Setup

-- Audit Menu (227)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 227)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(227, 101, N'Audit',NULL, 37, N'sidenav-icon fas fa-portrait', 1, N'System',GETDATE(), 54, 0, 0)			

	-- Schedule Period (407)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 407)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(407, 227, N'Schedule Period', N'Definitions/SchedulePeriod', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	-- /End Schedule Period

	-- Shift Audit (408)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 408)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(408, 227, N'Shift Audit', N'Definitions/ShiftAudit', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	-- /End Schedule Period

	-- Shift Audit (409)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 409)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(409, 227, N'THP Periods', N'Rules/THPPeriods', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	-- /End Schedule Period

	-- User Login Audit (418)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 418)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(418, 227, N'User Activity', N'Security/Home/UserLoginAuditIndex', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	-- /End User Login Audit
--/End Audit Menu

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Employee Administration [102]

-- Employee (210)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 210)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(210, 102, N'Employee',NULL, 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 55, 0, 0)			

	-- Employee Profile (346)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 346)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(346, 210, N'Employee Profile',  N'Employee/EmployeeProfile', 2, N'', 1, N'System',GETDATE(), 56, 0, 0)	
	-- /End Employee Profile

	-- Roster Group Assignment (347)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 347)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(347, 210, N'Roster Group Assignment',  N'Employee/RosterGroup', 3, N'', 1, N'System',GETDATE(), 57, 0, 0)	
	-- /End Roster Group Assignment (346)

	-- Movement/Transfers (348)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 348)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(348, 210, N'Movement/Transfers',  N'Employee/EmployeeMovement', 4, N'', 1, N'System',GETDATE(), 58, 0, 0)
	-- /End Movement/Transfers

	-- Employee Leave Profile (348)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 349)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(349, 210, N'Employee Leave Profile ',  N'LeaveManagement/EmployeeLeaveProfile', 5, N'', 1, N'System',GETDATE(), 59, 0, 0)
	-- /End Employee Leave Profile (348)

	-- Leave Balance Audit (397)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 397)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(397, 210, N'Leave Balance Audit',  N'LeaveManagement/EmployeeLeaveProfile/LeaveBalanceAuditIndex', 6, N'', 1, N'System',GETDATE(), 59, 0, 0)
	-- /End Leave Balance Audit 

	-- Employee Approval Route (399)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 399)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(399, 210, N'Employee Approval Route',  N'Employee/EmployeeApproval', 7, N'', 1, N'System',GETDATE(), 59, 0, 0)

	-- /End Employee Approval Route

	-- Employee Approval Route (399)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 400)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(400, 210, N'Public Holiday Process Audit',  N'Employee/PublicHolidayProcessAudit', 7, N'', 1, N'System',GETDATE(), 59, 0, 0)

	-- /End Employee Approval Route

		-- Ramadan Period Setup (402)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 402)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(402, 210, N'Ramadan Period', N'Definitions/RamadanPeriod', 7, N'', 1, N'System',GETDATE(), 59, 0, 0)	
	-- /End Ramadan Period

	-- Ramadan Period Employee List (402)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 403)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(403, 210, N'Ramadan Period Employee List', N'Definitions/RamadanPeriodEmployees', 7, N'', 1, N'System',GETDATE(), 59, 0, 0)	
	-- /End Ramadan Period

	-- Pending Leave Records (406)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 406)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(406, 210, N'Pending Leave Records', N'SelfService/LeaveRecords/AllPendingLeavesIndex', 7, N'', 1, N'System',GETDATE(), 59, 0, 0)	
	-- /End Ramadan Period


-- /End Employee

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Workforce Scheduling [103]

-- Scheduling [211]
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 211)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(211, 103, N'Scheduling',NULL, 1, N'sidenav-icon fas fa-calendar-alt', 1, N'System',GETDATE(), 60, 0, 0)	

	-- Employee Roster (390)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 390)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(390, 211, N'Employee Roster',N'Scheduler/EmployeeRoster', 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 61, 0, 0)			

	-- Manual Leave Creation (391)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 391)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(391, 211, N'Manual Leave Creation',N'Scheduler/EmployeeLeave', 2, N'sidenav-icon fas fa-user-tie', 0, N'System',GETDATE(), 62, 0, 0)			

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Employee Self Service [104]

-- Employee Kiosk (213)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 213)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(213, 104, N'Employee Kiosk',NULL, 1, N'sidenav-icon fas fa-chalkboard-teacher', 1, N'System',GETDATE(), 63, 1, 0)			

	-- View Calendar (350)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 350)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(350, 213, N'View Calendar',  N'SelfService/Calendar', 2, N'', 1, N'System',GETDATE(), 64, 1, 0)	
	-- /End View Calendar

	-- My Leave Profile (351)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 351)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(351, 213, N'My Leave Profile',  N'SelfService/MyLeaveProfile', 3, N'', 1, N'System',GETDATE(), 65, 1, 0)	
	-- /End My Leave Profile 

	-- Apply Leave (352)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 352)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(352, 213, N'Apply Leave',  N'SelfService/ApplyLeave', 4, N'', 1, N'System',GETDATE(), 66, 1, 0)	
	-- /End Apply Leave 

	-- Leave Records (353)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 353)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(353, 213, N'Leave Records',  N'SelfService/LeaveRecords', 5, N'', 1, N'System',GETDATE(), 67, 1, 0)	
	-- /End Leave Records 

	-- Apply Time Off (354)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 354)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(354, 213, N'Apply Time Off',  N'SelfService/ApplyLeave/ApplyTimeOffIndex', 6, N'', 1, N'System',GETDATE(), 68, 1, 0)	
	-- /End Apply Time Off 

	-- Request Day In Lieu (355)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 355)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(355, 213, N'Request Day In Lieu',  N'SelfService/ApplyLeave/RequestDaysInLieuIndex', 7, N'', 1, N'System',GETDATE(), 69, 1, 0)	
	-- /End Request Day In Lieu

	-- Apply on Behalf (356)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 356)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(356, 213, N'Apply on Behalf',  N'Approvers/ApplyOnBehalf', 8, N'', 1, N'System',GETDATE(), 70, 1, 0)	
	-- /End Apply on Behalf 
-- /End Employee Kiosk (213)

-- Approver Kiosk (214)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 214)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(214, 104, N'Approver Kiosk',NULL, 9, N'sidenav-icon fas fa-calendar-check', 1, N'System',GETDATE(), 71, 1, 0)

	-- Approve Time Off (357)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 357)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(357, 214, N'Approve Time Off',  N'SelfService/Transactions/PendingTimeOffIndex', 10, N'', 1, N'System',GETDATE(), 73, 1, 0)	
	-- /End Approve Time Off 

	-- Approve Days In Lieu (358)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 358)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(358, 214, N'Approve Days In Lieu',  N'SelfService/Transactions/PendingDaysInLieuIndex', 11, N'', 1, N'System',GETDATE(), 73, 1, 0)	
	-- /End Approve Days In Lieu 

	-- Approve Leave (359)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 359)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(359, 214, N'Approve Leave',  N'SelfService/Transactions/PendingTransactionsIndex', 12, N'', 1, N'System',GETDATE(), 74, 1, 0)	
	-- /End Approve Leave 

	-- Cancel Approved Leaves (356)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 412)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(412, 214, N'Cancel Approved Leaves',  N'Transactions/CancelApprovedLeaves', 8, N'', 1, N'System',GETDATE(), 70, 1, 0)	
	Else
		UPDATE	C_Menu SET MenuLink = N'Transactions/CancelApprovedLeaves' Where MenuID = 412
	-- /End Apply on Behalf 
-- /End Approver Kiosk 

-- Clinic Portal (215)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 215)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(215, 104, N'Clinic Portal',NULL, 13, N'sidenav-icon fas fa-clinic-medical', 1, N'System',GETDATE(), 75, 1, 0)

	-- Sick/Injury Leave (360)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 360)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(360, 215, N'Sick/Injury Leave',  N'SelfService/ClinicalAccess', 14, N'', 1, N'System',GETDATE(), 76, 1, 0)	
	-- /End Sick/Injury Leave

	-- Cancel Leaves (360)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 405)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(405, 215, N'Sick/Injury Cancellation',  N'SelfService/ClinicalAccess/CancelClinicalLeaves', 15, N'', 1, N'System',GETDATE(), 77, 1, 0)	
	-- /End Sick/Injury Leave

-- /End Clinic Portal (215)

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Operation Planning & Execution [105]

-- Operations Workload Planning (216)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 216)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(216, 105, N'Workload Planning',NULL, 1, N'sidenav-icon fas fa-ship', 1, N'System',GETDATE(), 77, 0, 0)			

	-- Workload Planner (361)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 361)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(361, 216, N'Workload Planner',  N'Planning/DailyPlanning', 2, N'', 1, N'System',GETDATE(), 78, 0, 0)	
	-- /End Worklod Planner

	-- Resource Set Definition (362)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 362)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(362, 216, N'Resource Set Definition', N'MariTime/ResourceSet', 3, N'', 1, N'System',GETDATE(), 79, 0, 0)
	-- /End Resource Set Definition (362)
	
-- /End Operations Workload Planning (216)

-- Operations Workforce Execution (217)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 217)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(217, 105, N'Workforce Execution',NULL, 4, N'sidenav-icon fas fa-cogs', 1, N'System',GETDATE(), 80, 0, 0)			

	-- Operations Duty Manager (363)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 363)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(363, 217, N'Operations Duty Manager', N'Operations/DailyOperation', 5, N'', 1, N'System',GETDATE(), 81, 0, 0)
	-- /End Operations Duty Manager (363)

	-- Operations Duty Manager (413)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 413)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(413, 217, N'TOS Productivity Summary', N'Operations/DailyOperation/BoxMovementSummaryIndex', 6, N'', 1, N'System',GETDATE(), 81, 0, 0)
	-- /End Operations Duty Manager (363)

-- /End Operations Workforce Execution (217)

-- Execution Functions (218)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 218)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(218, 105, N'Execution Functions',NULL, 6, N'sidenav-icon fas fa-user-tie', 0, N'System',GETDATE(), 82, 0, 0)			

	-- Employee Attendance Status Change (364)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 364)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(364, 218, N'Employee Attendance Status Change', N'Planning/DailyOperation', 7, N'', 0, N'System',GETDATE(), 83, 0, 0)
	-- /End Employee Attendance Status Change

	-- Employee Shift Time Change (365)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 365)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(365, 218, N'Employee Shift Time Change', NULL, 8, N'', 0, N'System',GETDATE(), 84, 0, 0)
	-- /End Employee Shift Time Change (365)

	-- Swap Employee Work (366)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 366)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(366, 218, N'Swap Employee Work', NULL, 9, N'', 0, N'System',GETDATE(), 85, 0, 0)
	-- /End Swap Employee Work (366)

	-- Reassign Employee Work (367)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 367)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(367, 218, N'Reassign Employee Work', NULL, 10, N'', 0, N'System',GETDATE(), 86, 0, 0)
	-- /End Reassign Employee Work (367)

	-- Assignment of Unassigned Work (368)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 368)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(368, 218, N'Assignment of Unassigned Work', N'Planning/DailyOperation', 11, N'', 0, N'System',GETDATE(), 87, 0, 0)
	-- /End Assignment of Unassigned Work

	-- Remove Equipment/Activity (369)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 369)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(369, 218, N'Remove Equipment/Activity', NULL, 12, N'', 0, N'System',GETDATE(), 88, 0, 0)
	-- /End Remove Equipment/Activity (369)

	-- Replace Equipment (370)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 370)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(370, 218, N'Replace Equipment', NULL, 13, N'', 0, N'System',GETDATE(), 89, 0, 0)
	-- /End Replace Equipment (370)

	-- Add New Equipment/Activity (371)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 371)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(371, 218, N'Employee Shift Time Change', NULL, 14, N'', 1, N'System',GETDATE(), 90, 0, 0)
	-- /End Add New Equipment/Activity (371)

	-- Equipment/Activity Time Change (372)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 372)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(372, 218, N'Equipment/Activity Time Change', NULL, 15, N'', 0, N'System',GETDATE(), 91, 0, 0)
	-- /End Equipment/Activity Time Change (372)
	
-- /End Execution Functions (218)

-- Maintenance
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 219)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(219, 105, N'Maintenance',NULL, 1, N'sidenav-icon fas fa-hammer', 7, N'System',GETDATE(), 92, 0, 0)	

	-- Equipment Maintenance Update (219)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 392)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(392, 219, N'Equipment Maintenance',N'MariTime/EquipmentMaintenance', 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 93, 0, 0)			

-- /End Equipment Maintenance Update (219)

-- E-Attendance Monitoring (220)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 220)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(220, 105, N'E-Attendance Monitoring',NULL, 1, N'', 0, N'System',GETDATE(), 94, 0, 0)			

-- /End E-Attendance Monitoring (220)

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Time & Attendance [106]

-- Attendance & Clocking [211]
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 221)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(221, 106, N'Attendance & Clocking',NULL, 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 95, 0, 0)	

	-- Attendance Reconciliation (221)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 393)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(393, 221, N'Attendance Reconciliation',N'TimeAttendance/ManageAttendance', 1, N'sidenav-icon fas fa-user-clock', 1, N'System',GETDATE(), 96, 0, 0)			

	-- /End Attendance Reconciliation (221)
	
	-- Weekly Attendance Reconciliation (398)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 398)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(398, 221, N'Weekly Attendance',N'TimeAttendance/ManageAttendance/WeeklyAttendanceIndex', 1, N'sidenav-icon fas fa-user-clock', 1, N'System',GETDATE(), 96, 0, 0)			

	-- /End Weekly Attendance Reconciliation (398)

	-- Raw Clocking (222)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 394)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(394, 221, N'Raw Clocking',N'TimeAttendance/ManageRawClocking', 2, N'', 1, N'System',GETDATE(), 97, 0, 0)			
	-- /End Raw Clocking (222)
	
	-- Update Clock Out Time (410)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 410)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(410, 221, N'Update ClockOut Time',N'TimeAttendance/ManageAttendance/UpdateClockOutTimeIndex', 5, N'', 1, N'System',GETDATE(), 97, 0, 0)			
	-- /End Raw Clocking (410)
SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO

UPDATE c_MEnu SET MenuLink=N'TimeAttendance/ManageAttendance/ReProcessReconAndCostingIndex' Where MenuId = 412SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO

-- Reports [107]

-- Scheduler Reports (223)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 223)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(223, 107, N'Scheduler Reports',NULL, 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 98, 0, 0)

	-- Employee Details (373)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 373)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(373, 223, N'Employee Details', N'Reports/EmployeeDetailsListReport', 2, N'', 1, N'System',GETDATE(), 99, 0, 0)
	-- /End Employee Details (373)

	-- Overall Employee Roster (374)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 374)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(374, 223, N'Overall Employee Roster', N'Reports/OverAllEmployeeRoster', 3, N'', 1, N'System',GETDATE(), 100, 0, 0)
	-- /End Overall Employee Roster (374)

	-- Overall Actual Hours Report (375)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 375)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(375, 223, N'Overall Actual Hours', N'Reports/OverAllActualHours', 4, N'', 1, N'System',GETDATE(), 101, 0, 0)
	-- /End Overall Actual Hours Report (375)

-- /End Scheduler Reports (223)

-- Duty Manager Reports (224)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 224)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(224, 107, N'Duty Manager Reports',NULL, 2, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 102, 0, 0)
	
	-- Daily Booking (376)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 376)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(376, 224, N'Daily Booking', N'Reports/PlanningReports/DailyBookingReport', 1, N'', 1, N'System',GETDATE(), 103, 0, 0)
	-- /End Daily Booking (376)

	-- Equipment Booking (377)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 377)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(377, 224, N'Equipment Booking', N'Reports/PlanningReports/EquipmentBookingReport', 2, N'', 1, N'System',GETDATE(), 104, 0, 0)
	-- /End Equipment Booking (377)

	-- Shift Report (378)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 378)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(378, 224, N'Shift Report', 'Reports/ShiftDetailsListReport', 3, N'', 1, N'System',GETDATE(), 105, 0, 0)
	-- /End Shift Report (378)

	-- Overtime Summary (379)
	 IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 379)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(379, 224, N'Overtime Summary', N'Reports/OvertimeSummary', 2, N'', 1, N'System',GETDATE(), 106, 0, 0)
	-- /End Overtime Summary (379)

	-- THP Listing (380)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 380)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(380, 224, N'THP Listing', N'Reports/ThpListingDetails', 4, N'', 1, N'System',GETDATE(), 107, 0, 0)
	-- /End THP Listing (380)

	-- Standby Booking (381)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 381)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(381, 224, N'Standby Booking', N'Reports/StandByEmployee', 5, N'', 1, N'System',GETDATE(), 108, 0, 0)
	-- /End Standby Booking (381)

	-- Unassigned Work (382)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 382)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(382, 224, N'Unassigned Work', N'Reports/UncoveredDetails', 6, N'', 1, N'System',GETDATE(), 109, 0, 0)
	-- /End Unassigned Work (382)

	-- Acting Incentive Report (395)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 395)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(395, 224, N'Acting Incentive Summmary ', N'Reports/ActingIncentive', 7, N'', 1, N'System',GETDATE(), 110, 0, 0)
	-- /End Acting Incentive (395)


-- /End Duty Manager Reports (224)

-- T&A Reports (225)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 225)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(225, 107, N'T&A Reports',NULL, 3, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 111, 0, 0)	

	-- HR Attendance Details (383)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 383)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(383, 225, N'HR Attendance Details', N'Reports/HRAttendanceDetails', 1, N'', 1, N'System',GETDATE(), 112, 0, 0)
	-- /End HR Attendance Details (383)

	-- Time Sheet Summary (383)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 396)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(396, 225, N'Time Sheet Summary', N'Reports/TimeSheetSummary', 2, N'', 1, N'System',GETDATE(), 113, 0, 0)
	-- /End HR Attendance Details (396)

-- /End T&A Reports (225)

-- ESS Reports (226)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 226)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(226, 107, N'ESS Reports',NULL, 4, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 114, 0, 0)	

	-- Monthly Leave Report (384)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 384)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(384, 226, N'Monthly Leave', N'ESSReports/MonthlyLeaveReport', 1, N'', 1, N'System',GETDATE(), 115, 0, 0)
	-- /End Monthly Leave Report (384)

	-- Leave Report (385)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 385)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(385, 226, N'Leave Report', N'ESSReports/LeaveReport', 2, N'', 2, N'System',GETDATE(), 116, 0, 0)
	-- /End Leave Report (385)

	-- Leave Profile Report (386)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 386)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(386, 226, N'Leave Profile', N'ESSReports/LeaveProfileReport', 3, N'', 1, N'System',GETDATE(), 117, 0, 0)
	-- /End Leave Profile Report (386)

	-- Leave History Report (387)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 387)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(387, 226, N'Leave History', N'ESSReports/LeaveHistoryReport', 4, N'', 1, N'System',GETDATE(), 118, 0, 0)
	-- /End Leave History Report (387)

	-- Individual Leave Report (388)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 388)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(388, 226, N'Individual Leave', N'ESSReports/IndividualLeaveReport', 5, N'', 1, N'System',GETDATE(), 119, 0, 0)
	-- /End Individual leave Report (388)

	-- Weekly Leave Report (389)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 389)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(389, 226, N'Weekly Leave', N'ESSReports/WeeklyLeaveReport', 6, N'', 1, N'System',GETDATE(), 120, 0, 0)
	-- /End Weekly Leave Report (389)

	-- Sick Leave Report (404)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 404)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(404, 226, N'Sick Leave', N'ESSReports/SickLeaveReport', 7, N'', 1, N'System',GETDATE(), 121, 0, 0)
	-- /End Weekly Leave Report (404)

-- /End ESS Reports (226)


SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO

/****** Object:  UserDefinedFunction [dbo].[fnStringToTable]    Script Date: 10/20/2018 4:39:13 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

     
CREATE FUNCTION [dbo].[fnStringToTable]              
(              
 @psCSString NVARCHAR(Max)             
)              
RETURNS @otTemp TABLE(sID NVARCHAR(Max))              
AS              
BEGIN              
 DECLARE @sTemp NVARCHAR(Max)              
              
 WHILE LEN(@psCSString) > 0              
 BEGIN              
  SET @sTemp = LEFT(@psCSString, ISNULL(NULLIF(CHARINDEX(',', @psCSString) - 1, -1),LEN(@psCSString)))              
  SET @psCSString = SUBSTRING(@psCSString,ISNULL(NULLIF(CHARINDEX(',', @psCSString), 0),LEN(@psCSString)) + 1, LEN(@psCSString))              
  INSERT INTO @otTemp VALUES (@sTemp)              
 END              
              
RETURN              
END




GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prApp_AddResourceSetDetails')
	DROP PROC prApp_AddResourceSetDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC prApp_AddResourceSetDetails
	@ResourceSetId bigint = NULL,
	@SkillId bigint = NULL,
	@Requirement int = NULL,
	@LocationId bigint = NULL,
	@CreatedBy nvarchar(100) = NULL

AS

INSERT M_ResourceSetDetails(ResourceSetId, SkillId, Requirement, LocationId, CreatedBy, CreatedDate)
VALUES (@ResourceSetId, @SkillId, @Requirement, @LocationId, @CreatedBy,GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prApp_GetResourceSetDetailsByResourceSetDetId')
	DROP PROC prApp_GetResourceSetDetailsByResourceSetDetId
GO

----------------------------------------------------------------------------
-- Select a single record from M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC prApp_GetResourceSetDetailsByResourceSetDetId
	@ResourceSetDetId bigint
AS

SELECT	ResourceSetDetId,
	ResourceSetId,
	SkillId,
	Requirement,
	LocationId,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_ResourceSetDetails
WHERE 	ResourceSetDetId = @ResourceSetDetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prApp_GetResourceSetDetailsByResourceSetId')
	DROP PROC prApp_GetResourceSetDetailsByResourceSetId
GO

----------------------------------------------------------------------------
-- Select a single record from M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC prApp_GetResourceSetDetailsByResourceSetId
	@ResourceSetId bigint
AS

SELECT	ResourceSetDetId,
		ResourceSetId,
		M_ResourceSetDetails.SkillId,
		D_Skill.Skill SkillName,
		M_ResourceSetDetails.Requirement,
		M_ResourceSetDetails.LocationId,
		M_Locations.LocationName,
		M_ResourceSetDetails.CreatedBy,
		M_ResourceSetDetails.CreatedDate,
		M_ResourceSetDetails.UpdatedBy,
		M_ResourceSetDetails.UpdatedDate
FROM	M_ResourceSetDetails WITH (NOLOCK)
		INNER JOIN D_Skill ON M_ResourceSetDetails.SkillId = D_Skill.SkillId
		LEFT OUTER JOIN M_Locations ON M_ResourceSetDetails.LocationId = M_Locations.LocationId
WHERE 	ResourceSetId = @ResourceSetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prA_AddShiftByShiftId')
	DROP PROC prA_AddShiftByShiftId
GO

CREATE PROCEDURE prA_AddShiftByShiftId
(
	@ShiftId		BigInt,
	@AuditAction	nVarchar(500),
	@AuditActionId	Int,
	@AuditActionBy	nVarchar(50) = NULL
)
AS
BEGIN	 
	
	If (@AuditActionId = 1 OR @AuditActionId = 2 OR @AuditActionId = 3 OR @AuditActionId = 14 
		OR @AuditActionId = 16 OR @AuditActionId = 17 OR @AuditActionId = 10 OR @AuditActionId = 18)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime, CreatedBy, CreatedDate, ActionBy)
		SELECT  @ShiftId, S_Shifts.EmployeeId, @AuditAction, GETDATE(), D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, S_Shifts.CreatedBy, S_Shifts.CreatedDate, @AuditActionBy
		FROM	S_Shifts WITH (NOLOCK) 
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		WHERE	ShiftId			=	@ShiftId
	
		SELECT  CAST(@@Identity AS bigint)   
	END
	Else If (@AuditActionId = 11)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime,  ClockIn, InStatus, ReconStatus, ActionBy)
		SELECT	ShiftId, EmployeeId, @AuditAction, GETDATE(), D_SHiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, S_Shifts.InTime, Convert(nVarchar(10),S_Shifts.ReconStatusId), S_Shifts.InStatus,
				@AuditActionBy
		FROM	S_Shifts WITH (NOLOCK) INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		WHERE	ShiftId			=	@ShiftId

		SELECT  CAST(@@Identity AS bigint)   
	END
	Else If (@AuditActionId = 12)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime,  ClockOut, OutStatus, ReconStatus, ActionBy)
		SELECT	ShiftId, EmployeeId, @AuditAction, GETDATE(), D_SHiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, S_Shifts.OutTime, S_Shifts.OutStatus, Convert(nVarchar(10),S_Shifts.ReconStatusId), @AuditActionBy
		FROM	S_Shifts WITH (NOLOCK) INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		WHERE	ShiftId			=	@ShiftId

		SELECT  CAST(@@Identity AS bigint)   
	END
	Else If (@AuditActionId = 13 OR @AuditActionId = 5) -- In & Out Both Updated / Updated Reconciliation Process
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime,  
		 ClockIn, InStatus, ClockOut, OutStatus, ReconStatus,  ActionBy)
		SELECT	ShiftId, EmployeeId, @AuditAction, GETDATE(), D_SHiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, S_Shifts.InTime, 
				S_Shifts.InStatus, S_Shifts.OutTime, S_Shifts.OutStatus, Convert(nVarchar(10),S_Shifts.ReconStatusId), @AuditActionBy
		FROM	S_Shifts WITH (NOLOCK) INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		WHERE	ShiftId			=	@ShiftId

		SELECT  CAST(@@Identity AS bigint)   
	END
	Else If (@AuditActionId = 7) 
	BEGIN
		DECLARE @@ShiftId BigInt = 0, @@LeaveDate Date, @@EmployeeId BigInt = 0, @@ShiftBandName nVarchar(50),
				@@ShiftStartTime DateTime, @@ShiftEndTime DateTime 

		-- For Leave Application Details Retrieve Shift 
		SELECT	@@ShiftId			=	IsNull(S_EmployeeLeaves.ShiftId,0), 
				@@LeaveDate			=	Convert(Date,FromDate),
				@@EmployeeId		=	S_EmployeeLeaves.EmployeeId,
				@@ShiftBandName		=	D_ShiftBand.ShiftBandName,
				@@ShiftStartTime	=	S_Shifts.ActualStartTime,
				@@ShiftEndTime		=	S_Shifts.ActualEndTime
		FROM	S_EmployeeLeaves WITH (NOLOCK) 
				INNER JOIN S_Shifts WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_SHifts.ShiftBandId = D_ShiftBand.ShiftBandCode
		WHERE	S_EmployeeLeaves.LeaveId	=	@ShiftId

		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime, LeaveType, LeaveAppliedBy, 
		 LeaveApprovedBy,  LeaveAppliedDate, LeaveApprovedDate, ActionBy)
		SELECT	@@ShiftId, @@EmployeeId, @AuditAction, GETDATE(), @@ShiftBandName, @@ShiftStartTime, @@ShiftEndTime, 
				D_ExceptionCodes.ExcpetionCodeName, L_Leaves.AppliedBy, L_Leaves.ApprovedBy, 
				L_Leaves.AppliedDate, L_Leaves.ApprovedDate, @AuditActionBy
		FROM	L_Leaves WITH (NOLOCK) 
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_Leaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
		WHERE	L_Leaves.EmployeeId		=	@@EmployeeId
		AND		Convert(Date,@@LeaveDate) >= Convert(Date,L_Leaves.LeaveStart)
		AND		Convert(Date,@@LeaveDate) <= Convert(Date,L_Leaves.LeaveEnd) 

		SELECT  CAST(@@Identity AS bigint) 
	END
	Else If (@AuditActionId = 15)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ActionBy, ShiftBandName, ShiftStartTime, ShiftEndTime, ClockIn, ClockOut,
		 InStatus, OutStatus, ShiftCost)
		SELECT	S_Shifts.ShiftId, S_Shifts.EmployeeId, @AuditAction, GETDATE(), @AuditActionBy, 
				D_ShiftBand.ShiftBandCode, S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, 
				S_Shifts.InTime, S_Shifts.OutTime, S_Shifts.InStatus, S_Shifts.OutStatus, 
				STUFF(	(SELECT '; ', DPC.PayCode + ' : ' +  Convert(nVarchar(20),PSC.StartTime,120) + ' ' + 
								Convert(nvarchar(20),PSC.EndTime, 120)  + ' ' +  Convert(nVarchar(10),PSC.ActualHour)
						FROM	P_ShiftCosts PSC WITH (NOLOCK) 
								INNER JOIN D_PayCodes DPC WITH (NOLOCK) ON PSC.PayCodeId = DPC.PayCodeId
								INNER JOIN S_Shifts SS WITH (NOLOCK) ON PSC.ShiftId = SS.ShiftId
								INNER JOIN D_ShiftBand DSB WITH (NOLOCK) ON DSB.ShiftBandId = SS.ShiftBandId
						WHERE	PSC.ShiftId = @ShiftId
								FOR XML PATH('')), 1, 2, '')
				--STRING_AGG(	D_PayCodes.PayCode + ' : ' +  Convert(nVarchar(20),P_ShiftCosts.StartTime,120) + ' ' + 
				--			Convert(nvarchar(20),P_ShiftCosts.EndTime, 120)  + ' ' +  Convert(nVarchar(10),P_ShiftCosts.ActualHour), '; ')
		FROM	P_ShiftCosts WITH (NOLOCK) 
				INNER JOIN D_PayCodes WITH (NOLOCK) ON P_ShiftCosts.PayCodeId = D_PayCodes.PayCodeId
				INNER JOIN S_Shifts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_SHifts.ShiftId
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		where	P_ShiftCosts.ShiftId = @ShiftId
		GROUP BY S_Shifts.ShiftId, S_Shifts.EmployeeId, D_ShiftBand.ShiftBandCode, S_Shifts.ActualStartTime, S_Shifts.ActualEndTime,
				 S_Shifts.InTime, S_Shifts.OutTime, S_Shifts.InStatus, S_Shifts.OutStatus, P_ShiftCosts.CreatedBy

		SELECT  CAST(@@Identity AS bigint)

		
		
		--SELECT 1 
	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prA_GetUserLoginAudit')
	DROP PROC prA_GetUserLoginAudit
GO

CREATE PROCEDURE prA_GetUserLoginAudit
(
	@UserId			BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@SecurityRoleId	BigInt
)
AS
BEGIN
	SELECT	C_User.UserName, C_UserAudit.ActionType, C_UserAudit.ActionDescription, C_UserAudit.ActionDate, C_UserAudit.TraceLog,
			C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName, 
			C_OrganizationNode.OUName
	FROM	C_UserAudit WITH (NOLOCK) 
			LEFT OUTER JOIN C_User WITH (NOLOCK) ON C_User.UserID = C_UserAudit.UserId
			LEFT OUTER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
			LEFT OUTER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
	WHERE	(C_UserAudit.UserId		=	@UserId OR @UserId = 0)
	AND		Convert(Date,ActionDate) >= Convert(Date,@StartDate) 
	AND		Convert(Date,ActionDate) <= Convert(Date,@EndDate)
	ORDER BY	C_User.UserName, Convert(Date,ActionDate)

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddEmployeeMovement')
	DROP PROC prC_AddEmployeeMovement
GO

----------------------------------------------------------------------------
-- Insert a single record into C_EmployeeMovement
----------------------------------------------------------------------------
CREATE PROC prC_AddEmployeeMovement
(
	@EmployeeId		BigInt,
	@OUId			BigInt,
	@StartDate		Date,
	@EndDate		Date,
	@PrimaryRoleId	BigInt,
	@RosterGroupId	BigInt,
	@OTSettingsId	BigInt,
	@ScheduleRuleId	BigInt,
	@MovementStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS

BEGIN
	
	INSERT INTO C_EmployeeMovement
	(EmployeeId, OUId, StartDate, EndDate, PrimaryRoleId, RosterGroupId, OTSettingsId, ScheduleRuleId, MovementStatus, 
	 ActiveStatus, CreatedBy, CreatedDate)
	VALUES(	@EmployeeId, @OUId, @StartDate, @EndDate, @PrimaryRoleId, @RosterGroupId, @OTSettingsId, @ScheduleRuleId, 
			@MovementStatus, 1, @CreatedBy, GETDATE() )

	SELECT  CAST(@@Identity AS bigint) 
		
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddPermissions')
	DROP PROC prC_AddPermissions
GO

----------------------------------------------------------------------------
-- Insert a single record into C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_AddPermissions
	@OUId bigint = NULL,
	@MenuId bigint = NULL,
	@PermissionTypeId int = NULL,
	@SecurityRoleID bigint = NULL,
	@CreatedBy nvarchar(100)
AS

INSERT C_Permissions(OUId, MenuId, PermissionTypeId, SecurityRoleID, CreatedBy, CreatedDate)
VALUES (@OUId, @MenuId, COALESCE(@PermissionTypeId, (1)), @SecurityRoleID, @CreatedBy, GETDATE())

SELECT SCOPE_IDENTITY()

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddSecurityRoleMenuPermissions')
	DROP PROCEDURE prC_AddSecurityRoleMenuPermissions
GO

CREATE PROC prC_AddSecurityRoleMenuPermissions
(
	@SecurityRoleId		BigInt,
	@MenuId				BigInt,
	@PermissionTypeId	Int,
	@CreatedBy			nVarchar(50)
)
AS
	INSERT INTO C_SecurityRolePermissions
	(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
	VALUES(@SecurityRoleId, @MenuId, @PermissionTypeId, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS INTEGER) 

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddUserAudit')
	DROP PROC prC_AddUserAudit
GO

CREATE PROCEDURE [dbo].[prC_AddUserAudit]    
(
	@UserId				BigInt,
	@UserName			nVarchar(255),
	@ActionType			Int,
	@ActionDescription	nVarchar(max),
	@ActionLocation		nVarchar(255)
)
AS
BEGIN
	
	INSERT INTO C_UserAudit
	(UserId, UserName, ActionDate, ActionType, ActionDescription, TraceLog)
	VALUES(@UserId, @UserName, GETDATE(), @ActionType, @ActionDescription, @ActionLocation)

	SELECT CAST(@@Identity AS BigInt)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddUserSecurityRole')
	DROP PROCEDURE prC_AddUserSecurityRole
GO

CREATE PROC prC_AddUserSecurityRole
(
	@UserId			BigInt,
	@SecurityRoleId	BigInt,
	@ActiveStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS
	INSERT INTO C_UserSecurityRole
	(UserId, SecurityRoleId, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@UserId, @SecurityRoleId, @ActiveStatus, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS INTEGER) 

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddUserSecurityRoleOU')
	DROP PROCEDURE prC_AddUserSecurityRoleOU
GO

CREATE PROC prC_AddUserSecurityRoleOU
(
	@UserSecurityRoleId		BigInt,
	@OUId					BigInt,
	@ActiveStatus			Bit,
	@CreatedBy				nVarchar(50)
)
AS
	INSERT INTO C_UserSecurityRoleOU
	(UserSecurityRoleId, OUId, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@UserSecurityRoleId, @OUId, @ActiveStatus, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS INTEGER) 

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_AddUserSecurityRoles')
	DROP PROC prC_AddUserSecurityRoles
GO

----------------------------------------------------------------------------
-- Insert a single record into C_UserSecurityRoles
----------------------------------------------------------------------------
CREATE PROC prC_AddUserSecurityRoles
	@UserId bigint,
	@SecurityRoleId bigint,
	@StartDate datetime,
	@EndDate datetime = NULL,
	@CreatedBy nvarchar(100) = NULL
AS
DECLARE @UserSecurityRoleId BigInt = 0

BEGIN

	SELECT	@UserSecurityRoleId  = IsNull(UserSecurityRoleId,0) 
	FROM	C_UserSecurityRoles WITH(NOLOCK) 
	WHERE	UserId = @UserId

	If (@UserSecurityRoleId  = 0)
	BEGIN
		INSERT C_UserSecurityRoles(UserId, SecurityRoleId, StartDate, EndDate, CreatedBy, CreatedDate)
		VALUES (@UserId, @SecurityRoleId, @StartDate, @EndDate, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY()
	END
	ELSE
	BEGIN
		UPDATE	C_UserSecurityRoles
		SET		SecurityRoleId = @SecurityRoleId
		WHERE	UserSecurityRoleId = @UserSecurityRoleId 

		UPDATE	C_User 
		SET		UserRoleID	=	@UserSecurityRoleId
		WHERE	UserID		=	@UserId

		SELECT 1
	END
END

GO
/****** Object:  StoredProcedure [dbo].[prC_DeleteEmployeeRoleById]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_DeleteEmployeeRoleById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_DeleteEmployeeRoleById]
GO

/****** Object:  StoredProcedure [dbo].[prC_DeleteEmployeeRoleById]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_DeleteEmployeeRoleById]
(
	@EmployeeRoleId	BigInt
)
AS
BEGIN

	DELETE FROM C_EmployeeRoles 
	WHERE	EmployeeRoleId = @EmployeeRoleId

	SELECT 1
END 

GO





IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_DeletePermissionsByPermissionId')
	DROP PROC prC_DeletePermissionsByPermissionId
GO

----------------------------------------------------------------------------
-- Delete a single record from C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_DeletePermissionsByPermissionId
	@PermissionId bigint
AS

DELETE	C_Permissions
WHERE 	PermissionId = @PermissionId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_DeletePermissionsBySecurityRoleId')
	DROP PROC prC_DeletePermissionsBySecurityRoleId
GO

----------------------------------------------------------------------------
-- Delete a single record from C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_DeletePermissionsBySecurityRoleId
	@SecurityRoleId bigint
AS

DELETE	C_Permissions
WHERE 	SecurityRoleId = @SecurityRoleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_DeleteUserSecurityRoleById')
	DROP PROCEDURE prC_DeleteUserSecurityRoleById
GO

CREATE PROC prC_DeleteUserSecurityRoleById
(
	@UserSecurityRoleId	BigInt

)
AS
	DELETE FROM C_UserSecurityRole
	WHERE	UserSecurityRoleId	=	@UserSecurityRoleId
		
	SELECT 1

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_DeleteUserSecurityRoleOUByUserSecurityRoleId')
	DROP PROCEDURE prC_DeleteUserSecurityRoleOUByUserSecurityRoleId
GO

CREATE PROC prC_DeleteUserSecurityRoleOUByUserSecurityRoleId
(
	@UserSecurityRoleId		BigInt
)
AS
	DELETE FROM C_UserSecurityRoleOU
	WHERE	UserSecurityRoleId = @UserSecurityRoleId

	SELECT 1
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_DeleteUserSecurityRolesByUserSecurityRoleId')
	DROP PROC prC_DeleteUserSecurityRolesByUserSecurityRoleId
GO

----------------------------------------------------------------------------
-- Delete a single record from C_UserSecurityRoles
----------------------------------------------------------------------------
CREATE PROC prC_DeleteUserSecurityRolesByUserSecurityRoleId
	@UserSecurityRoleId bigint
AS

DELETE	C_UserSecurityRoles
WHERE 	UserSecurityRoleId = @UserSecurityRoleId

SELECT 1

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeAndRoleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeAndRoleSel]

GO

CREATE PROCEDURE [dbo].[prC_EmployeeAndRoleSel]    
(
	@OUID			BigInt
)
AS
BEGIN
	SELECT	C_Employee.EmployeeId,
			C_Employee.RosterGroupId,
			ISNull(C_EmployeeRoles.RoleId,0) RoleId,
			OrgNode.OUId,
			D_Roles.PreparationTime PreparationMins,
			D_Roles.DePreparationTime DePreparationMins,
			IsNull(C_Employee.HourlyRate,0) HourlyRate,
			C_Employee.HiredDate,
			C_Employee.IsTerminated,
			C_Employee.TerminationDate
	FROM	C_Employee WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON  C_Employee.OUId = OrgNode.OUId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId 
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId
			AND C_EmployeeRoles.IsPrimaryRole = 1
	WHERE	OrgNode.OUId = @OUID
	AND		C_Employee.ActiveStatus = 1 AND OrgNode.ActiveStatus = 1
	ORDER BY D_Roles.RoleName
END
GO
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeBaseIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeBaseIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeBaseIdByName]    Script Date: 7/31/2018 10:16:24 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prC_EmployeeBaseIdByName]    
(
	@EmployeeBaseName nvarchar(500) 
)
AS
DECLARE @EmploymentBasisId bigint = 0
BEGIN

	SELECT	@EmploymentBasisId =  EmploymentBasisId
	FROM	D_EmploymentBasis WITH (NOLOCK)
	WHERE	EmploymentBasisCode =@EmployeeBaseName
 

 SELECT @EmploymentBasisId;
	 
END
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeContactsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeContactsDel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsDel]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeContactsDel]
(
	@EmployeeContactId		BigInt,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	UPDATE	C_EmployeeContacts
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	EmployeeContactId	=	@EmployeeContactId

	SELECT 1
END 

GO





/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsIns]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeContactsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeContactsIns]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsIns]    Script Date: 27/06/2018 7:47:03 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeContactsIns]    
(
	@EmployeeId			BigInt,
	@Relationship		nVarchar(100),
	@ContactPersonName	nVarchar(1000),
	@Address1			nVarchar(500),
	@Address2			nVarchar(500),
	@Address3			nVarchar(500),
	@City				nVarchar(500),
	@State				nVarchar(500),
	@PostCode			nVarchar(50),
	@Country			nVarchar(500),
	@HomePhoneNumber	nVarchar(50),
	@MobilePhoneNumber	nVarchar(50),
	@EmailAddress		nVarchar(500),
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	INSERT INTO C_EmployeeContacts
	(EmployeeId, Relationship, ContactName, Address1, Address2, Address3, City, State, PostCode, Country, HomePhone, MobilePhone, EmailAddress, 
	 ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @Relationship, @ContactPersonName, @Address1, @Address2, @Address3, @City, @State, @PostCode, 
		   @Country, @HomePhoneNumber, @MobilePhoneNumber, @EmailAddress, @ActiveStatus, @CreatedBy, GETDATE())		

	SELECT SCOPE_IDENTITY();
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeContactsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeContactsSel]
GO



CREATE PROCEDURE [dbo].[prC_EmployeeContactsSel]    
(
	@EmployeeId		BigInt
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	EmployeeContactId,
			EmployeeId, 
			Relationship, 
			ContactName,
			Address1, Address2, Address3, City, State, PostCode, Country, HomePhone HomePhoneNumber, MobilePhone MobileNumber, EmailAddress, ActiveStatus, CreatedBy, CreatedDate,
			UpdatedBy, UpdatedDate
	FROM	C_EmployeeContacts WITH (NOLOCK)
	WHERE	EmployeeId	=	@EmployeeId 
	ORDER BY ContactName
	
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeContactsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeContactsUpd]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeContactsUpd]    Script Date: 27/06/2018 7:47:12 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeContactsUpd]    
(
	@EmployeeContactId	BigInt,
	@EmployeeId			BigInt,
	@Relationship		nVarchar(100),
	@ContactPersonName	nVarchar(1000),
	@Address1			nVarchar(500),
	@Address2			nVarchar(500),
	@Address3			nVarchar(500),
	@City				nVarchar(500),
	@State				nVarchar(500),
	@PostCode			nVarchar(50),
	@Country			nVarchar(500),
	@HomePhoneNumber	nVarchar(50),
	@MobilePhoneNumber	nVarchar(50),
	@EmailAddress		nVarchar(500),
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	UPDATE	C_EmployeeContacts
	SET		EmployeeId			=	@EmployeeId, 
			Relationship		=	@Relationship, 
			ContactName			=	@ContactPersonName,
			Address1			=	@Address1, 
			Address2			=	@Address2, 
			Address3			=	@Address3, 
			City				=	@City, 
			State				=	@State,
			PostCode			=	@PostCode, 
			Country				=	@Country,
			HomePhone			=	@HomePhoneNumber,
			MobilePhone			=	@MobilePhoneNumber,
			EmailAddress		=	@EmailAddress,
			ActiveStatus		=	@ActiveStatus, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeContactId	=	@EmployeeContactId

	SELECT 1;
END

GO


/****** Object:  StoredProcedure [dbo].[prC_EmployeeDel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeDel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeDel]    Script Date: 22/06/2018 2:23:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeDel]
(
	@EmployeeId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	C_Employee
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	EmployeeId	=	@EmployeeId

	SELECT 1
END 

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeDisciplinaryDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeDisciplinaryDel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryDel]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeDisciplinaryDel]
(
	@DisciplinaryId			BigInt,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	--UPDATE	C_EmployeeDiciplinary
	--SET		ActiveStatus		=	0,
	--		UpdatedBy		=	@UpdatedBy,
	--		UpdatedDate		=	GetDate()
	--WHERE	DisciplinaryId	=	@DisciplinaryId

	DELETE FROM C_EmployeeDiciplinary WHERE	DisciplinaryId	=	@DisciplinaryId

	SELECT 1
END 

GO





/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeDisciplinaryIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeDisciplinaryIns]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeDisciplinaryIns]    
(
	@EmployeeId			BigInt,
	@OUId				BigInt,
	@StatusId			Int,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@Remarks			nVarchar(1000),
	@ActionDate			DateTime,
	@ActionStatus		Int,
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeeDiciplinary
	(EmployeeId, OUId, StatusId, StartDate, EndDate, Remarks, ActionDate, DisciplinaryActionStatus, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @OUId, @StatusId, @StartDate, @EndDate, @Remarks, @ActionDate, @ActionStatus, @ActiveStatus, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinarySel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeDisciplinarySel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeDisciplinarySel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinarySel]    Script Date: 02/07/2018 12:30:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeDisciplinarySel]    
(
	@DisciplinaryId	BigInt,
	@EmployeeID			Numeric(18,0)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	SELECT	DisciplinaryId,
			EmployeeId,
			StatusId,
			D_MasterCodes.CodeValue DiciplinaryStatusDescription,
			StartDate,
			Convert(nVarchar,StartDate,120) StartDateString,
			EndDate,
			Convert(nVarchar,EndDate,120) EndDateString,
			Remarks,ActionDate,
			Convert(nVarchar,ActionDate,120) ActionDateString,
			C_EmployeeDiciplinary.ActiveStatus, 
			C_EmployeeDiciplinary.CreatedBy, 
			C_EmployeeDiciplinary.CreatedDate,
			C_EmployeeDiciplinary.UpdatedBy,
			C_EmployeeDiciplinary.UpdatedDate,
			'' DataTableCheckBoxColumn,
			'' DateTableActionButtonColumn,
			C_EmployeeDiciplinary.OUId
	FROM	C_EmployeeDiciplinary WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_EmployeeDiciplinary.OUId = C_OrganizationNode.OUId
			LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = C_EmployeeDiciplinary.StatusId
	WHERE	(C_EmployeeDiciplinary.EmployeeId = @EmployeeID	 OR @EmployeeID	= 0)
	ORDER BY ActionDate
END

GO


/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeDisciplinaryUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeDisciplinaryUpd]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeDisciplinaryUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeDisciplinaryUpd]    
(
	@DisciplinaryId		BigInt,
	@EmployeeId			BigInt,
	@OUId				BigInt,
	@StatusId			Int,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@Remarks			nVarchar(1000),
	--@ActionDate			DateTime,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN

	UPDATE	C_EmployeeDiciplinary
	SET		EmployeeId			=	@EmployeeId, 
			OUId				=	@OUId, 
			StatusId			=	@StatusId, 
			StartDate			=	@StartDate, 
			EndDate				=	@EndDate, 
			Remarks				=	@Remarks, 
			--ActionDate			=	@ActionDate,
			ActiveStatus		=	@ActiveStatus,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	DisciplinaryId		=	@DisciplinaryId

	SELECT 1;
END
GO


/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeExcludeSkillsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeExcludeSkillsDel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsDel]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeExcludeSkillsDel]
(
	@SkillExcludeId		BigInt,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	UPDATE	C_EmployeeExcludeSkills
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	SkillExcludeId	=	@SkillExcludeId

	SELECT 1
END 

GO





/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeExcludeSkillsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeExcludeSkillsIns]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[prC_EmployeeExcludeSkillsIns]    
(
	@EmployeeId			BigInt,
	@SkillId			BigInt,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@Reason				nVarchar(500),
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeeExcludeSkills
	(EmployeeId, SkillId, SkillStartDate, SkillEndDate, Reason, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @SkillId, @StartDate, @EndDate, @Reason, @ActiveStatus, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeExcludeSkillsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeExcludeSkillsSel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsSel]    Script Date: 02/07/2018 12:30:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeExcludeSkillsSel]    
(
	@SkillExcludeId	BigInt,
	@EmployeeId		BigInt
)
AS
BEGIN

	SELECT	SkillExcludeId, 
			EmployeeId, 
			C_EmployeeExcludeSkills.SkillId, 
			
			SkillStartDate,
			SkillEndDate,
			Convert(nVarchar(10),SkillStartDate,120) SkillStartDateString, 
			Convert(nVarchar(10),SkillEndDate,120) SkillEndDateString,
			C_EmployeeExcludeSkills.ActiveStatus, 
			C_EmployeeExcludeSkills.CreatedBy, 
			C_EmployeeExcludeSkills.CreatedDate, 
			C_EmployeeExcludeSkills.UpdatedBy, 
			C_EmployeeExcludeSkills.UpdatedDate, 
			D_Skill.Skill SkillCode, D_Skill.Seq,
			D_Skill.SkillDesc SkillDescription,
			'' DataTableCheckBoxColumn,
			'' DateTableActionButtonColumn
	FROM	C_EmployeeExcludeSkills WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeExcludeSkills.SkillId
	WHERE	(EmployeeId		=	@EmployeeId OR @EmployeeId  = 0)

	ORDER BY D_Skill.Skill
	
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeExcludeSkillsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeExcludeSkillsUpd]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeExcludeSkillsUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeExcludeSkillsUpd]    
(
	@SkillExcludeId		BigInt,
	@EmployeeId			BigInt,
	@SkillId			BigInt,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@Reason				nVarchar(500),
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN

	UPDATE	C_EmployeeExcludeSkills
	SET		EmployeeId			=	@EmployeeId, 
			SkillId				=	@SkillId, 
			SkillStartDate		=	@StartDate, 
			SkillEndDate		=	@EndDate,
			Reason				=	@Reason, 
			ActiveStatus		=	@ActiveStatus, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	SkillExcludeId		=	@SkillExcludeId

	SELECT 1;
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeIdByEmployeeNumber]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeIdByEmployeeNumber]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeIdByEmployeeNumber]    Script Date: 7/31/2018 10:25:26 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 

CREATE PROCEDURE [dbo].[prC_EmployeeIdByEmployeeNumber]    
(
	@EmployeeNumber		nvarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  EmployeeId
	FROM	C_Employee WITH (NOLOCK)
	WHERE	EmployeeNumber =@EmployeeNumber
 

 SELECT @ValidateDuplicate;
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeIdChk]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeIdChk]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeIdChk]    Script Date: 7/23/2018 2:53:32 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prC_EmployeeIdChk]    
(
	@EmployeeId		bigint 
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_Employee WITH (NOLOCK)
	WHERE	EmployeeId =@EmployeeId
 

 SELECT @ValidateDuplicate;
	 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeIns]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeIns]    
(
	@OUId				BigInt,
	@EmployeeNumber		nVarchar(50),
	@BadgeNumber		nVarchar(50),
	@FirstName			nVarchar(500),
	@MiddleName			nVarchar(500),
	@LastName			nVarchar(500),
	@DisplayName		nVarchar(2500),
	@DateOfBirth		DateTime,
	@EmploymentBasisId	BigInt,
	@MaritalStatusId	int,
	@GenderId			int,
	@ReligionId			int,
	@Address1			nVarchar(500),
	@Address2			nVarchar(500),
	@Address3			nVarchar(500),
	@City				nVarchar(500),
	@PostCode			nVarchar(50),
	@State				nVarchar(500),
	@CountryId			int,
	@HomePhoneNumber	nVarchar(50),
	@MobilePhoneNumber	nVarchar(50),
	@EmailAddress		nVarchar(500),
	@IsTerminated		Bit,
	@TerminationDate	DateTime,
	@HiredDate			DateTime,
	@Position			nVarchar(500),
	@Title				nVarchar(50),
	@ProfilePhoto		nVarchar(max),
	@ScheduleRuleId     bigint,
	@PayGroupId         bigint,
	@OvertimeId			BigInt,
	@HourlyRate         decimal(18,4),
	@ContractedHours    decimal(18,4),
	@AlternatePhoto		nVarchar(max),
	@ProbationExpiry	Date,
	@ActiveStatus		Bit,
	@RosterGroupId		BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_Employee WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EmployeeNumber))) = LTrim(RTrim(Upper(@EmployeeNumber)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_Employee
		(OUId, 
		EmployeeNumber, 
		BadgeNumber, 
		FirstName, 
		MiddleName, 
		LastName, 
		DisplayName, 
		DateOfBirth, 
		EmploymentBasisId, 
		MaritalStatusId,
		GenderId, 
		ReligionId, 
		Address1, 
		Address2, 
		Address3, 
		City, 
		PostCode, 
		State, 
		CountryId, 
		HomePhone, 
		MobilePhone, 
		EmailAddress,
		IsTerminated, 
		TerminationDate, 
		HiredDate, 
		Position, 
		Title, 
		ProfilePhoto1,
		ScheduleRuleId,
		PayGroupId,
		OverTimeId,
		HourlyRate,
		ContractedHours,
		ProfilePhoto2, 
		ProbationExpiryDate,
		ActiveStatus, 
		RosterGroupId,
		CreatedBy, 
		CreatedDate)
		VALUES(@OUId, @EmployeeNumber, @BadgeNumber, @FirstName, @MiddleName, @LastName, @DisplayName, @DateOfBirth, @EmploymentBasisId,
			   @MaritalStatusId, @GenderId, @ReligionId, @Address1, @Address2, @Address3, @City, @PostCode, @State, @CountryId,
			   @HomePhoneNumber, @MobilePhoneNumber, @EmailAddress, @IsTerminated, @TerminationDate, @HiredDate, @Position, @Title,
			   @ProfilePhoto,@ScheduleRuleId,@PayGroupId, @OvertimeId, @HourlyRate,@ContractedHours ,@AlternatePhoto, @ProbationExpiry, @ActiveStatus, 
			   @RosterGroupId, @CreatedBy, GETDATE())	

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeOUDel]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeOUDel]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeOUDel]    
(
	@EmployeeOUId	BigInt,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	UPDATE	C_EmployeeOU
	SET		ActiveStatus	=	0, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeOUId	=	@EmployeeOUId

	SELECT 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeOUIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeOUIns]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeOUIns]    
(
	@OUId			BigInt,
	@EmployeeId		BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@IsPrimaryOU	Bit,
	@ActiveStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate = COUNT(*) 
	FROM	C_EmployeeOU
	WHERE	EmployeeId		=	@EmployeeId
	AND		OUId			=	@OUId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_EmployeeOU
		(OUId, EmployeeId, StartDate, EndDate, IsPrimaryOU, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OUId, @EmployeeId, @StartDate, @EndDate, @IsPrimaryOU, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	ELSE
		SELECT 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeOUSel]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeOUSel]    
(
	@EmployeeId		BigInt
)
AS
BEGIN

	SELECT	C_EmployeeOU.EmployeeOUId,
			C_EmployeeOU.EmployeeId,
			C_EmployeeOU.OUId,
			C_OrganizationNode.OUName,
			C_EmployeeOU.ActiveStatus,
			C_EmployeeOU.IsPrimaryOU,
			C_EmployeeOU.StartDate,
			C_EmployeeOU.EndDate,
			Convert(nVarchar(20),C_EmployeeOU.StartDate,120) StartDateString,
			Convert(nVarchar(20),C_EmployeeOU.EndDate,120) EndDateString,
			C_EmployeeOU.CreatedBy,
			C_EmployeeOU.UpdatedBy,
			C_EmployeeOU.CreatedDate,
			C_EmployeeOU.UpdatedDate
	FROM	C_EmployeeOU WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode WITH (NOLOCK) 
			ON C_EmployeeOU.OUId = C_OrganizationNode.OUId
	WHERE	(EmployeeId		=	@EmployeeId OR @EmployeeId = 0)
	--AND		C_EmployeeOU.ActiveStatus	=	1 
	AND		C_OrganizationNode.ActiveStatus = 1
	--AND		EndDate			>=	GETDATE()
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeOUUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeOUUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeOUUpd]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeOUUpd]    
(
	@EmployeeOUId	BigInt,
	@OUId			BigInt,
	@EmployeeId		BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@IsPrimaryOU	Bit,
	@ActiveStatus	Bit,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	UPDATE	C_EmployeeOU
	SET		OUId			=	@OUId, 
			EmployeeId		=	@EmployeeId, 
			StartDate		=	@StartDate, 
			EndDate			=	@EndDate, 
			IsPrimaryOU		=	@IsPrimaryOU, 
			ActiveStatus	=	@ActiveStatus, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeOUId	=	@EmployeeOUId

	SELECT 1
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesByOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeRolesByOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeRolesByOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesByOUSel]    Script Date: 02/07/2018 12:30:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeRolesByOUSel]    
(
	@OuId	BigInt
)
AS
BEGIN

	SELECT	EmployeeRoleId, 
			EmployeeId,
			C_EmployeeRoles.RoleId, 
			IsPrimaryRole,
			C_EmployeeRoles.CreatedBy, 
			C_EmployeeRoles.CreatedDate, 
			C_EmployeeRoles.UpdatedBy, 
			C_EmployeeRoles.UpdatedDate 

	FROM	C_EmployeeRoles WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	EXISTS (SELECT	EmployeeId 
					FROM	C_Employee WITH (NOLOCK) 
					WHERE	C_Employee.OUId = @OuId)
	ORDER BY C_EmployeeRoles.EmployeeId
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeRolesIdByEmployeeID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeRolesIdByEmployeeID]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesIdByEmployeeID]    Script Date: 7/31/2018 10:27:54 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prC_EmployeeRolesIdByEmployeeID]    
(
	@employeeid bigint
)
AS
DECLARE @EmployeeRoleId bigint = 0
BEGIN

	SELECT	@EmployeeRoleId =  EmployeeRoleId
	FROM	C_EmployeeRoles WITH (NOLOCK)
	WHERE	EmployeeId =@employeeid 
 

 SELECT @EmployeeRoleId;
	 
END
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeRolesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeRolesIns]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesIns]    Script Date: 02/07/2018 12:30:28 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeRolesIns]    
(
	@EmployeeId			BigInt,
	@RoleId				BigInt,
	@IsPrimaryRole		Bit,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeeRoles
	(EmployeeId, RoleId, IsPrimaryRole, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @RoleId, @IsPrimaryRole, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeRolesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeRolesSel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesSel]    Script Date: 02/07/2018 12:30:33 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeRolesSel]    
(
	@EmployeeRoleId		BigInt,
	@EmployeeId			BigInt
)
AS
BEGIN

	SELECT	EmployeeRoleId, 
			EmployeeId,
			C_EmployeeRoles.RoleId, 
			IsPrimaryRole,
			C_EmployeeRoles.CreatedBy, 
			C_EmployeeRoles.CreatedDate, 
			C_EmployeeRoles.UpdatedBy, 
			C_EmployeeRoles.UpdatedDate 

	FROM	C_EmployeeRoles WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	(EmployeeId		=	@EmployeeId OR @EmployeeId  = 0)

	ORDER BY D_Roles.RoleName
	
END
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeRolesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeRolesUpd]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeRolesUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeRolesUpd]    
(
	@EmployeeRoleId			BigInt,
	@EmployeeId				BigInt,
	@RoleId					BigInt,
	@IsPrimaryRole			Bit,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN

	UPDATE	C_EmployeeRoles
	SET		EmployeeId			=	@EmployeeId, 
			RoleId				=	@RoleId, 
			IsPrimaryRole		=	@IsPrimaryRole, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeRoleId		=	@EmployeeRoleId

	If (@IsPrimaryRole = 1)
	BEGIN
		UPDATE	S_Shifts
		SET		RoleId							=	@RoleId
		WHERE	EmployeeId						=	@EmployeeId
		AND		Convert(Date,ActualStartTime)	>=	Convert(Date,GETDATE())
	END
	SELECT 1;
END

GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeSel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSel]
GO

CREATE PROCEDURE [dbo].[prC_EmployeeSel]    
(
	@EmployeeID			Numeric(18,0),
	@OUID				BigInt,
	@EmpBasisItems		nVarchar(max),
	@RosterGroupItems	nVarchar(max),
	@RoleGroupItems		nVarchar(max)
)
AS
DECLARE @__empBasisItemsId INT = 0, @__rosterGroupItemsId INT = 0, @__roleGroupItemsId INT = 0
BEGIN

	SELECT TOP 1 @__empBasisItemsId = sID FROM fnStringToTable(@EmpBasisItems)
	
	SELECT TOP 1 @__rosterGroupItemsId = sID FROM fnStringToTable(@RosterGroupItems)

	SELECT TOP 1 @__roleGroupItemsId = sID FROM fnStringToTable(@RoleGroupItems)
	

	SELECT	Employee.EmployeeId,
			Employee.OUId,
			Employee.RosterGroupId,
			S_RosterGroup.GroupName RosterGroupCode,
			S_RosterGroup.GroupDesc RosterGroupDescription,
			EmployeeNumber,
			BadgeNumber,
			FirstName,
			MiddleName,
			LastName,
			DisplayName,
			DateOfBirth,
			Convert(nvarchar,DateOfBirth,120) DateOfBirthString,
			Employee.EmploymentBasisId,
			MaritalStatusId,
			GenderId,
			ReligionId,
			Address1,
			Address2,
			Address3,
			City,
			PostCode,
			State,
			CountryId,
			HomePhone HomePhoneNumber,
			MobilePhone MobileNumber,
			EmailAddress,
			IsTerminated,
			TerminationDate,
			Convert(nvarchar,TerminationDate,120) TerminationDateString,
			HiredDate,
			Convert(nvarchar,HiredDate,120) HireDateString,
			Position,
			Title,
			ProfilePhoto1,
			ProfilePhoto2,
			IsNull(Employee.ScheduleRuleId,0) ScheduleRuleId,
			IsNull(Employee.PayGroupId,0) PayGroupId,
			D_PayGroup.PayGroupCode,
			D_PayGroup.PayGroupDesc,
			IsNull(HourlyRate,0) HourlyRate,
			IsNull(ContractedHours,0) ContractedHours,
			Employee.ActiveStatus, 
			Employee.CreatedBy, 
			Employee.CreatedDate,
			Employee.UpdatedBy,
			Employee.UpdatedDate,
			OrgUnit.OUDesc OUDescription,
			OrgUnit.OUName,
			Employee.ProbationExpiryDate,
			D_Roles.RoleName,
			C_EmployeeRoles.RoleId,
			Convert(nvarchar,Employee.ProbationExpiryDate) ProbationExpiryString,
			D_EmploymentBasis.EmploymentBasisCode,
			D_EmploymentBasis.EmploymentBasisDesc,
			Employee.OverTimeId,
			IsNull(C_User.UserID,0) UserID,
			IsNull(C_User.UserName,'') UserName,
			Convert(nVarchar(20), C_User.LastLoginDate,120) LastLoginDateString,
			IsNull(C_UserSecurityRoles.UserSecurityRoleId,0) UserSecurityRoleId
	FROM	C_Employee Employee WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode OrgUnit WITH (NOLOCK) ON Employee.OUId = OrgUnit.OUId 
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = Employee.ScheduleRuleId
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK)  ON D_PayGroup.PayGroupId = Employee.PayGroupId
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
			LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = Employee.EmploymentBasisId
			LEFT OUTER JOIN C_User WITH (NOLOCK) ON Employee.EmployeeId = C_User.EmployeeID
			LEFT OUTER JOIN C_UserSecurityRoles WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRoles.UserId
	WHERE	(Employee.EmployeeId = @EmployeeID	 OR @EmployeeID	= 0)
	AND		OrgUnit.OUId = @OUID
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @__rosterGroupItemsId = 0)
	AND		(Employee.EmploymentBasisId IN (SELECT * FROM fnStringToTable(@EmpBasisItems)) OR @__empBasisItemsId = 0)
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @__roleGroupItemsId = 0)
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	--ORDER BY Employee.EmployeeNumber
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSkillsByOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSkillsByOUSel]

GO
CREATE PROCEDURE [dbo].[prC_EmployeeSkillsByOUSel]    
(
	@OuId	BigInt
)
AS
BEGIN
	SELECT	EmployeeSkillId, 
			EmployeeId, 
			C_EmployeeSkills.SkillId, 
			C_EmployeeSkills.SkillRating LevelNo, 
			C_EmployeeSkills.RotationNo,
			IsPrimary, 
			StartDate,
			EndDate,
			Convert(nVarchar(10),StartDate,120) StartDateString, 
			Convert(nVarchar(10),EndDate,120) EndDateString,
			C_EmployeeSkills.ActiveStatus, 
			C_EmployeeSkills.CreatedBy, 
			C_EmployeeSkills.CreatedDate, 
			C_EmployeeSkills.UpdatedBy, 
			C_EmployeeSkills.UpdatedDate, 
			D_Skill.Skill SkillCode, D_Skill.Seq,
			D_Skill.SkillDesc SkillDescription
	FROM	C_EmployeeSkills WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId
			--LEFT OUTER JOIN D_MasterCodes SkillLevel WITH (NOLOCK) ON SkillLevel.CodeId = C_EmployeeSkills.SkillId  
			--AND SkillLevel.CodeType = 'SkillLevel'
	WHERE	EXISTS (SELECT	EmployeeId 
					FROM	C_Employee WITH (NOLOCK) 
					WHERE	C_Employee.OUId = @OuId)
	ORDER BY C_EmployeeSkills.EmployeeId
	
END

GO


/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSkillsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSkillsDel]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsDel]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeSkillsDel]
(
	@EmployeeSkillId		BigInt,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	/*UPDATE	C_EmployeeSkills
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	EmployeeSkillId	=	@EmployeeSkillId */

	DELETE FROM C_EmployeeSkills
	WHERE	EmployeeSkillId = @EmployeeSkillId

	SELECT 1
END 

GO





/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSkillsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSkillsIns]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsIns]    Script Date: 02/07/2018 12:30:28 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeSkillsIns]    
(
	@EmployeeId			BigInt,
	@SkillId			BigInt,
	@SkillRating		Int,
	@RotationNo			Int,
	@IsPrimary			Bit,
	@IsActingSkill		Bit,
	@SkillGrantedDate	DateTime,
	@SkillRenewedDate	DateTime,
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	--TODO: Correct This Script
	INSERT INTO C_EmployeeSkills
	(EmployeeId, SkillId, SkillRating, RotationNo, IsPrimary, StartDate, EndDate, ActiveStatus, CreatedBy, CreatedDate, IsActingSkill)
	VALUES(@EmployeeId, @SkillId, @SkillRating, @RotationNo, @IsPrimary, @SkillGrantedDate, @SkillRenewedDate, @ActiveStatus, @CreatedBy, GETDATE(), @IsActingSkill)

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSkillsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSkillsSel]

GO
CREATE PROCEDURE [dbo].[prC_EmployeeSkillsSel]    
(
	@EmployeeSkillId	BigInt,
	@EmployeeId		BigInt
)
AS
BEGIN
	SELECT	EmployeeSkillId, 
			EmployeeId, 
			C_EmployeeSkills.SkillId, 
			C_EmployeeSkills.SkillRating LevelNo, 
			C_EmployeeSkills.RotationNo,
			IsPrimary, 
			StartDate,
			EndDate,
			Convert(nVarchar(10),StartDate,120) StartDateString, 
			Convert(nVarchar(10),EndDate,120) EndDateString,
			C_EmployeeSkills.ActiveStatus, 
			C_EmployeeSkills.IsActingSkill,
			C_EmployeeSkills.CreatedBy, 
			C_EmployeeSkills.CreatedDate, 
			C_EmployeeSkills.UpdatedBy, 
			C_EmployeeSkills.UpdatedDate, 
			D_Skill.Skill SkillCode, D_Skill.Seq,
			D_Skill.SkillDesc SkillDescription
	FROM	C_EmployeeSkills WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId
			--LEFT OUTER JOIN D_MasterCodes SkillLevel WITH (NOLOCK) ON SkillLevel.CodeId = C_EmployeeSkills.SkillId  
			--AND SkillLevel.CodeType = 'SkillLevel'
	WHERE	(EmployeeId		=	@EmployeeId OR @EmployeeId  = 0)
	AND		(EmployeeSkillId	=	0 OR 0 = 0)
	ORDER BY D_Skill.Seq
	
END

GO


/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeSkillsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeSkillsUpd]
GO

/****** Object:  StoredProcedure [dbo].[prC_EmployeeSkillsUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeSkillsUpd]    
(
	@EmployeeSkillId		BigInt,
	@EmployeeId				BigInt,
	@SkillId				BigInt,
	@SkillRating			Int,
	@RotationNo				Int,
	@IsPrimary				Bit,
	@IsActingSkill			Bit,
	@SkillGrantedDate		DateTime,
	@SkillRenewedDate		DateTime,
	@ActiveStatus			Bit,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	--TODO: Correct This Script
	UPDATE	C_EmployeeSkills
	SET		EmployeeId			=	@EmployeeId, 
			SkillId				=	@SkillId, 
			SkillRating			=	@SkillRating, 
			RotationNo			=	@RotationNo,
			IsPrimary			=	@IsPrimary, 
			IsActingSkill		=	@IsActingSkill,
			StartDate			=	@SkillGrantedDate, 
			EndDate				=	@SkillRenewedDate, 
			ActiveStatus		=	@ActiveStatus, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeSkillId		=	@EmployeeSkillId

	SELECT 1;
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeeUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeUpd]    Script Date: 7/24/2018 6:13:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeeUpd]    
(
	@EmployeeID			BigInt,
	@OUID				BigInt,
	@RoasterGroupId		BigInt,
	@EmployeeNumber		nVarchar(50),
	@BadgeNumber		nVarchar(50),
	@FirstName			nVarchar(500),
	@MiddleName			nVarchar(500),
	@LastName			nVarchar(500),
	@DisplayName		nVarchar(2500),
	@DateOfBirth		DateTime,
	@EmploymentBasisId	BigInt,
	@MaritalStatusId	int,
	@GenderId			int,
	@ReligionId			int,
	@Address1			nVarchar(500),
	@Address2			nVarchar(500),
	@Address3			nVarchar(500),
	@City				nVarchar(500),
	@PostCode			nVarchar(50),
	@State				nVarchar(500),
	@CountryId			int,
	@HomePhoneNumber	nVarchar(50),
	@MobilePhoneNumber	nVarchar(50),
	@EmailAddress		nVarchar(500),
	@IsTerminated		Bit,
	@TerminationDate	DateTime,
	@HiredDate			DateTime,
	@Position			nVarchar(500),
	@Title				nVarchar(50),
	@ProfilePhoto		nVarchar(max),
	@ScheduleRuleId     bigint,
	@PayGroupId         bigint,
	@OverTimeId			BigInt,
	@HourlyRate         decimal(18,4),
	@ContractedHours    decimal(18,4),
	@AlternatePhoto		nVarchar(max),
	@ProbationExpiry	Date,
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_Employee WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EmployeeNumber))) = LTrim(RTrim(Upper(@EmployeeNumber)))
	AND		EmployeeId != @EmployeeID

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	C_Employee 
		SET		OUId				=	@OUID, 
				RosterGroupId		=	@RoasterGroupId, 
				EmployeeNumber		=	@EmployeeNumber, 
				BadgeNumber			=	@BadgeNumber,
				FirstName			=	@FirstName,
				MiddleName			=	@MiddleName,
				LastName			=	@LastName,
				DisplayName			=	@DisplayName,
				DateOfBirth			=	@DateOfBirth,
				EmploymentBasisId	=	@EmploymentBasisId,
				MaritalStatusId		=	@MaritalStatusId,
				GenderId			=	@GenderId,
				ReligionId			=	@ReligionId,
				Address1			=	@Address1,
				Address2			=	@Address2,
				Address3			=	@Address3,
				City				=	@City,
				PostCode			=	@PostCode,
				State				=	@State,
				CountryId			=	@CountryId,
				HomePhone			=	@HomePhoneNumber,
				MobilePhone			=	@MobilePhoneNumber,
				EmailAddress		=	@EmailAddress,
				IsTerminated		=	@IsTerminated,
				TerminationDate		=	@TerminationDate,
				HiredDate			=	@HiredDate,
				Position			=	@Position,
				Title				=	@Title,
				ProfilePhoto1		=	@ProfilePhoto,
                ScheduleRuleId      =   @ScheduleRuleId,
				PayGroupId			=   @PayGroupId,
				OverTimeId			=	@OverTimeId,
				HourlyRate			=	@HourlyRate,
				ContractedHours		=	@ContractedHours,
				ProfilePhoto2		=	@AlternatePhoto,
				ProbationExpiryDate =	@ProbationExpiry,
				ActiveStatus		=	@IsActive, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	EmployeeID			=	@EmployeeID

		SELECT 1
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prC_GeneralMasterDel]    Script Date: 6/20/2018 11:08:41 AM ******/
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisByOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GeneralMasterDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GeneralMasterDel]
GO
/****** Object:  StoredProcedure [dbo].[prC_GeneralMasterDel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_GeneralMasterDel]    
(
	@CodeId		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	D_MasterCodes
	SET		ActiveStatus	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	CodeId		=	@CodeId

	SELECT 1
END


GO
/****** Object:  StoredProcedure [dbo].[prC_GetAllEmployees]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetAllEmployees]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetAllEmployees]
GO

CREATE PROCEDURE [dbo].[prC_GetAllEmployees]    
AS
BEGIN
	SELECT	C_Employee.EmployeeId, EmployeeNumber, DisplayName EmployeeName, C_OrganizationNode.OUId,C_OrganizationNode.OUName,D_Roles.RoleName PrimaryRoleName
	FROM	C_Employee WITH (NOLOCK)
	INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId=C_Employee.EmployeeId
	INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId=C_Employee.OUId
	INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId=C_EmployeeRoles.RoleId
	AND C_EmployeeRoles.IsPrimaryRole=1	
	WHERE C_Employee.ActiveStatus = 1 AND IsTerminated = 0
END

GO
/****** Object:  StoredProcedure [dbo].[prC_GetAllMenuItems]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetAllMenuItems]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetAllMenuItems]
GO

/****** Object:  StoredProcedure [dbo].[prC_GetAllMenuItems]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE  PROCEDURE [dbo].[prC_GetAllMenuItems]    
AS
BEGIN
	SELECT	MenuID,
			ParentMenuID, 
			MenuName, 
			MenuLink,
			DisplayOrder,
			MenuImage,
			IsActive, 
			CreatedBy, 
			CreatedDate,
			Sequence,
			IsSelfService,
			IsHorizontalMenuItem
	FROM	C_Menu WITH (NOLOCK)
	WHERE	IsActive = 1
	ORDER BY DisplayOrder
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetAllUserSecurityRole')
	DROP PROCEDURE prC_GetAllUserSecurityRole
GO

CREATE PROC prC_GetAllUserSecurityRole
AS
	SELECT	C_UserSecurityRole.UserSecurityRoleId,
			C_UserSecurityRole.UserId,
			C_UserSecurityRole.SecurityRoleId,
			C_UserSecurityRole.ActiveStatus,
			C_UserSecurityRole.CreatedBy,
			C_UserSecurityRole.UpdatedBy,
			C_UserSecurityRole.CreatedDate,
			C_UserSecurityRole.UpdatedDate,
			C_SecurityRole.SecurityRoleCode SecurityRoleName
	FROM	C_UserSecurityRole 
			INNER JOIN C_SecurityRole ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
	WHERE	C_UserSecurityRole.ActiveStatus = 1
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetChildMenuPermissionsByParentMenuId')
	DROP PROCEDURE prC_GetChildMenuPermissionsByParentMenuId
GO

CREATE PROC prC_GetChildMenuPermissionsByParentMenuId
(
	@OUId			BigInt,
	@UserId			BigInt,
	@ParentMenuId	BigInt
)
AS
	SELECT	C_Menu.*
	FROM	C_Menu WITH (NOLOCK) INNER JOIN 
			C_SecurityRolePermissions WITH (NOLOCK) ON C_Menu.MenuID = C_SecurityRolePermissions.MenuId
			INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_SecurityRolePermissions.SecurityRoleId = C_UserSecurityRole.SecurityRoleId
			INNER JOIN C_UserSecurityRoleOU WITH (NOLOCK) ON C_UserSecurityRoleOU.UserSecurityRoleId = C_UserSecurityRole.UserSecurityRoleId
	WHERE	C_UserSecurityRoleOU.OUId = @OUId
	AND		C_UserSecurityRole.UserId = @UserId
	AND		(C_Menu.ParentMenuID = @ParentMenuId OR @ParentMenuId = 0)
	--AND		C_SecurityRolePermissions.PermissionTypeId <> 0
	--UNION	ALL
	--SELECT	C_Menu.*
	--FROM	C_Menu WITH (NOLOCK) WHERE IsSelfService = 1
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetChildrenByParentOuId')
	DROP PROC prC_GetChildrenByParentOuId
GO

----------------------------------------------------------------------------
-- Insert a single record into prC_GetChildrenByParentOuId
----------------------------------------------------------------------------
CREATE PROC prC_GetChildrenByParentOuId
	@ParentOuId		BigInt,
	@UserId			BigInt
AS
	WITH OrganizationNodes
	AS 
	( 
		SELECT y.OUId, y.OUName, y.ParentOUId
		 FROM   C_OrganizationNode AS y
		 WHERE  y.ParentOUId is NOT NULL and ParentOUId = @ParentOuId
		 UNION ALL
		 SELECT ChildMenu.OUId, ChildMenu.OUName, ChildMenu.ParentOUId
		 FROM   OrganizationNodes AS ParentMenu
		 JOIN   C_OrganizationNode AS ChildMenu
		 ON ChildMenu.ParentOUId = ParentMenu.OUId
	)
	SELECT * FROM   OrganizationNodes


	SELECT	C_UserSecurityRoleOU.OUId, 
			C_UserSecurityRoleOU.UserSecurityRoleId,
			C_UserSecurityRoleOU.UserSecurityRoleOUId,
			C_UserSecurityRole.SecurityRoleId	
	FROM	C_UserSecurityRoleOU 
			INNER JOIN C_UserSecurityRole ON C_UserSecurityRoleOU.UserSecurityRoleId = C_UserSecurityRole.UserSecurityRoleId
			INNER JOIN C_User ON C_User.UserID = C_UserSecurityRole.UserId
	WHERE	C_User.UserID	=	@UserId
GO
/****** Object:  StoredProcedure [dbo].[prC_GetEmployeeForShiftCostById]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetEmployeeForShiftCostById]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prC_GetEmployeeForShiftCostById]
GO

CREATE PROCEDURE [dbo].[prC_GetEmployeeForShiftCostById]    
(
	@EmployeeId	BigInt
)
AS
BEGIN

	SELECT	EmployeeId, EmployeeNumber, PayGroupId, OvertimeId, Convert(Float,HourlyRate), ScheduleRuleId, Position
	FROM	C_Employee
	WHERE	EmployeeId = @EmployeeId	
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetEmployeeMovementByDate')
	DROP PROC prC_GetEmployeeMovementByDate
GO

----------------------------------------------------------------------------
-- Retrieve Employee Movement Records By Selected Date
----------------------------------------------------------------------------
CREATE PROC prC_GetEmployeeMovementByDate
(
	@MovementDate	Date
)
AS
BEGIN
	SELECT	MovementId,
			EmployeeId,
			OUId,
			StartDate,
			EndDate,
			PrimaryRoleId,
			RosterGroupId,
			OTSettingsId,
			ScheduleRuleId
	FROM	C_EmployeeMovement
	WHERE	Convert(Date,StartDate) <= Convert(Date,@MovementDate)
	AND		C_EmployeeMovement.MovementStatus = 0
END
GO
/****** Object:  StoredProcedure [dbo].[prC_GetEmployeesCount]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetEmployeesCount]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetEmployeesCount]
GO

CREATE PROCEDURE [dbo].[prC_GetEmployeesCount]    
AS
BEGIN
	SELECT COUNT(*) FROM C_Employee WITH (NOLOCK) WHERE ActiveStatus = 1 AND IsTerminated = 0
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetInterfacecConfigByInterfaceId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetInterfacecConfigByInterfaceId]
GO
/****** Object:  StoredProcedure [dbo].[prC_GetInterfacecConfigByInterfaceId]    Script Date: 7/23/2018 2:57:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_GetInterfacecConfigByInterfaceId]    
(	
	@InterfaceId	BigInt	
)
AS
BEGIN
	SELECT	C_InterfaceConfig.InterfaceConfigId,
			C_InterfaceConfig.InterfaceId,
			C_InterfaceConfig.ConfigType,
			C_InterfaceConfig.ConfigValue,
			C_InterfaceConfig.ActiveStatus,
			C_InterfaceConfig.CreatedBy,
			C_InterfaceConfig.CreatedDate,
			C_InterfaceConfig.UpdatedBy,
			C_InterfaceConfig.UpdatedDate
	FROM	C_InterfaceConfig WITH (NOLOCK)
	WHERE	C_InterfaceConfig.InterfaceId = @InterfaceId
	ORDER BY C_InterfaceConfig.InterfaceConfigId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetMenuPermissionsByOUAndUserId')
	DROP PROCEDURE prC_GetMenuPermissionsByOUAndUserId
GO

CREATE PROC prC_GetMenuPermissionsByOUAndUserId
(
	@OUId			BigInt,
	@UserId			BigInt,
	@ParentMenuId	BigInt
)
AS
	SELECT	DISTINCT C_Menu.*
	FROM	C_Menu WITH (NOLOCK) INNER JOIN 
			C_SecurityRolePermissions WITH (NOLOCK) ON C_Menu.MenuID = C_SecurityRolePermissions.MenuId
			INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_SecurityRolePermissions.SecurityRoleId = C_UserSecurityRole.SecurityRoleId 
			INNER JOIN C_UserSecurityRoleOU WITH (NOLOCK) ON C_UserSecurityRoleOU.UserSecurityRoleId = C_UserSecurityRole.UserSecurityRoleId
			INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
			AND C_SecurityRole.IsActive = 1
	WHERE	C_UserSecurityRoleOU.OUId = @OUId
	AND		C_UserSecurityRole.UserId = @UserId
	AND		(C_Menu.ParentMenuID = @ParentMenuId OR @ParentMenuId = 0)
	AND		C_SecurityRolePermissions.PermissionTypeId <> 0
	--UNION	ALL
	--SELECT	C_Menu.*
	--FROM	C_Menu WITH (NOLOCK) WHERE IsSelfService = 1
GO


/****** Object:  StoredProcedure [dbo].[prC_GetOrganizationUnits]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetOrganizationUnits]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetOrganizationUnits]
GO
/****** Object:  StoredProcedure [dbo].[prC_GetOrganizationUnits]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_GetOrganizationUnits]    
(
	@OUID		BigInt
)
AS
BEGIN
	SELECT  OrgUnit.OUID,
			OrgUnit.OUName,
			OrgUnit.OUDesc OUDescription,
			IsNull(OrgUnit.ParentOUID,0) ParentOUID,
			OrgUnit.ActiveStatus, 
			OrgUnit.CreatedBy,
			OrgUnit.CreatedDate,
			OrgUnit.UpdatedBy,
			OrgUnit.UpdatedDate,
			ISNull(ParentOrgUnit.OUName,'') ParentOrganization
	FROM	C_OrganizationNode OrgUnit WITH (NOLOCK) LEFT OUTER JOIN C_OrganizationNode ParentOrgUnit WITH (NOLOCK)
			ON ParentOrgUnit.OUId = OrgUnit.ParentOUId
	WHERE	(OrgUnit.OUID = @OUID OR @OUID = 0)
	AND		OrgUnit.ActiveStatus = 1
	ORDER BY OrgUnit.OUName

END



GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetPendingTerminationsByDate')
	DROP PROC prC_GetPendingTerminationsByDate
GO

----------------------------------------------------------------------------
-- Retrieve Pending Terminations From Disciplinary 
----------------------------------------------------------------------------
CREATE PROC prC_GetPendingTerminationsByDate
(
	@DisciplinaryStatus	Int,
	@TerminationDate	Date,
	@ActionStatus		Int
)
AS
BEGIN
	
	SELECT	DisciplinaryId,
			EmployeeId,
			OUId,
			StartDate,
			EndDate,
			Remarks,
			ActionDate,
			ActiveStatus,
			DisciplinaryActionStatus
	FROM	C_EmployeeDiciplinary WITH (NOLOCK)
	WHERE	Convert(Date,StartDate)		<=	Convert(Date,@TerminationDate)
	AND		DisciplinaryActionStatus	=	@ActionStatus
	AND		StatusId					=	@DisciplinaryStatus
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetPermissionsByPermissionId')
	DROP PROC prC_GetPermissionsByPermissionId
GO

----------------------------------------------------------------------------
-- Select a single record from C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_GetPermissionsByPermissionId
	@PermissionId bigint
AS

SELECT	PermissionId,
	OUId,
	MenuId,
	PermissionTypeId,
	SecurityRoleID,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	C_Permissions
WHERE 	PermissionId = @PermissionId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetPermissionsBySecurityRoleAndOuId')
	DROP PROC prC_GetPermissionsBySecurityRoleAndOuId
GO

----------------------------------------------------------------------------
-- Select a single record from C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_GetPermissionsBySecurityRoleAndOuId
	@SecurityRoleId BigInt,
	@OuId			BigInt
AS

SELECT	C_Menu.MenuID,
		IsNull(C_Menu.ParentMenuID,0) ParentMenuID,
		C_Menu.MenuName,
		C_Menu.DisplayOrder,
		C_Menu.Sequence,
		IsNull(C_Permissions.PermissionId,0) PermissionId,
		IsNull(C_OrganizationNode.OUId,0) OUId,
		C_OrganizationNode.OUName,
		IsNull(C_Permissions.PermissionTypeId,0) PermissionTypeId,
		IsNull(C_Permissions.SecurityRoleID,0) SecurityRoleID
FROM	C_Menu  
		LEFT OUTER JOIN C_Permissions ON C_Menu.MenuID = C_Permissions.MenuId AND C_Permissions.SecurityRoleID = @SecurityRoleId 
		LEFT OUTER JOIN C_OrganizationNode ON C_Permissions.OUId = C_OrganizationNode.OUId AND C_Permissions.OUId = @OuId
WHERE	C_Menu.IsActive = 1
ORDER BY C_Menu.ParentMenuID, C_Menu.DisplayOrder
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetSecurityRoleAndPermissionsById')
	DROP PROC prC_GetSecurityRoleAndPermissionsById
GO

----------------------------------------------------------------------------
-- Retrieve Security Role 
----------------------------------------------------------------------------
CREATE PROC prC_GetSecurityRoleAndPermissionsById
(
	@SecurityRoleId		BigInt
)
AS
BEGIN
	
	-- Get Security Role By Security 
	SELECT	C_SecurityRole.SecurityRoleID,
			C_SecurityRole.SecurityRoleCode RoleCode,
			C_SecurityRole.Description RoleDescription,
			C_SecurityRole.IsActive,
			C_SecurityRole.CreatedBy,
			C_SecurityRole.UpdatedBy,
			C_SecurityRole.CreatedDate,
			C_SecurityRole.UpdatedDate  
	FROM	C_SecurityRole 
	WHERE	C_SecurityRole.SecurityRoleID = @SecurityRoleId;

	WITH MenuItems
	AS ( SELECT y.MenuID, y.MenuName, y.ParentMenuID, y.MenuLink, y.Sequence 
		FROM   C_Menu AS y
		WHERE  y.ParentMenuID IS NULL
			AND y.IsHorizontalMenuItem = 1
		UNION ALL
		SELECT ChildMenu.MenuID, ChildMenu.MenuName, ChildMenu.ParentMenuID, ChildMenu.MenuLink, ChildMenu.Sequence
		FROM   MenuItems AS ParentMenu
		JOIN   C_Menu AS ChildMenu
		ON ChildMenu.ParentMenuID = ParentMenu.MenuID
		AND ChildMenu.IsHorizontalMenuItem = 0 
	)
	SELECT	MenuItems.*, 
			IsNull(C_SecurityRolePermissions.PermissionTypeId,0) PermissionTypeId,
			IsNull(C_SecurityRolePermissions.SecurityRolePermissionId,0) SecurityRolePermissionId,
			IsNull(C_SecurityRolePermissions.SecurityRoleId, 0) SecurityRoleId
	FROM   MenuItems LEFT OUTER JOIN C_SecurityRolePermissions ON MenuItems.MenuID = C_SecurityRolePermissions.MenuId
	where ParentMenuID IS NOT NULL 
	AND C_SecurityRolePermissions.SecurityRoleId = @SecurityRoleId
	ORDER BY Sequence;
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetSubModuleParentChildMenuItems')
	DROP PROC prC_GetSubModuleParentChildMenuItems
GO

----------------------------------------------------------------------------
-- Retrieve Recommended Employees To Swap.
----------------------------------------------------------------------------
CREATE PROC prC_GetSubModuleParentChildMenuItems
AS
BEGIN
	WITH MenuItems
	AS ( SELECT y.MenuID, y.MenuName, y.ParentMenuID, y.MenuLink, y.Sequence 
		 FROM   C_Menu AS y
		 WHERE  y.ParentMenuID IS NULL
				AND y.IsHorizontalMenuItem = 1 And IsActive = 1
		 UNION ALL
		 SELECT ChildMenu.MenuID, ChildMenu.MenuName, ChildMenu.ParentMenuID, ChildMenu.MenuLink, ChildMenu.Sequence
		 FROM   MenuItems AS ParentMenu
		 JOIN   C_Menu AS ChildMenu
		 ON ChildMenu.ParentMenuID = ParentMenu.MenuID
			AND ChildMenu.IsHorizontalMenuItem = 0 AND IsActive = 1)
	SELECT *
	FROM   MenuItems where ParentMenuID IS NOT NULL order by Sequence;
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetUserByUserName]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prC_GetUserByUserName]
GO

CREATE PROCEDURE [dbo].[prC_GetUserByUserName]    
(
	@UserName	 nVarchar(50)
)
AS
BEGIN
	SELECT	C_User.UserID,
			C_User.UserName,
			IsNull(C_User.EmployeeID,0) EmployeeID,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			IsNull(C_Employee.EmailAddress,'') LoginUserEmailAddress
	FROM	C_User WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
	WHERE	C_User.UserName		=	@UserName 
	AND		C_User.IsActive		=	1
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetUserSecurityRoleByUserId')
	DROP PROCEDURE prC_GetUserSecurityRoleByUserId
GO

CREATE PROC prC_GetUserSecurityRoleByUserId
( 
	@UserId				BigInt 
)
AS
	-- Get User Details
	SELECT	C_User.UserID,
			C_User.UserName,
			C_User.PasswordHash,
			C_User.PasswordSalt,
			IsNull(C_User.EmployeeID,0) EmployeeID,
			IsNull(C_Employee.EmployeeNumber,'') EmployeeNumber,
			IsNull(C_Employee.DisplayName,'') EmployeeName,
			IsNull(C_Employee.OUId, 0) LoginUserOuId,
			IsNull(C_OrganizationNode.OUName, '') LoginUserOuName,
			C_User.LastLoginDate,
			Convert(nVarchar(20),C_User.LastLoginDate,120) LastLoginDateString,
			C_User.ResetPassword,
			C_User.IsActive,
			C_User.CreatedBy,
			C_User.CreatedDate,
			C_User.UpdatedBy,
			C_User.UpdatedDate,
			C_User.ChangePasswordOnLogin
	FROM	C_User WITH (NOLOCK)
			LEFT OUTER JOIN C_Employee WITH (NOLOCK) ON C_USER.EmployeeID = C_Employee.EmployeeId
			LEFT OUTER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	WHERE	UserID	=	@UserId
	AND		IsActive = 1

	-- Get User Security Role By User Id
	SELECT	C_UserSecurityRole.UserSecurityRoleId,
			C_UserSecurityRole.UserId,
			C_UserSecurityRole.SecurityRoleId,
			C_UserSecurityRole.ActiveStatus,
			C_UserSecurityRole.CreatedBy,
			C_UserSecurityRole.UpdatedBy,
			C_UserSecurityRole.CreatedDate,
			C_UserSecurityRole.UpdatedDate,
			C_SecurityRole.SecurityRoleCode SecurityRoleName
	FROM	C_UserSecurityRole WITH (NOLOCK)
			INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
	WHERE	C_UserSecurityRole.UserId = @UserId
	AND		C_UserSecurityRole.ActiveStatus = 1

	-- Get User Security Role OU By User Id
	SELECT	C_UserSecurityRoleOU.UserSecurityRoleOUId,
			C_UserSecurityRoleOU.UserSecurityRoleId,
			C_UserSecurityRole.SecurityRoleId,
			C_UserSecurityRoleOU.OUId,
			C_OrganizationNode.OUName,
			C_UserSecurityRoleOU.ActiveStatus,
			C_UserSecurityRoleOU.CreatedBy,
			C_UserSecurityRoleOU.CreatedDate,
			C_UserSecurityRoleOU.UpdatedBy,
			C_UserSecurityRoleOU.UpdatedDate
	FROM	C_UserSecurityRoleOU WITH (NOLOCK)
			INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_UserSecurityRoleOU.UserSecurityRoleId = C_UserSecurityRole.UserSecurityRoleId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_UserSecurityRoleOU.OUId
	WHERE	C_UserSecurityRole.UserId = @UserId
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceLogIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceLogIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceLogIns]    Script Date: 7/23/2018 2:54:57 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prC_InterfaceLogIns]    
(
	@InterfaceId		bigint,
	@TranId				bigint,
	@RowNo				bigint,
	@FileContent		text,
	@MessageType		int,
	@Message			text,
	@CreatedBy			nvarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	--SELECT	@ValidateDuplicate =  COUNT(*)
	--FROM	C_InterfaceLog WITH (NOLOCK)
	--WHERE	InterfaceId =@InterfaceId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_InterfaceLog
		(InterfaceId, TranId, RowNo, FileContent, MessageType, Message, 
		 CreatedBy, CreatedDate)
		VALUES
		(
			@InterfaceId, @TranId, @RowNo, @FileContent, @MessageType, @Message, 
			@CreatedBy, getdate()
		)

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceLogSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceLogSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceLogSel]    Script Date: 7/23/2018 2:57:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_InterfaceLogSel]    
(	
	@TranId   	        BigInt	
)
AS
BEGIN
	SELECT	C_InterfaceLog.LogId,
			C_InterfaceLog.TranId,
			C_InterfaceLog.RowNo,
			C_InterfaceTransactions.FileName,
			C_InterfaceTransactions.InterfaceId,
			C_Interfaces.ModuleName InterfaceType,
			C_InterfaceLog.FileContent,
			C_InterfaceLog.MessageType,
			C_InterfaceLog.Message,
			C_InterfaceLog.CreatedBy,
			C_InterfaceLog.CreatedDate
	FROM	C_InterfaceLog 
			INNER JOIN C_InterfaceTransactions ON C_InterfaceLog.TranId = C_InterfaceTransactions.TranId
			INNER JOIN C_Interfaces ON C_InterfaceTransactions.InterfaceId = C_Interfaces.InterfaceId
	WHERE	(C_InterfaceLog.TranId = @TranId)
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfacesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfacesSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfacesSel]    Script Date: 7/23/2018 2:55:43 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
Create PROCEDURE [dbo].[prC_InterfacesSel]   
(
	@InterfaceId	 bigInt 
	
)
AS
BEGIN	 
	SELECT  	C_Interfaces.InterfaceId,
			    C_Interfaces.Type	, 
				C_Interfaces.Name,
				C_Interfaces. ModuleName,
				C_Interfaces.Method, 
				C_Interfaces.FileType ,				 
				C_Interfaces.SoftwareName ,
				C_Interfaces.FileNamePrefix ,
				C_Interfaces.FileLocation,
				C_Interfaces.FileFormat,  
				C_Interfaces.ActiveStatus, 
				C_Interfaces.CreatedBy,
				C_Interfaces.CreatedDate,
				C_Interfaces.UpdatedBy	,
				C_Interfaces.UpdatedDate	
	    FROM	C_Interfaces 		 
	WHERE	(InterfaceId = @InterfaceId OR @InterfaceId = 0)
	 
	Order By C_Interfaces.Name
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfacesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfacesUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfacesUpd]    Script Date: 7/23/2018 2:56:36 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prC_InterfacesUpd] 
(
	@InterfaceId			BigInt,
	@FileLocation			nVarchar(2000),
	@Name					nvarchar(500),
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_Interfaces WITH (NOLOCK)
	WHERE	 InterfaceId != @InterfaceId
	and LTrim(RTrim(Upper(Name))) = LTrim(RTrim(Upper(@Name)))

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	C_Interfaces 
		SET		FileLocation			=	@FileLocation,				  
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	InterfaceId			=	@InterfaceId

		SELECT 1
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceTransactions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceTransactions]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceTransactions]    Script Date: 7/23/2018 2:57:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_InterfaceTransactions]    
(	
	@TranId   	        BigInt	
)
AS
BEGIN
	SELECT	TOP 10 C_InterfaceTransactions.TranId,
			C_InterfaceTransactions.InterfaceId,
			C_InterfaceTransactions.InitializedDate,
			C_InterfaceTransactions.InitializedUser,
			C_InterfaceTransactions.StartDate,
			C_InterfaceTransactions.EndDate,
			C_InterfaceTransactions.Status,
			C_InterfaceTransactions.Remarks,
			C_InterfaceTransactions.FileName
	FROM	C_InterfaceTransactions  WITH (NOLOCK)
	WHERE	(C_InterfaceTransactions.TranId = @TranId OR @TranId = 0)
	ORDER BY C_InterfaceTransactions.StartDate DESC
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceTransactionsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceTransactionsDel]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceTransactionsDel]    Script Date: 7/23/2018 2:58:03 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prC_InterfaceTransactionsDel] 
(
	@TranId		BigInt	 
)
AS
BEGIN

DELETE FROM C_InterfaceLog WHERE TranId=@TranId
	 DELETE FROM C_InterfaceTransactions WHERE TranId=@TranId

	  

	SELECT 1
END 
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceTransactionsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceTransactionsIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceTransactionsIns]    Script Date: 7/23/2018 2:58:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 

Create PROCEDURE [dbo].[prC_InterfaceTransactionsIns]    
(
	@InterfaceId		bigint,
	@InitializedDate	datetime,
	@InitializedUser	nVarchar(50),
	@StartDate			datetime,
	@EndDate			datetime,
	@Status				int,
	@Remarks			nvarchar(max),
	@FileName			nvarchar(max) 
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	--SELECT	@ValidateDuplicate =  COUNT(*)
	--FROM	C_InterfaceTransactions WITH (NOLOCK)
	--WHERE	InterfaceId =@InterfaceId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_InterfaceTransactions
		(InterfaceId, InitializedDate, InitializedUser, StartDate, EndDate, Status, 
		 Remarks, FileName)
		VALUES
		(
			@InterfaceId, @InitializedDate, @InitializedUser, @StartDate, @EndDate, @Status, 
			@Remarks, @FileName
		)

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceTransactionsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceTransactionsSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_InterfaceTransactionsSel]    Script Date: 7/24/2018 4:26:10 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[prC_InterfaceTransactionsSel]    
(	
	 
	@interfaceId        bigint
	
)
AS
BEGIN
	SELECT	TOP 10 C_InterfaceTransactions.TranId,
			C_InterfaceTransactions.InterfaceId,
			C_InterfaceTransactions.InitializedDate,
			C_InterfaceTransactions.InitializedUser,
			C_InterfaceTransactions.StartDate,
			C_InterfaceTransactions.EndDate,
			C_InterfaceTransactions.Status,
			C_InterfaceTransactions.Remarks,
			C_InterfaceTransactions.FileName
	FROM	C_InterfaceTransactions  WITH (NOLOCK)
	--WHERE	(C_InterfaceTransactions.TranId = @TranId OR @TranId = 0)
	where C_InterfaceTransactions.InterfaceId = @interfaceId
	ORDER BY C_InterfaceTransactions.StartDate DESC
	
END
GO
/****** Object:  StoredProcedure [dbo].[prC_MenuSel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_MenuSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_MenuSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_MenuSel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE  PROCEDURE [dbo].[prC_MenuSel]    
(
	@MenuID			int,
	@UserId		BigInt,
	@OUId		BigInt,
	@IsActive	Bit
)
AS
BEGIN
	If (@UserId != 0)
	BEGIN
		SELECT	MenuID,
				ParentMenuID, 
				MenuName, 
				MenuLink,
				DisplayOrder,
				MenuImage,
				IsActive, 
				CreatedBy, 
				CreatedDate,
				Sequence
		FROM	C_Menu WITH (NOLOCK)
		WHERE	(MenuID = @MenuID OR @MenuID = 0)
		AND		IsActive = @IsActive
		AND		EXISTS (SELECT OUID FROM C_Permissions 
						INNER JOIN C_SecurityRole ON C_SecurityRole.SecurityRoleID = C_Permissions.SecurityRoleID 
						AND C_SecurityRole.IsActive = 1
						INNER JOIN C_UserSecurityRoles ON C_UserSecurityRoles.SecurityRoleId = C_SecurityRole.SecurityRoleID 
						AND	C_UserSecurityRoles.UserId = @UserId 
						AND C_Permissions.OUId = @OUId
						AND	C_Permissions.MenuId = C_Menu.MenuID)
		UNION
		SELECT	MenuID,
				ParentMenuID, 
				MenuName, 
				MenuLink,
				DisplayOrder,
				MenuImage,
				IsActive, 
				CreatedBy, 
				CreatedDate,
				Sequence
		FROM	C_Menu
		WHERE	IsSelfService = 1
		ORDER BY C_Menu.DisplayOrder
	END
	Else
	BEGIN
		SELECT	MenuID,
				ParentMenuID, 
				MenuName, 
				MenuLink,
				DisplayOrder,
				MenuImage,
				IsActive, 
				CreatedBy, 
				CreatedDate,
				Sequence
		FROM	C_Menu WITH (NOLOCK)
		WHERE	(MenuID = @MenuID OR @MenuID = 0)
		AND		IsActive = @IsActive
		ORDER BY  C_Menu.DisplayOrder
	END


END




GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeDel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_OrganizationNodeDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_OrganizationNodeDel]
GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeDel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_OrganizationNodeDel]    
(
	@OUID		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	C_OrganizationNode
	SET		ActiveStatus=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	OUID		=	@OUID

	SELECT 1
END


GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeIns]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_OrganizationNodeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_OrganizationNodeIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_OrganizationNodeIns]    
(
	@OUName			nVarchar(500),
	@OUDescription	nVarchar(2000),
	@ParentOUID		bigint,
	@IsActive		Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0, @OrgUnitScopeIdentity BigInt = 0, @SecurityRoleId BigInt = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_OrganizationNode WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(OUName))) = LTrim(RTrim(Upper(@OUName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_OrganizationNode 
		(OUName, OUDesc, ParentOUID, ActiveStatus, CreatedBy, CreatedDate)
		VALUES
		(
			@OUName, @OUDescription, @ParentOUID, @IsActive, @CreatedBy, GETDATE()
		)

		SET @OrgUnitScopeIdentity =  SCOPE_IDENTITY();

		-- Insert Data Into C_Permissions Table
		-- Find Security Role ID For Administrator Role
		SELECT @SecurityRoleId = C_SecurityRole.SecurityRoleID FROM C_SecurityRole WITH (NOLOCK) WHERE C_SecurityRole.SecurityRoleCode ='Administrator'

		If (@SecurityRoleId != 0)
		BEGIN
			INSERT INTO C_Permissions 
			(OUId, MenuId, PermissionTypeId, SecurityRoleID, CreatedBy, CreatedDate)
			SELECT @OrgUnitScopeIdentity, C_Menu.MenuID, 2, @SecurityRoleId,  @CreatedBy, GETDATE()
			FROM   C_Menu WITH (NOLOCK) WHERE NOT EXISTS (SELECT MenuId From C_Permissions WITH (NOLOCK) 
														  WHERE C_Permissions.SecurityRoleID = @SecurityRoleId AND C_Permissions.OUId = @OrgUnitScopeIdentity)
		END

		SELECT @OrgUnitScopeIdentity
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeSel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_OrganizationNodeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_OrganizationNodeSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeSel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_OrganizationNodeSel]    
(
	@OUID		BigInt,
	@UserId		BigInt
	--@IsActive	Bit
)
AS
BEGIN
	SELECT  OrgUnit.OUID,
			OrgUnit.OUName,
			OrgUnit.OUDesc OUDescription,
			IsNull(OrgUnit.ParentOUID,0) ParentOUID,
			OrgUnit.ActiveStatus, 
			OrgUnit.CreatedBy,
			OrgUnit.CreatedDate,
			OrgUnit.UpdatedBy,
			OrgUnit.UpdatedDate,
			ISNull(ParentOrgUnit.OUName,'') ParentOrganization
	FROM	C_OrganizationNode OrgUnit WITH (NOLOCK) LEFT OUTER JOIN C_OrganizationNode ParentOrgUnit WITH (NOLOCK) 
			ON ParentOrgUnit.OUId = OrgUnit.ParentOUId
	WHERE	(OrgUnit.OUID = @OUID OR @OUID = 0)
	AND		EXISTS (SELECT OUID 
					FROM C_UserSecurityRoleOU WITH (NOLOCK) 
					INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_UserSecurityRole.UserSecurityRoleId = C_UserSecurityRoleOU.UserSecurityRoleId
					INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_SecurityRole.SecurityRoleID = C_UserSecurityRole.SecurityRoleId
					AND C_UserSecurityRole.UserId = @UserId AND C_UserSecurityRoleOU.OUId = OrgUnit.OUId
					UNION
					SELECT OUID FROM C_Employee INNER JOIN C_USER 
								ON C_Employee.EmployeeId = C_User.EmployeeId 
								AND C_User.UserId = @UserId
								AND C_Employee.OUId = OrgUnit.OUId)
	--AND		EXISTS (SELECT OUID FROM C_Permissions 
	--							INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_SecurityRole.SecurityRoleID = C_Permissions.SecurityRoleID 
	--							INNER JOIN C_UserSecurityRoles WITH (NOLOCK) ON C_UserSecurityRoles.SecurityRoleId = C_SecurityRole.SecurityRoleID 
	--							AND	C_UserSecurityRoles.UserId = @UserId 
	--							AND	C_Permissions.OUId = OrgUnit.OUId
	--				UNION
	--				SELECT OUID FROM C_Employee INNER JOIN C_USER 
	--							ON C_Employee.EmployeeId = C_User.EmployeeId 
	--							AND C_User.UserId = @UserId
	--							AND C_Employee.OUId = OrgUnit.OUId)
	ORDER BY OrgUnit.OUName

END



GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_OrganizationNodeSelForTHP]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_OrganizationNodeSelForTHP]
GO
 

Create PROCEDURE [dbo].[prC_OrganizationNodeSelForTHP]    
(
	@OUID		BigInt

)
AS
BEGIN
	SELECT  OrgUnit.OUID,
			OrgUnit.OUName,
			OrgUnit.OUDesc OUDescription,
			IsNull(OrgUnit.ParentOUID,0) ParentOUID,
			OrgUnit.ActiveStatus, 
			OrgUnit.CreatedBy,
			OrgUnit.CreatedDate,
			OrgUnit.UpdatedBy,
			OrgUnit.UpdatedDate
			
	FROM	C_OrganizationNode OrgUnit			
	WHERE	(OrgUnit.OUID = @OUID OR @OUID = 0)
	
	--AND		ActiveStatus = @IsActive
	ORDER BY OrgUnit.OUName

END




GO


/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_OrganizationNodeUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_OrganizationNodeUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_OrganizationNodeUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_OrganizationNodeUpd]    
(
	@OUID			BigInt,
	@OUName			nVarchar(500),
	@OUDescription	nVarchar(2000),
	@ParentOUID		BigInt,
	@IsActive		Bit,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_OrganizationNode WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(OUName))) = LTrim(RTrim(Upper(@OUName)))
	AND		OUID != @OUID

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	C_OrganizationNode 
		SET		OUName			=	@OUName, 
				OUDesc	=	@OUDescription, 
				ParentOUID		=	@ParentOUID, 
				ActiveStatus		=	@IsActive, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	OUID			=	@OUID

		SELECT 1
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
/****** Object:  StoredProcedure [dbo].[prC_GetEmployeesCount]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_SearchEmployee]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_SearchEmployee]
GO

CREATE PROCEDURE [dbo].[prC_SearchEmployee]    
(
	@SearchEmployeeString	nVarchar(100),
	@FilteredOUString		nVarchar(max)
)
AS
BEGIN
	If (@filteredOUString = '') SET @filteredOUString = '0'

	SELECT	C_Employee.EmployeeId, 
			EmployeeNumber, 
			DisplayName EmployeeName, 
			C_Employee.OUId, 
			C_OrganizationNode.OUName,
			D_Roles.RoleName PrimaryRoleName,
			C_EmployeeRoles.RoleId PrimaryRoleId,
			C_Employee.EmailAddress ApplicantEmailId
	FROM	C_Employee WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
						AND (C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUString)) OR @FilteredOUString = '0')
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1
	WHERE	C_Employee.EmployeeNumber LIKE @SearchEmployeeString 
	OR		C_Employee.FirstName LIKE @SearchEmployeeString
	OR		C_Employee.LastName LIKE @SearchEmployeeString
	OR		C_Employee.MiddleName LIKE @SearchEmployeeString

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateEmployeeDetailsWithMovementDetails')
	DROP PROC prC_UpdateEmployeeDetailsWithMovementDetails
GO

----------------------------------------------------------------------------
-- Update Employee Details By Movement Details
-- This Will Update More Than 1 Table
----------------------------------------------------------------------------
CREATE PROC prC_UpdateEmployeeDetailsWithMovementDetails
(
	@EmployeeId		BigInt,
	@OUId			BigInt,
	@StartDate		Date,
	@EndDate		Date,
	@PrimaryRoleId	BigInt,
	@RosterGroupId	BigInt,
	@OTSettingsId	BigInt,
	@ScheduleRuleId	BigInt,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @PrimarySkillId		BigInt = 0, @EmployeeSkillId BigInt = 0, 
		@EmployeeOUId BigInt = 0, @UserSecurityRoleOUId BigInt = 0, @CurrentOUId BigInt = 0;
BEGIN
	
	-- Retrieve Existing Employee Skill Id From C_EmployeeSkills Table By Employee ID
	SELECT	@EmployeeSkillId = EmployeeSkillId
	FROM	C_EmployeeSkills WITH (NOLOCK)
	WHERE	EmployeeId	=	@EmployeeId
	AND		IsPrimary	=	1

	-- Retrieve Employee OUId From C_EmployeeOU Table By Employee Id And Primary OU
	SELECT	@EmployeeOUId	= EmployeeOUId
	FROM	C_EmployeeOU WITH (NOLOCK)
	WHERE	EmployeeId		=	@EmployeeId
	AND		IsPrimaryOU		=	1

	-- Retrieve Primary Skill Id By Selected Role Id
	SELECT	@PrimarySkillId	= IsNull(D_Roles.PrimarySkillId,0)
	FROM	D_Roles	WITH (NOLOCK)
	WHERE	D_Roles.RoleId	=	@PrimaryRoleId

	-- Get Employee Current OUId
	SELECT	@CurrentOUId	 = OUId From C_Employee Where EmployeeId = @EmployeeId

	-- Replace Old OUId With Moved OU Id IN Security Role OU
	UPDATE	C_UserSecurityRoleOU SET OUId = @OUId
	WHERE	C_UserSecurityRoleOU.UserSecurityRoleOUId IN 
			(	SELECT	C_UserSecurityRoleOU.UserSecurityRoleOUId
				FROM	C_UserSecurityRoleOU 
						INNER JOIN C_UserSecurityRole 
								ON C_UserSecurityRole.UserSecurityRoleId = C_UserSecurityRoleOU.UserSecurityRoleId
						INNER JOIN C_User ON C_User.UserID = C_UserSecurityRole.UserId
				WHERE	C_User.EmployeeID = @EmployeeId
				AND		C_UserSecurityRoleOU.OUId = @CurrentOUId
			)


	-- Update OUId,Roster GroupId, Overtime Settings Id, Schedule Rule Id
	UPDATE	C_Employee 
	SET		OUId				=	@OUId,
			RosterGroupId		=	@RosterGroupId,
			OvertimeId			=	@OTSettingsId,
			ScheduleRuleId		=	@ScheduleRuleId,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeId			=	@EmployeeId

	-- Update Employee Primary Role C_EmployeeRole
	UPDATE	C_EmployeeRoles 
	SET		RoleId			=	@PrimaryRoleId,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeId		=	@EmployeeId
	AND		IsPrimaryRole	=	1

	-- Update Employee Previous SKill Data Before Updating with new Id
	UPDATE	C_EmployeeSkills
	SET		IsPrimary		=	0,
			ActiveStatus	=	0,
			EndDate			=	DATEADD(DD, -1, @StartDate),
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeSkillId	=	@EmployeeSkillId

	-- Insert Employee Primary Skill With New Skill Updated Primary Role C_EmployeeSkills
	INSERT INTO C_EmployeeSkills
	(EmployeeId, SkillId, IsPrimary, StartDate, EndDate, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @PrimarySkillId, 1, @StartDate, @EndDate, 1, @UpdatedBy, GETDATE())


	-- Update Roster Group Details, Roster Group Id By Employee Id
	UPDATE	S_RosterGroupDetails
	SET		RosterGroupId	=	@RosterGroupId,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeId		=	@EmployeeId

	-- Update Current Employee OU End Date And Change The Status of Primary OU To False
	UPDATE	C_EmployeeOU	
	SET		IsPrimaryOU		=	0,
			ActiveStatus	=	0,
			EndDate			=	DATEADD(DD, -1, @StartDate),
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmployeeOUId	=	@EmployeeOUId

	-- Insert Employee OU Details With Movement Request OUID
	INSERT INTO C_EmployeeOU
	(EmployeeId, OUId, StartDate, EndDate, IsPrimaryOU, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @OUId, @StartDate, @EndDate, 1, 1, @UpdatedBy, GETDATE())

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateEmployeeMovementStauts')
	DROP PROC prC_UpdateEmployeeMovementStauts
GO

----------------------------------------------------------------------------
-- Update Employee Movement Status Details
----------------------------------------------------------------------------
CREATE PROC prC_UpdateEmployeeMovementStauts
(
	@EmployeeMovementId	BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	
	UPDATE C_EmployeeMovement
	SET		MovementStatus	=	1,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	MovementId		=	@EmployeeMovementId

	SELECT 1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateEmployeeTermination')
	DROP PROC prC_UpdateEmployeeTermination
GO

----------------------------------------------------------------------------
-- Update Employee Termination Details
----------------------------------------------------------------------------
CREATE PROC prC_UpdateEmployeeTermination
(
	@DisciplinaryId		BigInt,
	@EmployeeId			BigInt,
	@TerminationFrom	DateTime,
	@TerminationTo		DateTime,
	@ActionStatus		Int,
	@ProcessedBy		nVarchar(50)
)
AS
BEGIN
	
	-- Update Employee Table Termination Columns
	UPDATE	C_Employee
	SET		TerminationDate		=	@TerminationFrom,
			IsTerminated		=	1,
			ActiveStatus		=	0,
			UpdatedBy			=	@ProcessedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeId			=	@EmployeeId

	-- Delete Available Shifts From Termination Date Till 
	DELETE FROM S_Shifts
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@TerminationFrom)
	--AND		Convert(Date,ActualStartTime) <= Convert(Date,@TerminationTo)
	AND		S_Shifts.EmployeeId	=	@EmployeeId

	DELETE FROM C_User WHERE EmployeeId = @EmployeeId

	UPDATE	C_EmployeeDiciplinary
	SET		DisciplinaryActionStatus	=	@ActionStatus,
			UpdatedBy					=	@ProcessedBy,
			UpdatedDate					=	GETDATE()
	WHERE	DisciplinaryId				=	@DisciplinaryId

	--TODO: Check what are the other contents to remove or change status to In-Active instead.
	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UpdatePasswordByUserId]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prC_UpdatePasswordByUserId]
GO

CREATE PROCEDURE [dbo].[prC_UpdatePasswordByUserId]    
(
	@UserId					BigInt,
	@PasswordHash			nVarchar(max),
	@PasswordSalt			nVarchar(max),
	@ChangePasswordOnLogin	Bit
)
AS
BEGIN
	UPDATE	C_User
	SET		PasswordHash			=	@PasswordHash,
			PasswordSalt			=	@PasswordSalt,
			ChangePasswordOnLogin	=	@ChangePasswordOnLogin
	WHERE	UserID					=	@UserId

	SELECT 1
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdatePermissions')
	DROP PROC prC_UpdatePermissions
GO

----------------------------------------------------------------------------
-- Insert a single record into C_Permissions
----------------------------------------------------------------------------
CREATE PROC prC_UpdatePermissions
	@PermissionId		BigInt = NULL,
	@OUId				bigint = NULL,
	@MenuId				bigint = NULL,
	@PermissionTypeId	int = NULL,
	@SecurityRoleID		bigint = NULL,
	@UpdatedBy			nvarchar(100)
AS

UPDATE	C_Permissions
SET		PermissionTypeId	=	@PermissionTypeId,
		UpdatedBy			=	@UpdatedBy
WHERE	MenuId				=	@MenuId
AND		SecurityRoleID		=	@SecurityRoleID
AND		OUId				=	@OUId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateSecurityRoleMenuPermissions')
	DROP PROCEDURE prC_UpdateSecurityRoleMenuPermissions
GO

CREATE PROC prC_UpdateSecurityRoleMenuPermissions
(
	@SecurityRolePermissionId	BigInt,
	@SecurityRoleId				BigInt,
	@MenuId						BigInt,
	@PermissionTypeId			Int,
	@UpdatedBy					nVarchar(50)
)
AS
	UPDATE	C_SecurityRolePermissions
	SET		SecurityRoleId				=	@SecurityRoleId, 
			MenuId						=	@MenuId, 
			PermissionTypeId			=	@PermissionTypeId, 
			UpdatedBy					=	@UpdatedBy,
			UpdatedDate					=	GETDATE()
	WHERE	SecurityRolePermissionId	=	@SecurityRolePermissionId
		
	SELECT  @SecurityRolePermissionId

GO


/****** Object:  StoredProcedure [dbo].[prC_UpdateUserLogin]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UpdateUserLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UpdateUserLogin]
GO
/****** Object:  StoredProcedure [dbo].[prC_UpdateUserLogin]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UpdateUserLogin]    
(
	@UserId	BigInt
)
AS
BEGIN
	
	UPDATE	C_User 
	SET		LastLoginDate = GETDATE()
	WHERE	UserID = @UserId

	SELECT 1

END
GO
/****** Object:  StoredProcedure [dbo].[prC_UpdateUserPassword]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UpdateUserPassword]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UpdateUserPassword]
GO
/****** Object:  StoredProcedure [dbo].[prC_UpdateUserPassword]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UpdateUserPassword]    
(
	@UserId			BigInt,
	@PasswordHash	nVarchar(max),
	@PasswordSalt	nVarchar(max),
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	
	UPDATE	C_User 
	SET		PasswordHash			=	@PasswordHash,
			PasswordSalt			=	@PasswordSalt,
			ChangePasswordOnLogin	=	0,
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GETDATE()
	WHERE	UserID					=	@UserId

	SELECT 1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateUserSecurityRoleById')
	DROP PROCEDURE prC_UpdateUserSecurityRoleById
GO

CREATE PROC prC_UpdateUserSecurityRoleById
(
	@UserSecurityRoleId	BigInt,
	@UserId				BigInt,
	@SecurityRoleId		BigInt,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
	UPDATE	C_UserSecurityRole
	SET		UserId				=	@UserId, 
			SecurityRoleId		=	@SecurityRoleId, 
			ActiveStatus		=	@ActiveStatus, 
			UpdatedBy			=	@UpdatedBy, 
			UpdatedDate			=	GETDATE()
	WHERE	UserSecurityRoleId	=	@UserSecurityRoleId
		
	SELECT 1

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateUserSecurityRoleOUById')
	DROP PROCEDURE prC_UpdateUserSecurityRoleOUById
GO

CREATE PROC prC_UpdateUserSecurityRoleOUById
(
	@UserSecurityRoleOUId	BigInt,
	@UserSecurityRoleId		BigInt,
	@OUId					BigInt,
	@ActiveStatus			Bit,
	@UpdatedBy				nVarchar(50)
)
AS
	UPDATE	C_UserSecurityRoleOU
	SET		UserSecurityRoleId		=	@UserSecurityRoleId, 
			OUId					=	@OUId, 
			ActiveStatus			=	@ActiveStatus, 
			UpdatedBy				=	@UpdatedBy, 
			UpdatedDate				=	GETDATE()
	WHERE	UserSecurityRoleOUId	=	@UserSecurityRoleOUId
		
	SELECT 1

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UpdateUserSecurityRolesByUserSecurityRoleId')
	DROP PROC prC_UpdateUserSecurityRolesByUserSecurityRoleId
GO

----------------------------------------------------------------------------
-- Update a single record in C_UserSecurityRoles
----------------------------------------------------------------------------
CREATE PROC prC_UpdateUserSecurityRolesByUserSecurityRoleId
	@UserSecurityRoleId Bigint,
	@SecurityRoleId		BigInt,
	@StartDate			datetime,
	@EndDate			datetime = NULL,	
	@UpdatedBy			nvarchar(100) = NULL
AS

UPDATE	C_UserSecurityRoles
SET		SecurityRoleId		= @SecurityRoleId,
		StartDate			= @StartDate,
		EndDate				= @EndDate,	
		UpdatedBy			= @UpdatedBy,
		UpdatedDate			= GETDATE()
WHERE 	UserSecurityRoleId	= @UserSecurityRoleId

SELECT 1

GO
/****** Object:  StoredProcedure [dbo].[prC_UserDel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserDel]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserDel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserDel]    
(
	@UserID		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	C_User
	SET		IsActive	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	UserID		=	@UserID

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prC_UserIns]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_UserIns]    
(
	@UserName				nVarchar(50),
	@PasswordHash			nVarchar(2000),
	@PasswordSalt			nVarchar(200),
	@UserRoleID				Numeric(18,0),
	@EmployeeID				Numeric(18,0) = NULL,
	@ChangePasswordOnLogin	Bit,
	@LastLoginDate			DateTime,
	@ResetPassword			Bit,
	@IsActive				Bit,
	@CreatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_User WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(UserName))) = LTrim(RTrim(Upper(@UserName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_User
		(UserName, PasswordHash, PasswordSalt, UserRoleID, EmployeeID, LastLoginDate, ChangePasswordOnLogin,
		 ResetPassword, IsActive, CreatedBy, CreatedDate)
		VALUES
		(
			@UserName, @PasswordHash, @PasswordSalt, @UserRoleID, @EmployeeID, @LastLoginDate, @ChangePasswordOnLogin,
			@ResetPassword, @IsActive, @CreatedBy, GETDATE()
		)

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UserRoleDel')
	DROP PROC prC_UserRoleDel
GO

CREATE PROCEDURE [dbo].[prC_UserRoleDel]    
(
	@UserRoleID	BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	C_SecurityRole
	SET		IsActive			=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GetDate()
	WHERE	SecurityRoleID		=	@UserRoleID

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleIns]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserRoleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserRoleIns]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserRoleIns]    
(
	@RoleCode			nVarchar(50),
	@RoleDescription	nVarchar(500),
	@IsActive			Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_SecurityRole WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(SecurityRoleCode))) = LTrim(RTrim(Upper(@RoleCode)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_SecurityRole
		(SecurityRoleCode, Description, IsActive, CreatedBy, CreatedDate)
		VALUES
		(
			@RoleCode, @RoleDescription, @IsActive, @CreatedBy, GETDATE()
		)

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END


GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleSel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserRoleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserRoleSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleSel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserRoleSel]    
(
	@UserRoleID			Numeric(18,0)
)
AS
BEGIN
	SELECT	C_SecurityRole.SecurityRoleID,
			C_SecurityRole.SecurityRoleCode RoleCode,
			C_SecurityRole.Description RoleDescription,
			C_SecurityRole.IsActive,
			C_SecurityRole.CreatedBy,
			C_SecurityRole.CreatedDate,
			C_SecurityRole.UpdatedBy,
			C_SecurityRole.UpdatedDate
	FROM	C_SecurityRole WITH (NOLOCK) 
	WHERE	(C_SecurityRole.SecurityRoleID  = @UserRoleID OR @UserRoleID = 0)
	ORDER BY C_SecurityRole.SecurityRoleCode
END
GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserRoleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserRoleUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserRoleUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserRoleUpd]    
(
	@UserRoleID			Numeric(18,0),
	@RoleCode			nVarchar(50),
	@RoleDescription	nVarchar(500),
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_SecurityRole WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(SecurityRoleCode))) = LTrim(RTrim(Upper(@RoleCode)))
	AND		SecurityRoleID != @UserRoleID

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	C_SecurityRole
		SET		SecurityRoleCode		=	@RoleCode,
				Description		=	@RoleDescription,
				IsActive		=	@IsActive,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	SecurityRoleID		=	@UserRoleID

		SELECT 1
	END
	Else
	BEGIN
		SELECT -1
	END
END


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_UserSecurityRolesByUserId')
	DROP PROC prC_UserSecurityRolesByUserId
GO

----------------------------------------------------------------------------
-- Select a single record from C_UserSecurityRoles
----------------------------------------------------------------------------
CREATE PROC prC_UserSecurityRolesByUserId
	@UserId bigint
AS

SELECT	UserSecurityRoleId,
	UserId,
	SecurityRoleId,
	StartDate,
	EndDate,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	C_UserSecurityRoles
WHERE 	UserId = @UserId

GO
/****** Object:  StoredProcedure [dbo].[prC_UserSel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserSel]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserSel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserSel]    
(
	@UserName	nVarchar(50)
)
AS
DECLARE @OUId BigInt = 0, @OUName nVarchar(100) = '', @SecurityRoleId BigInt = 0
BEGIN

	SELECT	TOP 1 
			@OUId = IsNull(C_Permissions.OUId,0), 
			@OUName = IsNull(C_OrganizationNode.OUName,'')
	FROM	C_User WITH (NOLOCK)
			INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_User.UserRoleId = C_SecurityRole.SecurityRoleId AND C_SecurityRole.IsActive = 1
			INNER JOIN C_Permissions WITH (NOLOCK) ON C_Permissions.SecurityRoleID = C_SecurityRole.SecurityRoleID
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode .OUId = C_Permissions.OUId
	WHERE	C_User.UserName = 'planner'
	AND		C_User.IsActive = 1

	SELECT	TOP 1 @SecurityRoleId = SecurityRoleId
	FROM	C_UserSecurityRole WITH (NOLOCK) 
			INNER JOIN C_User WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
	WHERE	C_User.UserName = @UserName ANd C_UserSecurityRole.SecurityRoleId = 1

	SELECT	C_User.UserID,
			C_User.UserName,
			C_User.PasswordHash,
			C_User.PasswordSalt,
			IsNull(C_SecurityRole.SecurityRoleID,0) UserRoleID,
			C_SecurityRole.SecurityRoleCode RoleCode,
			C_SecurityRole.Description RoleDescription,
			IsNull(C_User.EmployeeID,0) EmployeeID,
			IsNull(C_Employee.EmployeeNumber,'') EmployeeNumber,
			IsNull(C_Employee.DisplayName,'') EmployeeName,
			IsNull(C_Employee.OUId, @OUId) LoginUserOuId,
			IsNull(C_OrganizationNode.OUName, @OUName) LoginUserOuName,
			C_User.LastLoginDate,
			C_User.ResetPassword,
			C_User.IsActive,
			C_User.CreatedBy,
			C_User.CreatedDate,
			C_User.UpdatedBy,
			C_User.UpdatedDate,
			C_User.ChangePasswordOnLogin,
			@SecurityRoleId  UserSecurityRoleId,
			datepart(TZOFFSET,SYSDATETIMEOFFSET()) DatabaseServerTimeZoneOffSet
	FROM	C_User WITH (NOLOCK) 
			LEFT OUTER JOIN C_SecurityRole WITH (NOLOCK) ON C_User.UserRoleID = C_SecurityRole.SecurityRoleID AND C_SecurityRole.IsActive = 1
			LEFT OUTER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = C_User.EmployeeID
			LEFT OUTER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	WHERE	(C_User.UserName = @UserName OR @UserName = '')
	AND		C_User.IsActive = 1
	ORDER BY C_User.UserName
END
GO
/****** Object:  StoredProcedure [dbo].[prC_UserSelByID]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserSelByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserSelByID]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserSelByID]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_UserSelByID]    
(
	@UserID	 BigInt
)
AS
BEGIN
	SELECT	C_User.UserID,
			C_User.UserName,
			C_User.PasswordHash,
			C_User.PasswordSalt,
			IsNull(C_SecurityRole.SecurityRoleID,0) UserRoleID,
			IsNull(C_SecurityRole.SecurityRoleCode,'') RoleCode,
			IsNull(C_SecurityRole.Description,'') RoleDescription,
			IsNull(C_User.EmployeeID,0) EmployeeID,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			IsNull(C_Employee.EmailAddress,'') LoginUserEmailAddress,
			C_User.LastLoginDate,
			Convert(nVarchar(20),C_User.LastLoginDate,120) LastLoginDateString,
			C_User.ResetPassword,
			C_User.IsActive,
			C_User.CreatedBy,
			C_User.CreatedDate,
			C_User.UpdatedBy,
			C_User.UpdatedDate,
			IsNull(C_UserSecurityRoles.UserSecurityRoleId,0) UserSecurityRoleId
	FROM	C_User WITH (NOLOCK) 
			LEFT OUTER JOIN C_SecurityRole WITH (NOLOCK) ON C_User.UserRoleID = C_SecurityRole.SecurityRoleID
			LEFT OUTER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
			LEFT OUTER JOIN C_UserSecurityRoles WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRoles.UserId
	WHERE	C_User.UserID = @UserID OR @UserID = 0
	--AND		C_User.IsActive = 1
END

GO
/****** Object:  StoredProcedure [dbo].[prC_UserUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_UserUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_UserUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_UserUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_UserUpd]    
(
	@UserID					Numeric(18,0),
	@UserName				nVarchar(50),
	@PasswordHash			nVarchar(2000),
	@PasswordSalt			nVarchar(200),
	@UserRoleID				Numeric(18,0),
	@EmployeeID				Numeric(18,0),
	@ChangePasswordOnLogin	Bit,
	@LastLoginDate			DateTime,
	@ResetPassword			Bit,
	@IsActive				Bit,
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	C_User WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(UserName))) = LTrim(RTrim(Upper(@UserName)))
	AND		UserID != @UserID

	If (@ValidateDuplicate = 0)
	BEGIN
		If (@PasswordHash != '*')
			UPDATE	C_User
			SET		UserName				=	@UserName,
					PasswordHash			=	@PasswordHash,
					PasswordSalt			=	@PasswordSalt,
					UserRoleID				=	@UserRoleID,
					EmployeeID				=	@EmployeeID,
					ChangePasswordOnLogin	=	@ChangePasswordOnLogin,
					LastLoginDate			=	@LastLoginDate,
					ResetPassword			=	@ResetPassword,
					IsActive				=	@IsActive,
					UpdatedBy				=	@UpdatedBy,
					UpdatedDate				=	GETDATE()
			WHERE	UserID					=	@UserID
		Else
			UPDATE	C_User
			SET		UserName				=	@UserName,
					UserRoleID				=	@UserRoleID,
					EmployeeID				=	@EmployeeID,
					ChangePasswordOnLogin	=	@ChangePasswordOnLogin,
					LastLoginDate			=	@LastLoginDate,
					ResetPassword			=	@ResetPassword,
					IsActive				=	@IsActive,
					UpdatedBy				=	@UpdatedBy,
					UpdatedDate				=	GETDATE()
			WHERE	UserID					=	@UserID

		SELECT 1
	END
	Else
	BEGIN
		SELECT -1
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prC_ValidateLogin]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_ValidateLogin]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_ValidateLogin]
GO
/****** Object:  StoredProcedure [dbo].[prC_ValidateLogin]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_ValidateLogin]    
(
	@UserName	nVarchar(50),
	@Password	nVarchar(max)
)
AS
BEGIN
	SELECT	C_User.UserID,
			C_User.UserName,
			IsNull(C_UserRole.UserRoleID,0) UserRoleID,
			C_UserRole.RoleCode,
			C_UserRole.RoleDescription,
			C_User.EmployeeID,
			C_User.LastLoginDate,
			C_User.ResetPassword,
			C_User.IsActive,
			C_User.CreatedBy,
			C_User.CreatedDate,
			C_User.UpdatedBy,
			C_User.UpdatedDate
	FROM	C_User LEFT OUTER JOIN C_UserRole ON C_User.UserRoleID = C_UserRole.UserRoleID 
			-- TODO: // Inner Join With T_Employee.
	WHERE	C_User.UserName = @UserName And PasswordHash = @Password
	AND		C_User.IsActive = 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prDash_GetBoxMovementSummary]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prDash_GetBoxMovementSummary]
GO

Create PROCEDURE [dbo].[prDash_GetBoxMovementSummary]
(
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	SELECT	I_BoxMovementSummary.Date,
			Sum(CMPHTarget) CMPHTarget, 
			Sum(CMPHActual) CMPHActual, 
			Sum(PMPHTarget) PMPHTarget, 
			Sum(PMPHActual) PMPHActual
	FROM	I_BoxMovementSummary WITH (NOLOCK)
	WHERE	Convert(Date,Date) >= Convert(Date,@StartDate)
	AND		Convert(Date,Date) <= Convert(Date,@EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	GROUP BY I_BoxMovementSummary.Date
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prDash_GetGangAllocationByDateForExport') AND type in (N'P', N'PC'))
	DROP PROCEDURE prDash_GetGangAllocationByDateForExport
GO

Create PROCEDURE prDash_GetGangAllocationByDateForExport
(
	@OUId				BigInt,
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	
	--SELECT	J_PlanningRequirements.RequirementDate,
	--		D_ShiftBand.ShiftBandCode ShiftBand,
	--		Round(J_PlanningRequirements.RequirementCount/1.5,0) RequirementCount, 'Planned' ResultType
	--FROM	J_PlanningRequirements WITH (NOLOCK) 
	--		INNER JOIN D_ShiftBand WITH (NOLOCK) ON J_PlanningRequirements.ShiftBandId = D_ShiftBand.ShiftBandId
	--Where	Convert(Date,RequirementDate) >= Convert(Date,@StartDate)
	--And		Convert(Date,RequirementDate) <= Convert(Date,@EndDate)
	--And		SkillId = 1 
	--And		OUId = @OUId
	--AND		J_PlanningRequirements.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	SELECT	J_PlanningEquipmentRequirements.RequirementDate,
			D_ShiftBand.ShiftBandCode ShiftBand,
			RequirementCount, 'Planned' ResultType
	FROM	J_PlanningEquipmentRequirements WITH (NOLOCK) 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON J_PlanningEquipmentRequirements.ShiftBandId = D_ShiftBand.ShiftBandId
	Where	Convert(Date,RequirementDate) >= Convert(Date,@StartDate)
	And		Convert(Date,RequirementDate) <= Convert(Date,@EndDate)
	And		EquipmentTypeId = 0 
	And		OUId = @OUId
	AND		J_PlanningEquipmentRequirements.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	UNION ALL
	SELECT	I_BoxMovementSummary.Date RequirementDate, 
			D_ShiftBand.ShiftBandCode ShiftBand,
			ActualGang RequirementCount, 'Actual' ResultType
	FROM	I_BoxMovementSummary WITH (NOLOCK)
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = I_BoxMovementSummary.ShiftBandId
	WHERE	Convert(Date,Date) >= Convert(Date,@StartDate)
	AND		Convert(Date,Date) <= Convert(Date,@EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prDash_GetGangAllocationSummary') AND type in (N'P', N'PC'))
	DROP PROCEDURE prDash_GetGangAllocationSummary
GO

Create PROCEDURE prDash_GetGangAllocationSummary
(
	@OUId				BigInt = 24,
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	
	--SELECT	J_PlanningRequirements.RequirementDate,
	--		Sum(Round(J_PlanningRequirements.RequirementCount/1.5,0)) RequirementCount, 'Planned' ResultType
	--FROM	J_PlanningRequirements
	--Where	Convert(Date,RequirementDate) >= Convert(Date,@StartDate)
	--And		Convert(Date,RequirementDate) <= Convert(Date,@EndDate)
	--And		SkillId = 1 
	--And		OUId = @OUId
	--AND		J_PlanningRequirements.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	--Group By J_PlanningRequirements.RequirementDate
	SELECT	J_PlanningEquipmentRequirements.RequirementDate,
			Sum(J_PlanningEquipmentRequirements.RequirementCount) RequirementCount, 'Planned' ResultType
	FROM	J_PlanningEquipmentRequirements
	Where	Convert(Date,RequirementDate) >= Convert(Date,@StartDate)
	And		Convert(Date,RequirementDate) <= Convert(Date,@EndDate)
	And		EquipmentTypeId = 0 
	And		OUId = @OUId
	AND		J_PlanningEquipmentRequirements.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	Group By J_PlanningEquipmentRequirements.RequirementDate
	UNION ALL
	SELECT	I_BoxMovementSummary.Date RequirementDate, 
			Sum(ActualGang) RequirementCount, 'Actual' ResultType
	FROM	I_BoxMovementSummary WITH (NOLOCK)
	WHERE	Convert(Date,Date) >= Convert(Date,@StartDate)
	AND		Convert(Date,Date) <= Convert(Date,@EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	GROUP BY I_BoxMovementSummary.Date
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prDash_GetManHourPerMoveForExport') AND type in (N'P', N'PC'))
	DROP PROCEDURE prDash_GetManHourPerMoveForExport
GO

Create PROCEDURE prDash_GetManHourPerMoveForExport
(
	@OUId				BigInt,
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	
	SELECT	Convert(Date,ActualStartTime) RequirementDate,
			Sum(DATEDIFF(hh, ActualStartTime, ActualEndTime)) as RequirementCount, 
			'TotalManHour' ResultType, D_ShiftBand.ShiftBandCode ShiftBand
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN D_RoleSkill WITH (NOLOCK) ON S_Shifts.RoleId = D_RoleSkill.RoleId
			AND D_RoleSkill.SkillId IN (1,2,3,4,5,6,7,8,9)
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	Where	Convert(Date, ActualStartTime) >= Convert(Date, @StartDate)
	And		Convert(Date, ActualStartTime) <= Convert(Date, @EndDate)
	And		OUId = @OUId 
	And		S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	Group BY Convert(Date,ActualStartTime), D_ShiftBand.ShiftBandCode
	UNION ALL
	SELECT	I_BoxMovementSummary.Date RequirementDate, 
			Sum(MovesActual) RequirementCount, 'TotalMoves' ResultType, D_ShiftBand.ShiftBandCode ShiftBand
	FROM	I_BoxMovementSummary WITH (NOLOCK)  
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON I_BoxMovementSummary.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	Convert(Date,Date) >= Convert(Date, @StartDate)
	AND		Convert(Date,Date) <= Convert(Date, @EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	GROUP BY I_BoxMovementSummary.Date, D_ShiftBand.ShiftBandCode
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prDash_GetManHourPerMoveSummary') AND type in (N'P', N'PC'))
	DROP PROCEDURE prDash_GetManHourPerMoveSummary
GO

Create PROCEDURE prDash_GetManHourPerMoveSummary
(
	@OUId				BigInt,
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	
	SELECT	Convert(Date,ActualStartTime) RequirementDate,
			Sum(DATEDIFF(hh, ActualStartTime, ActualEndTime)) as RequirementCount, 
			'TotalManHour' ResultType
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId 
			INNER JOIN D_RoleOU WITH (NOLOCK) ON D_Roles.RoleId = D_RoleOU.RoleId And D_RoleOU.OUId = @OUId
			--INNER JOIN D_RoleSkill WITH (NOLOCK) ON S_Shifts.RoleId = D_RoleSkill.RoleId
			--AND D_RoleSkill.SkillId IN (1,2,3,4,5,6,7,8,9)
	Where	Convert(Date, ActualStartTime) >= Convert(Date, @StartDate)
	And		Convert(Date, ActualStartTime) <= Convert(Date, @EndDate)
	And		S_Shifts.InTime IS NOT NULL 
	And		S_Shifts.OutTime IS NOT NULL
	And		S_Shifts.Reconciled = 1 
	And		S_Shifts.OUId = @OUId 
	And		S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	Group BY Convert(Date,ActualStartTime)
	UNION ALL
	SELECT	I_BoxMovementSummary.Date RequirementDate, 
			Sum(MovesActual) RequirementCount, 'TotalMoves' ResultType
	FROM	I_BoxMovementSummary WITH (NOLOCK)
	WHERE	Convert(Date,Date) >= Convert(Date, @StartDate)
	AND		Convert(Date,Date) <= Convert(Date, @EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
	GROUP BY I_BoxMovementSummary.Date
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prDash_GetProductivitySummary]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prDash_GetProductivitySummary]
GO

Create PROCEDURE [dbo].[prDash_GetProductivitySummary]
(
	@ShiftBands			nVarchar(max),
	@StartDate			Date,
	@EndDate			Date
)
AS
BEGIN
	SELECT	I_BoxMovementSummary.Date,
			D_ShiftBand.ShiftBandCode ShiftBand,
			CMPHTarget, 
			CMPHActual, 
			PMPHTarget, 
			PMPHActual
	FROM	I_BoxMovementSummary WITH (NOLOCK) 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON I_BoxMovementSummary.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	Convert(Date,Date) >= Convert(Date,@StartDate)
	AND		Convert(Date,Date) <= Convert(Date,@EndDate)
	AND		I_BoxMovementSummary.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prDash_GetRequiredDeployedCountByDateShiftBand')
	DROP PROC prDash_GetRequiredDeployedCountByDateShiftBand
GO

CREATE PROCEDURE [dbo].[prDash_GetRequiredDeployedCountByDateShiftBand]    
(
	@OUId			BigInt,
	@ShiftBandId	BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN

	-- Retrieve Required Information From Planning Requirements Table
	SELECT	PlanningRequirementId, 
			OUId, 
			J_PlanningRequirements.SkillId, 
			D_Skill.Skill SkillName,
			ShiftBandId, 
			RequirementDate, 
			ShiftStartTime,
			ShiftEndTime,
			RequirementCount,
			DeployedCount,
			J_PlanningRequirements.CreatedBy,
			J_PlanningRequirements.CreatedDate
	FROM	J_PlanningRequirements WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON J_PlanningRequirements.SkillId = D_SKill.SkillId
	WHERE	OUId							=	@OUId
	AND		ShiftBandId						=	@ShiftBandId
	AND		Convert(date,ShiftStartTime)	>=	Convert(Date,@StartDate)
	AND		Convert(date,ShiftEndTime)	<=	Convert(Date,@EndDate)


	-- Deployed Resources Count By OUId, ShiftBand, Shift Start Time And Shift End Time
	SELECT  D_Skill.Skill SkillName,
			J_Activity.SkillId,
			Count(Distinct J_Activity.ShiftId) DeployedResourceCount
	FROM	J_Activity 
			INNER JOIN D_Skill ON J_Activity.SkillId = D_Skill.SkillId
			INNER JOIN S_Shifts ON J_Activity.ShiftId = S_Shifts.ShiftId
	WHERE	J_Activity.ShiftId IS NOT NULL
	AND		J_Activity.OUId				=	@OUId
	AND		J_Activity.ShiftBandId		=	@ShiftBandId
	AND		Convert(DATETIME,StartTime)	>=	Convert(DATETIME,@StartDate)
	AND		Convert(DATETIME,EndTime)	<=	Convert(DATETIME,@EndDate)
	GROUP BY D_Skill.Skill, J_Activity.SkillId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prDash_GetResourceAvilableByDateShiftBand')
	DROP PROC prDash_GetResourceAvilableByDateShiftBand
GO

CREATE PROCEDURE [dbo].[prDash_GetResourceAvilableByDateShiftBand]    
(
	@StartDate		Date,
	@EndDate		Date,
	@OUId			BigInt,
	@ShiftBandId	BigInt
)
AS
BEGIN
	SELECT		TOP (100) PERCENT COUNT(*) AS Available, 
				D_EmploymentBasis.EmploymentBasisCode, 
				CONVERT(date, S_Shifts.ShiftStartTime) AS ShiftDate, 
				D_ShiftBand.ShiftBandName, 
				D_Roles.RoleName,
				Skill,
				D_Skill.ColorCode SkillColor
	FROM		C_Employee INNER JOIN
                         D_EmploymentBasis ON dbo.D_EmploymentBasis.EmploymentBasisId = dbo.C_Employee.EmploymentBasisId INNER JOIN
                         S_Shifts ON dbo.S_Shifts.EmployeeId = dbo.C_Employee.EmployeeId INNER JOIN
                         D_ShiftBand ON dbo.D_ShiftBand.ShiftBandId = dbo.S_Shifts.ShiftBandId INNER JOIN
                         C_EmployeeRoles ON dbo.C_EmployeeRoles.EmployeeId = dbo.C_Employee.EmployeeId AND dbo.C_EmployeeRoles.IsPrimaryRole = 1 INNER JOIN
                         D_Roles ON dbo.D_Roles.RoleId = dbo.C_EmployeeRoles.RoleId
						-- inner join D_RoleSkill on D_RoleSkill.RoleId=  D_Roles.PrimarySkillId
						 --inner join D_RoleSkill on D_RoleSkill.RoleId=  D_Roles.RoleId
						 inner join D_Skill on D_Skill.SkillId = D_Roles.PrimarySkillId
	WHERE        (CONVERT(Date, S_Shifts.ShiftStartTime) >= @StartDate) AND (CONVERT(Date, S_Shifts.ShiftStartTime) <= @EndDate)
	--and S_Shifts.ShiftBandId in (2,3)
	AND		(S_Shifts.ShiftBandId = @ShiftBandId OR @ShiftBandId = 0)
	AND		S_Shifts.OUId  = @OUId
	GROUP BY dbo.D_EmploymentBasis.EmploymentBasisCode, CONVERT(date, dbo.S_Shifts.ShiftStartTime), dbo.D_ShiftBand.ShiftBandName, dbo.D_Roles.RoleName,Skill, D_Skill.ColorCode

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_AddRamadanPeriod')
	DROP PROC prD_AddRamadanPeriod
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_AddRamadanPeriod
----------------------------------------------------------------------------
CREATE PROC [dbo].[prD_AddRamadanPeriod]
	@RamadanYear			Int,
	@PeriodStart			DateTime,
	@PeriodEnd				DateTime,
	@Description			nVarchar(50),
	@DailyOverTimeHours		Decimal(18,2),
	@WeeklyOverTimeHours	Decimal(18,2),
	@CreatedBy				nVarchar(50),
	@DayStartTime           datetime,       
	@DayEndTime             datetime,
	@NightStartTime         datetime,
	@NightEndTime           datetime,
	@MaxOvrtimehrs     Decimal(18,2)
	
	

AS

DECLARE @RecCount Int = 0
SELECT  @RecCount = Count(*) 
FROM	D_RamadanPeriod 
WHERE	Convert(Date,PeriodEnd)			> Convert(Date,@PeriodEnd)
AND		Convert(Date,PeriodStart)		< Convert(Date,@PeriodStart)


If (@RecCount = 0) 
BEGIN
	INSERT D_RamadanPeriod
	(RamadanYear, PeriodStart, PeriodEnd, Description, DailyOverTimeHours, WeeklyOverTimeHours, CreatedBy, CreatedDate,DayStartTime,DayEndTime,NightStartTime,NightEndTime,MaxDailyOvertimeHours)
	VALUES(@RamadanYear, @PeriodStart, @PeriodEnd, @Description, @DailyOverTimeHours, @WeeklyOverTimeHours, @CreatedBy, GETDATE(),@DayStartTime,@DayEndTime,@NightStartTime,@NightEndTime,@MaxOvrtimehrs)

	SELECT  CAST(@@Identity AS INTEGER)
END
Else
	SELECT  -1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_AddRamadanPeriodEmployeeList')
	DROP PROC prD_AddRamadanPeriodEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_AddRamadanPeriodEmployeeList
----------------------------------------------------------------------------
CREATE PROC prD_AddRamadanPeriodEmployeeList
	@RamadanPeriodId		BigInt,
	@EmployeeId				BigInt,
	@TypeId					Int,
	@TypeDescription		nVarchar(500),
	@CreatedBy				nVarchar(50)
	
AS

INSERT D_RamadanPeriodEmployeeList
(RamadanPeriodId, EmployeeId, TypeId, TypeDescription, CreatedBy, CreatedDate)
VALUES(@RamadanPeriodId, @EmployeeId, @TypeId, @TypeDescription, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_DeleteRamadanPeriod')
	DROP PROC prD_DeleteRamadanPeriod
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_DeleteRamadanPeriod
----------------------------------------------------------------------------
CREATE PROC prD_DeleteRamadanPeriod
	@RamadanPeriodId		BigInt
AS

DELETE FROM  D_RamadanPeriod
WHERE	RamadanPeriodId		=	@RamadanPeriodId

SELECT  1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_DeleteRamadanPeriodEmployeeList')
	DROP PROC prD_DeleteRamadanPeriodEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_DeleteRamadanPeriodEmployeeList
----------------------------------------------------------------------------
CREATE PROC prD_DeleteRamadanPeriodEmployeeList
	@TranId		BigInt
AS

DELETE FROM  D_RamadanPeriodEmployeeList
WHERE	TranId		=	@TranId

SELECT  1

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_D_ShiftBandDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_D_ShiftBandDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_D_ShiftBandDel]    Script Date: 6/27/2018 7:27:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_D_ShiftBandDel]    
(
	@ShiftBandId		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	D_ShiftBand
	SET		ActiveStatus	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	ShiftBandId		= @ShiftBandId

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisByOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisByOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisByOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisByOUSel]    Script Date: 20/06/2018 10:49:31 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_EmploymentBasisByOUSel]    
(	
	@OUId	BigInt
)
AS
BEGIN
	
	SELECT	DISTINCT 
			empbasis.EmploymentBasisId,
			empBasis.EmploymentBasisCode EmploymentBasisCode,
			empBasis.EmploymentBasisDesc EmploymentBasisDescription--,
			--orgNode.OUId, orgNode.OUName, orgNode.ParentOUId
	FROM	D_EmploymentBasis empBasis 
			INNER JOIN D_EmploymentBasisOU empBasisOU ON empBasis.EmploymentBasisId = empBasisOU.EmploymentBasisId
			INNER JOIN C_OrganizationNode orgNode ON orgNode.OUId = empBasisOU.OUId
	WHERE	(empBasisOU.OUId = @OUId OR @OUId = 0)
	AND		empBasis.ActiveStatus = 1
	ORDER BY empBasis.EmploymentBasisCode
END

GO





/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisDel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisDel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_EmploymentBasisDel]    
(
	@EmploymentBasisId		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	D_EmploymentBasis
	SET		ActiveStatus	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	EmploymentBasisId		= @EmploymentBasisId

	SELECT 1
END

GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisIns]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prD_EmploymentBasisIns]    
(	
	@Code			nVarchar(500),
	@Description	nVarchar(1000),
	@Seq		Int,
	@ActiveStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_EmploymentBasis WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EmploymentBasisCode))) = LTrim(RTrim(Upper(@Code)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_EmploymentBasis
		(EmploymentBasisCode, EmploymentBasisDesc, Seq, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@Code, @Description, @Seq, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END

GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUDel]    Script Date: 20/06/2018 10:49:04 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_EmploymentBasisOUDel]    
(	
	@EmploymentBasisID	BigInt,
	@OUID				BigInt
)
AS
BEGIN
	DELETE FROM D_EmploymentBasisOU
	WHERE	OUId = @OUID
	AND		EmploymentBasisId = @EmploymentBasisID
	SELECT 1
	 
END

GO





/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUIns]    Script Date: 20/06/2018 10:47:52 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_EmploymentBasisOUIns]    
(	
	@EmploymentBasisID	BigInt,
	@OUID				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @validateOUCount Numeric(18,0)
BEGIN
	SET @validateOUCount = 0;

	SELECT @validateOUCount = COUNT(*) FROM D_EmploymentBasisOU WITH (NOLOCK)
	WHERE	EmploymentBasisId = @EmploymentBasisID
	AND		OUId = @OUID

	If (@validateOUCount = 0)
	BEGIN
		INSERT INTO D_EmploymentBasisOU
		(EmploymentBasisId, OUId, CreatedBy, CreatedDate)
		VALUES(@EmploymentBasisID, @OUID, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
		SELECT 1

END

GO





/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisOUSel]    Script Date: 20/06/2018 10:48:27 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_EmploymentBasisOUSel]    
(	
	@EmploymentBasisID	BigInt
)
AS
BEGIN
	
	SELECT	empBasisOU.EmploymentBasisOUId,
			empBasisOU.EmploymentBasisId,
			empBasisOU.OUId,
			empBasis.EmploymentBasisCode EmploymentBasisCode,
			empBasis.EmploymentBasisDesc EmploymentBasisDescription,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_EmploymentBasisOU empBasisOU WITH (NOLOCK)
			INNER JOIN C_OrganizationNode orgNode WITH (NOLOCK) ON empBasisOU.OUId = orgNode.OUId		
			INNER JOIN D_EmploymentBasis empBasis WITH (NOLOCK) ON empBasis.EmploymentBasisId = empBasisOU.EmploymentBasisId
	WHERE	empBasisOU.EmploymentBasisId = @EmploymentBasisID
	 
END

GO





/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisSel]    Script Date: 20/6/2018 7:35:56 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_EmploymentBasisSel]    
(	
	@EmploymentBasisID	BigInt,
	@OUID				BigInt
	
)
AS
BEGIN
	SELECT	D_EmploymentBasis.EmploymentBasisId,
			D_EmploymentBasis.EmploymentBasisCode,
			D_EmploymentBasis.EmploymentBasisDesc,
			D_EmploymentBasis.Seq,
			D_EmploymentBasis.ActiveStatus,
			D_EmploymentBasis.CreatedBy,
			D_EmploymentBasis.CreatedDate,
			D_EmploymentBasis.UpdatedBy,
			D_EmploymentBasis.Updateddate
	FROM	D_EmploymentBasis  WITH (NOLOCK)
			--LEFT OUTER JOIN D_EmploymentBasisOU WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = D_EmploymentBasisOU.EmploymentBasisId
			--LEFT OUTER JOIN C_OrganizationNode WITH (NOLOCK) ON D_EmploymentBasisOU.OUId = C_OrganizationNode.OUId
			INNER JOIN D_EmploymentBasisOU WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = D_EmploymentBasisOU.EmploymentBasisId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON D_EmploymentBasisOU.OUId = C_OrganizationNode.OUId
	WHERE	(D_EmploymentBasis.EmploymentBasisId = @employmentBasisID OR @employmentBasisID = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
	ORDER BY D_EmploymentBasis.EmploymentBasisCode
END

GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_EmploymentBasisUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_EmploymentBasisUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_EmploymentBasisUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_EmploymentBasisUpd]    
(	
	@ID				BigInt,
	@Code			nVarchar(500),
	@Description	nVarchar(1000),
	@Seq		Int,
	@ActiveStatus	Bit,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_EmploymentBasis WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EmploymentBasisCode))) = LTrim(RTrim(Upper(@Code)))
	AND		EmploymentBasisId != @ID

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_EmploymentBasis
		SET		EmploymentBasisCode		=	@Code, 
				EmploymentBasisDesc	=	@Description, 
				Seq					=	@Seq, 
				ActiveStatus		=	@ActiveStatus, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	EmploymentBasisId	=	@ID

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodeIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodeIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodeIdByName]    Script Date: 7/31/2018 10:29:53 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prD_ExceptionCodeIdByName]    
(
	@ExcpetionCodeName nvarchar(500) 
)
AS
DECLARE @ExceptionCodeId bigint = 0
BEGIN

	SELECT	@ExceptionCodeId =  ExceptionCodeId
	FROM	D_ExceptionCodes WITH (NOLOCK)
	WHERE	ExcpetionCodeName =@ExcpetionCodeName
 

 SELECT @ExceptionCodeId;
	 
END
GO
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesByLeaveidSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesByLeaveidSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesByLeaveidSel]    Script Date: 7/26/2018 6:41:53 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ExceptionCodesByLeaveidSel]  
(
	@ExceptionTypeId			BigInt 
)
AS
BEGIN
	SELECT	D_ExceptionCodes.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName  ,
			D_ExceptionCodes.ExceptionCodeDesc ,
			D_ExceptionCodes.ExceptionTypeId,
			D_ExceptionCodes.IsPaid  ,
			D_ExceptionCodes.ColorCode ColorCode,
			D_ExceptionCodes.ESS  ,
			D_ExceptionCodes.ShiftLength  ,
			D_ExceptionCodes.ActiveStatus, 
			D_ExceptionCodes.CreatedBy, 
			D_ExceptionCodes.CreatedDate,
			D_ExceptionCodes.UpdatedBy,
			D_ExceptionCodes.UpdatedDate
	FROM	D_ExceptionCodes WITH (NOLOCK) 
	WHERE	D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId 
	ORDER BY D_ExceptionCodes.ExcpetionCodeName
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesDel]    Script Date: 7/10/2018 12:06:06 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_ExceptionCodesDel]
(
	@ExceptionCodeId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	D_ExceptionCodes
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	ExceptionCodeId	=	@ExceptionCodeId

	SELECT 1
END 
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesIns]    Script Date: 7/10/2018 12:06:43 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ExceptionCodesIns]    
(
	@ExcpetionCodeName	nVarchar(50),
	@ExceptionCodeDesc	nVarchar(255),
	@ExceptionTypeId	int,
	@ColorCode			nvarchar(50),	 
	@IsPaid				Bit,
	@Ess				Bit,
	@ShiftLength		int,
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ExceptionCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ExcpetionCodeName))) = LTrim(RTrim(Upper(@ExcpetionCodeName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_ExceptionCodes
		(ExcpetionCodeName, ExceptionCodeDesc, ExceptionTypeId, ColorCode, 
		 IsPaid, ESS, ShiftLength, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@ExcpetionCodeName, @ExceptionCodeDesc, @ExceptionTypeId, @ColorCode, 
			   @IsPaid, @Ess, @ShiftLength, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesOUDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesOUDel]    Script Date: 7/10/2018 12:12:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_ExceptionCodesOUDel]    
(
	@ExceptionCodeId			BigInt,
	@OUId				BigInt
)
AS
DECLARE @ExceptionCodeOUId BigInt = 0;
BEGIN

	SELECT	@ExceptionCodeOUId = IsNull(ExceptionCodeOUId,0)
	FROM	D_ExceptionCodesOU WITH (NOLOCK)
	WHERE	ExceptionCodeId =	@ExceptionCodeId
	AND		OUId	=	@OUId

	If (@ExceptionCodeOUId > 0)
	BEGIN
		DELETE FROM D_ExceptionCodesOU
		WHERE	ExceptionCodeOUId	= @ExceptionCodeOUId

		SELECT 1;
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesOUIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesOUIns]    Script Date: 7/10/2018 12:11:16 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prD_ExceptionCodesOUIns]    
(
	@ExceptionCodeId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ExceptionCodeOUId BigInt = 0;
BEGIN

	SELECT	@ExceptionCodeOUId = IsNull(ExceptionCodeOUId,0)
	FROM	D_ExceptionCodesOU WITH (NOLOCK)
	WHERE	ExceptionCodeId =	@ExceptionCodeId
	AND		OUId	=	@OUId

	If (@ExceptionCodeOUId = 0)
	BEGIN
		INSERT INTO D_ExceptionCodesOU
		(ExceptionCodeId, OUId, CreatedBy, CreatedDate)
		VALUES(@ExceptionCodeId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesOUSel]    Script Date: 7/10/2018 12:10:10 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prD_ExceptionCodesOUSel]    
(
	@ExceptionCodeId	BigInt
)
AS
BEGIN
	SELECT	D_ExceptionCodesOU.ExceptionCodeOUId,
			D_ExceptionCodesOU.ExceptionCodeId,
			D_ExceptionCodesOU.OUId,
			D_ExceptionCodesOU.CreatedBy, 
			D_ExceptionCodesOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_ExceptionCodesOU WITH (NOLOCK) 
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodesOU.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_ExceptionCodesOU.OUId  
			WHERE	D_ExceptionCodesOU.ExceptionCodeId		=	@ExceptionCodeId 
END
GO
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesSel]    Script Date: 7/10/2018 12:09:17 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_ExceptionCodesSel]  
(
	@ExceptionCodeId			BigInt,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	DISTINCT D_ExceptionCodes.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName  ,
			D_ExceptionCodes.ExceptionCodeDesc ,
			D_ExceptionCodes.ExceptionTypeId,
			D_ExceptionType.ExceptionTypeName,
			D_ExceptionCodes.IsPaid  ,
			D_ExceptionCodes.ColorCode ColorCode,
			D_ExceptionCodes.ESS  ,
			Convert(datetime,DATEADD(MINUTE,D_ExceptionCodes.ShiftLength,Convert(DateTime,'2019-01-01 00:00:00')),120) ShiftLength,
			0 ShiftLengthValue,
			D_ExceptionCodes.ActiveStatus, 
			D_ExceptionCodes.CreatedBy, 
			D_ExceptionCodes.CreatedDate,
			D_ExceptionCodes.UpdatedBy,
			D_ExceptionCodes.UpdatedDate
	FROM	D_ExceptionCodes WITH (NOLOCK) 
			INNER JOIN D_ExceptionCodesOU WITH (NOLOCK)  ON D_ExceptionCodes.ExceptionCodeId = D_ExceptionCodesOU.ExceptionCodeId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_ExceptionCodesOU.OUId = C_OrganizationNode.OUId
			INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
	WHERE	(D_ExceptionCodes.ExceptionCodeId = @ExceptionCodeId OR @ExceptionCodeId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
	ORDER BY D_ExceptionCodes.ExcpetionCodeName
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionCodesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionCodesUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionCodesUpd]    Script Date: 7/10/2018 12:08:12 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prD_ExceptionCodesUpd]    
(
	@ExceptionCodeId	BigInt,
	@ExcpetionCodeName	nVarchar(50),
	@ExceptionCodeDesc	nVarchar(255),
	@ExceptionTypeId	int,	 
	@ColorCode			nVarchar(20),
	@IsPaid				Bit,
	@Ess				Bit,
	@ShiftLength		int,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ExceptionCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ExcpetionCodeName))) = LTrim(RTrim(Upper(@ExcpetionCodeName)))
	AND		ExceptionCodeId != @ExceptionCodeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_ExceptionCodes
				SET	ExcpetionCodeName		=	@ExcpetionCodeName, 
				ExceptionCodeDesc			=	@ExceptionCodeDesc, 
				ExceptionTypeId				=	@ExceptionTypeId, 				 
				ColorCode					=	@ColorCode, 
				IsPaid						=	@IsPaid,
				ESS							=	@Ess,
				ShiftLength					=	@ShiftLength,
				ActiveStatus				=	@ActiveStatus, 
				UpdatedBy					=	@UpdatedBy,
				UpdatedDate					=	GETDATE()
		WHERE	ExceptionCodeId				=	@ExceptionCodeId
					
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ExceptionTypeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ExceptionTypeSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ExceptionTypeSel]    Script Date: 7/10/2018 12:12:47 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
create PROCEDURE [dbo].[prD_ExceptionTypeSel]    
(
	@ExceptionTypeId	 Int
)
AS
BEGIN	 
	SELECT	ExceptionTypeId,
			ExceptionTypeName,
			ExceptionTypeDesc,			 
			 CreatedBy,
			 CreatedDate,
			 UpdatedBy,			 
			 UpdatedDate
	FROM	D_ExceptionType 			 
	WHERE	(ExceptionTypeId = @ExceptionTypeId OR @ExceptionTypeId = 0)
	Order By D_ExceptionType.ExceptionTypeName
END
GO
/****** Object:  StoredProcedure [dbo].[prD_GetAllEmailTemplates]  ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetAllEmailTemplates]') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_GetAllEmailTemplates
GO

CREATE PROCEDURE [dbo].[prD_GetAllEmailTemplates]    
(
	@EmailTemplateId	BigInt,
	@LanguageId			BigInt
)
AS
BEGIN
	SELECT	TemplateId,
			LanguageId,
			FunctionId,
			MailSubject,
			MailBody,
			MailCC,
			MailFrom,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_EmailTemplate 
	WHERE	(TemplateId = @EmailTemplateId OR @EmailTemplateId = 0)
	AND		(LanguageId  = @LanguageId OR @LanguageId = 0)
	AND		ActiveStatus = 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetAllShiftBands]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prD_GetAllShiftBands]
GO

Create PROCEDURE [dbo].[prD_GetAllShiftBands]
AS
BEGIN
	SELECT	ShiftBandId, ShiftBandName, ShiftBandCode
	FROM	D_ShiftBand
	ORDER BY ShiftBandCode

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_GetbyIdShiftAudit')
	DROP PROC prD_GetbyIdShiftAudit
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_GetbyIdShiftAudit
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prD_GetbyIdShiftAudit] 
(
	            @EmployeeId	      bigInt,
				@ShiftStartTime   Datetime,
				@ShiftEndTime     Datetime	
)
AS

SELECT    
                A_Shifts.ShiftId,
	            A_Shifts.Action,
				A_Shifts.ShiftBandName,
				A_Shifts.ShiftStartTime ,
				A_Shifts.ShiftEndTime ,
				A_Shifts.CreatedBy,
				A_Shifts.CreatedDate,
				A_Shifts.ClockIn,
				A_Shifts.ClockOut,
				A_Shifts.ReconStatus,
	            A_Shifts.InStatus,
				A_Shifts.OutStatus,
				A_Shifts.LeaveType,
				A_Shifts.LeaveApprovedBy,
				A_Shifts.LeaveAppliedDate,
				A_Shifts.LeaveApprovedDate,
				A_Shifts.ShiftCost,
				A_Shifts.Remarks,
				A_Shifts.ActionDate
FROM            A_Shifts            WITH (NOLOCK) 
                --INNER JOIN S_Shifts WITH (NOLOCK)  ON S_Shifts.ShiftId = A_Shifts.ShiftId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = A_Shifts.EmployeeId

WHERE           (C_Employee.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0) 
                AND		CONVERT(DATE,A_Shifts.ShiftStartTime)>=CONVERT(DATE,@ShiftStartTime)
				AND		CONVERT(DATE,A_Shifts.ShiftStartTime)<=CONVERT(DATE,@ShiftEndTime)
                
ORDER BY        A_Shifts.ShiftBandName

GO

                


			IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetPublicHolidaysByDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_GetPublicHolidaysByDate]
GO


create PROCEDURE [dbo].[prD_GetPublicHolidaysByDate]    
(
	@HolidayDate datetime
)
AS
BEGIN
	SELECT	PublicHolidayId,
			HolidayName,
			HolidayDate  ,
			IsPaid,
			HolidayNote, 
			CreatedBy, 
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_PublicHolidays
	WHERE	HolidayDate =  CONVERT(date, @HolidayDate)
	ORDER BY HolidayDate
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_GetRamadanPeriodById')
	DROP PROC prD_GetRamadanPeriodById
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_GetRamadanPeriodById
----------------------------------------------------------------------------
CREATE PROC prD_GetRamadanPeriodById
	@RamadanPeriodId		BigInt
AS

	SELECT	RamadanPeriodId, 
			RamadanYear RamadanPeriodYear,
			PeriodStart,
			PeriodEnd,
			Description,
			DailyOverTimeHours,
			WeeklyOverTimeHours,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate,
			DayStartTime,
			DayEndTime,
			NightStartTime,
			NightEndTime,
			MaxDailyOvertimeHours,
			IsAutoApproveOvertime
	FROM	D_RamadanPeriod
	WHERE	(RamadanPeriodId		=	@RamadanPeriodId OR @RamadanPeriodId = 0)

	--SELECT  1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_GetRamadanPeriodEmployeeListById')
	DROP PROC prD_GetRamadanPeriodEmployeeListById
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_GetRamadanPeriodEmployeeListById
----------------------------------------------------------------------------
CREATE PROC prD_GetRamadanPeriodEmployeeListById
	@TranId		BigInt,
	@EmployeeId	BigInt
AS

SELECT	TranId,
		D_RamadanPeriodEmployeeList.RamadanPeriodId,
		D_RamadanPeriodEmployeeList.EmployeeId,
		D_RamadanPeriod.Description,
		D_RamadanPeriod.PeriodStart,
		D_RamadanPeriod.PeriodEnd,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		D_RamadanPeriodEmployeeList.TypeId,
		D_RamadanPeriodEmployeeList.TypeDescription,
		D_RamadanPeriodEmployeeList.CreatedBy,
		D_RamadanPeriodEmployeeList.CreatedDate,
		D_RamadanPeriodEmployeeList.UpdatedBy,
		D_RamadanPeriodEmployeeList.UpdatedDate
FROM	D_RamadanPeriodEmployeeList WITH (NOLOCK) 
		INNER JOIN C_Employee WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = C_Employee.EmployeeId
		INNER JOIN D_RamadanPeriod WITH (NOLOCK) ON D_RamadanPeriod.RamadanPeriodId = D_RamadanPeriodEmployeeList.RamadanPeriodId
WHERE	(D_RamadanPeriodEmployeeList.EmployeeId	= @EmployeeId OR @EmployeeId = 0)
AND		(TranId = @TranId OR @TranId = 0)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_GetRamadanPeriodEmployeesByRamadanPeriodId')
	DROP PROC prD_GetRamadanPeriodEmployeesByRamadanPeriodId
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_GetRamadanPeriodEmployeesByRamadanPeriodId
----------------------------------------------------------------------------
CREATE PROC prD_GetRamadanPeriodEmployeesByRamadanPeriodId
	@RamadanPeriodId	BigInt,
	@OUId				BigInt
AS

SELECT	TranId,
		D_RamadanPeriod.RamadanPeriodId,
		D_RamadanPeriod.Description RamadanPeriodDescription,
		D_RamadanPeriodEmployeeList.EmployeeId,
		D_RamadanPeriod.Description,
		D_RamadanPeriod.PeriodStart,
		D_RamadanPeriod.PeriodEnd,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		D_RamadanPeriodEmployeeList.TypeId,
		D_RamadanPeriodEmployeeList.TypeDescription,
		D_RamadanPeriodEmployeeList.CreatedBy,
		D_RamadanPeriodEmployeeList.CreatedDate,
		D_RamadanPeriodEmployeeList.UpdatedBy,
		D_RamadanPeriodEmployeeList.UpdatedDate,
		D_Roles.RoleId,
		D_Roles.RoleName PrimaryRoleName
FROM	D_RamadanPeriodEmployeeList WITH (NOLOCK) 
		INNER JOIN C_Employee WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = C_Employee.EmployeeId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId  = C_Employee.EmployeeId
		INNER JOIN D_Roles	WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1 
		INNER JOIN D_RamadanPeriod WITH (NOLOCK) ON D_RamadanPeriod.RamadanPeriodId = D_RamadanPeriodEmployeeList.RamadanPeriodId
WHERE	D_RamadanPeriodEmployeeList.RamadanPeriodId	= @RamadanPeriodId
--AND		C_Employee.OUId		=	@OUId


GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetRoleSkillByRoles]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_GetRoleSkillByRoles]
GO
/****** Object:  StoredProcedure [dbo].[prD_GetRoleSkillByRoles]    Script Date: 6/22/2018 6:48:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_GetRoleSkillByRoles]    
(
	@Roles			nVarchar(max),
	@PrimaryRoleId	BigInt

)
AS
BEGIN

	SELECT	D_Roles.RoleId,
			D_Roles.RoleName,
			D_Roles.RoleDesc,
			D_Roles.PrimarySkillId,
			D_Roles.CreatedBy,
			D_Roles.CreatedDate
	FROM	D_Roles 
	WHERE	D_Roles.RoleId	=	@PrimaryRoleId


	SELECT	D_RoleSkill.RoleId ,
			D_RoleSkill.RoleSkillId ,
			D_RoleSkill.SkillId ,
			D_RoleSkill.Priority, 
			D_Skill.Skill SkillCode,
			D_Skill.SkillDesc SkillDescription,
			D_Skill.Seq SkillSequence,
			D_Skill.LicenceRequired IsLicenceRequired,
			D_RoleSkill.CreatedBy, 
			D_RoleSkill.CreatedDate		 
	FROM	D_RoleSkill  WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_RoleSkill.SkillId = D_Skill.SkillId
			--INNER JOIN D_Roles WITH (NOLOCK) ON D_RoleSkill.RoleId = D_Roles.RoleId		 
	WHERE	D_RoleSkill.RoleId	IN (SELECT * FROM fnStringToTable(@Roles)) 
	ORDER BY D_Skill.Skill
END
GO
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_MasterCodeIdByTypeAndName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_MasterCodeIdByTypeAndName]
GO
/****** Object:  StoredProcedure [dbo].[prD_MasterCodeIdByTypeAndName]    Script Date: 7/31/2018 10:18:26 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prD_MasterCodeIdByTypeAndName]    
(
	@CodeType nvarchar(50) ,
	@CodeValue nvarchar(500) 
)
AS
DECLARE @MaritalStatusId bigint = 0
BEGIN

	SELECT	@MaritalStatusId =  CodeId
	FROM	D_MasterCodes WITH (NOLOCK)
	WHERE	CodeType =@CodeType and CodeValue=@CodeValue
 

 SELECT @MaritalStatusId;
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_MasterCodesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_MasterCodesIns]
GO

Create PROCEDURE [dbo].[prD_MasterCodesIns]    
(
	@CodeType		nVarchar(50),
	@CodeValue		nVarchar(500),
	@Sequence		Int,
	@IsActive		Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_MasterCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(CodeValue))) = LTrim(RTrim(Upper(@CodeValue)))
	AND		LTrim(RTrim(Upper(CodeType))) = LTrim(RTrim(Upper(@CodeType)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_MasterCodes
		(CodeType, CodeValue, Seq, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@CodeType, @CodeValue, @Sequence, @IsActive, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_MasterCodesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_MasterCodesSel]
GO


CREATE PROCEDURE [dbo].[prD_MasterCodesSel]    
(
	@ID			BigInt
	--@CodeType	nVarchar(50),
	--@IsActive	Bit
)
AS
BEGIN
	SELECT	CodeId,
			CodeType,
			CodeValue,
			Seq,
			ActiveStatus, 
			CreatedBy, 
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_MasterCodes
	WHERE	(D_MasterCodes.CodeId = @ID OR @ID = 0)
	--AND		(D_MasterCodes.CodeType LIKE (@CodeType))
	--AND		D_MasterCodes.ActiveStatus = @IsActive 
	ORDER BY D_MasterCodes.CodeType, CodeValue, Seq
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_MasterCodesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_MasterCodesUpd]
GO

CREATE PROCEDURE [dbo].[prD_MasterCodesUpd]    
(
	@CodeID				BigInt,
	@CodeType		nVarchar(50),
	@CodeValue		nVarchar(500),
	@Sequence		Int,
	@IsActive		Bit,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_MasterCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(CodeValue))) = LTrim(RTrim(Upper(@CodeValue)))
	AND		LTrim(RTrim(Upper(CodeType))) = LTrim(RTrim(Upper(@CodeType)))
	AND		CodeId	!=	@CodeID

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_MasterCodes
		SET		CodeType		=	@CodeType, 
				CodeValue		=	@CodeValue, 
				Seq				=	@Sequence, 
				ActiveStatus	=	@IsActive, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	CodeId			=	@CodeID
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

/****** Object:  StoredProcedure [dbo].[prD_PayCodeDel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodeDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodeDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodeDel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_PayCodeDel]
(
	@PayCodeId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	D_PayCodes
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	PayCodeId	=	@PayCodeId

	SELECT 1
END 

GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodeOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodeOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUDel]    Script Date: 6/22/2018 11:52:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodeOUDel]    
(
	@PayCodeId			BigInt,
	@OUId				BigInt
)
AS
DECLARE @PayCodeOUId BigInt = 0;
BEGIN

	SELECT	@PayCodeOUId = IsNull(PayCodeOUId,0)
	FROM	D_PayCodeOU WITH (NOLOCK)
	WHERE	PayCodeId =	@PaycodeId
	AND		OUId	=	@OUId

	If (@PaycodeOUId > 0)
	BEGIN
		DELETE FROM D_PayCodeOU
		WHERE	PayCodeOUId	= @PayCodeOUId

		SELECT 1;
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodeOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodeOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUIns]    Script Date: 6/22/2018 11:53:26 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodeOUIns]    
(
	@PayCodeId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @PayCodeOUId BigInt = 0;
BEGIN

	SELECT	@PayCodeOUId = IsNull(PayCodeOUId,0)
	FROM	D_PayCodeOU WITH (NOLOCK)
	WHERE	PayCodeId =	@PayCodeId
	AND		OUId	=	@OUId

	If (@PayCodeOUId = 0)
	BEGIN
		INSERT INTO D_PayCodeOU
		(PayCodeId, OUId, CreatedBy, CreatedDate)
		VALUES(@PayCodeId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUSel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodeOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodeOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayCodeOUSel]    Script Date: 6/22/2018 11:54:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodeOUSel]    
(
	@PayCodeId	BigInt
)
AS
BEGIN
	SELECT	D_PayCodeOU.PayCodeOUId,
			D_PayCodes.PayCodeId,
			D_PayCodeOU.OUId,
			D_PayCodeOU.CreatedBy, 
			D_PayCodeOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_PayCodeOU WITH (NOLOCK) 
			INNER JOIN D_PayCodes WITH (NOLOCK) ON D_PayCodeOU.PayCodeId = D_PayCodes.PayCodeId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_PayCodeOU.OUId  
			WHERE	D_PayCodeOU.PayCodeId		=	@PayCodeId 
END

GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodesIns]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodesIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodesIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodesIns]    
(
	@PayCode		nVarchar(50),
	@PayCodeDesc	nVarchar(500),
	@Sequence		Int,
	@IsActive		Bit,
	@CreatedBy		nVarchar(50),
	@Multiplier		Decimal(18,5)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PayCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PayCode))) = LTrim(RTrim(Upper(@PayCode)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_PayCodes
		(PayCode, PayCodeDesc, Seq, ActiveStatus, CreatedBy, CreatedDate, Multiplier)
		VALUES(@PayCode, @PayCodeDesc, @Sequence, @IsActive, @CreatedBy, GETDATE(), @Multiplier)

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodesSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodesSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodesSel]    
(
	@PayCodeID			Numeric(18,0),
	@OUID				BigInt
)
AS
BEGIN
	SELECT	D_PayCodes.PayCodeId,
			D_PayCodes.PayCode,
			D_PayCodes.PayCodeDesc PayCodeDescription,
			D_PayCodes.Seq Sequence,
			D_PayCodes.ActiveStatus, 
			D_PayCodes.CreatedBy, 
			D_PayCodes.CreatedDate,
			D_PayCodes.UpdatedBy,
			D_PayCodes.UpdatedDate,
			D_PayCodes.Multiplier,
			D_PayCodes.IsEditable
	FROM	D_PayCodes WITH (NOLOCK) 
			INNER JOIN D_PayCodeOU WITH (NOLOCK)  ON D_PayCodes.PayCodeId = D_PaycodeOU.PayCodeId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_PayCodeOU.OUId = C_OrganizationNode.OUId
	WHERE	(D_PayCodes.PayCodeId = @PayCodeID OR @PayCodeID = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
	ORDER BY D_PayCodes.PayCode
END
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodesUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayCodesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayCodesUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayCodesUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayCodesUpd]    
(
	@PayCodeId		BigInt,
	@PayCode		nVarchar(50),
	@PayCodeDesc	nVarchar(500),
	@Sequence		Int,
	@IsActive		Bit,
	@UpdatedBy		nVarchar(50),
	@Multiplier		Decimal(18,5)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PayCodes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PayCode))) = LTrim(RTrim(Upper(@PayCode)))
	AND		PayCodeId	!=	@PayCodeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_PayCodes
		SET		PayCode			=	@PayCode, 
				PayCodeDesc		=	@PayCodeDesc, 
				Seq				=	@Sequence,
				ActiveStatus	=	@IsActive, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE(),
				Multiplier		=	@Multiplier				
		WHERE	PayCodeId		=	@PayCodeId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupCodesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupCodesDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesDel]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupCodesDel]    
(
	@PayGroupId			BigInt,
	@PayGroupPayCodeId	BigInt
)
AS
BEGIN

	DELETE FROM D_PaygroupCodes
	WHERE	PayGroupId			=	@PayGroupId
	AND		PayGroupPayCodeId	=	@PayGroupPayCodeId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupCodesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupCodesIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupCodesIns]    
(
	@PayGroupId			BigInt,
	@PayCodeId			BigInt,
	@PaycodeType		Int,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	INSERT INTO D_PaygroupCodes
	(PayGroupId, PayCodeId, PaycodeType, CreatedBy, CreatedDate)
	VALUES(@PayGroupId, @PayCodeId, @PaycodeType, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupCodesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupCodesSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupCodesSel]    
(
	@PayGroupID			BigInt
)
AS
BEGIN
	SELECT	D_PaygroupCodes.PayGroupPayCodeId,
			D_PaygroupCodes.PayGroupId,
			D_PaygroupCodes.PayCodeId,
			D_PaygroupCodes.PaycodeType PayCodeType,
			D_PayCodes.PayCode,
			D_PaygroupCodes.CreatedBy,D_PayCodes.Multiplier
	FROM	D_PaygroupCodes WITH (NOLOCK) 
			INNER JOIN D_PayCodes WITH (NOLOCK) ON D_PaygroupCodes.PayCodeId = D_PayCodes.PayCodeId
			INNER JOIN D_PayGroup WITH (NOLOCK) ON D_PaygroupCodes.PayGroupId = D_PayGroup.PayGroupId
	WHERE	(D_PaygroupCodes.PayGroupId = @PayGroupID OR @PayGroupID = 0)
	ORDER BY D_PayCodes.PayCode
END

GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupCodesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupCodesUpd]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupCodesUpd]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupCodesUpd]    
(
	@PayGroupPayCodeId	BigInt,
	@PayGroupId			BigInt,
	@PayCodeId			BigInt,
	@PaycodeType		Int,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	UPDATE	D_PaygroupCodes
	SET		PayGroupId			=	@PayGroupId, 
			PayCodeId			=	@PayCodeId, 
			PaycodeType			=	@PaycodeType, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	PayGroupPayCodeId	=	@PayGroupPayCodeId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prD_PayCodeDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupDel]    Script Date: 6/22/2018 11:47:08 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_PayGroupDel]
(
	@PayGroupId		BigInt,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	UPDATE	D_PayGroup
	SET		ActiveStatus		=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GetDate()
	WHERE	PayGroupId			=	@PaygroupId

	SELECT 1
END 
GO
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupIdByName]    Script Date: 7/31/2018 10:22:01 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prD_PayGroupIdByName]    
(
	@PayGroupCode nvarchar(50) 
)
AS
DECLARE @PayGroupId bigint = 0
BEGIN

	SELECT	@PayGroupId =  PayGroupId
	FROM	D_PayGroup WITH (NOLOCK)
	WHERE	PayGroupCode =@PayGroupCode 
 

 SELECT @PayGroupId;
	 
END
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupIns]    
(
	@PayGroupCode		nVarchar(50),
	@PayGroupDesc		nVarchar(500),
	@PayPeriod			nVarchar(500),
	@IsActive			Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PayGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PayGroupCode))) = LTrim(RTrim(Upper(@PayGroupCode)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_PayGroup
		(PayGroupCode, PayGroupDesc, PayPeriod, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@PayGroupCode, @PayGroupDesc, @PayPeriod, @IsActive, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUDel]    Script Date: 6/21/2018 6:29:24 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prD_PayGroupOUDel]    
(	
	@PayGroupId	        BigInt,
	@OUID				BigInt
)
AS
BEGIN
	DELETE FROM D_PayGroupOU
	WHERE	OUId = @OUID
	AND		PayGroupId = @PayGroupId
	SELECT 1
 
END
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUIns]    Script Date: 6/21/2018 6:31:01 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prD_PayGroupOUIns]    
(
	@PayGroupId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @PayGroupOUId BigInt = 0;
BEGIN

	SELECT	@PayGroupOUId	= IsNull(PayGroupOUId,0)
	FROM	D_PayGroupOU WITH (NOLOCK)
	WHERE	PayGroupId		=	@PayGroupId
	AND		OUId			=	@OUId

	If (@PayGroupOUId = 0)
	BEGIN
		INSERT INTO D_PayGroupOU
		(PayGroupId, OUId, CreatedBy, CreatedDate)
		VALUES(@PayGroupId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupOUSel]    Script Date: 6/21/2018 6:31:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupOUSel]    
(
	@PayGroupId	BigInt
)
AS
BEGIN
	SELECT	D_PayGroupOU.PayGroupOUId,
			D_PayGroup.PayGroupId,
			D_PayGroupOU.OUId,
			D_PayGroupOU.CreatedBy, 
			D_PayGroupOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_PayGroupOU WITH (NOLOCK) 
			INNER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroupOU.PayGroupId = D_PayGroup.PayGroupId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_PayGroupOU.OUId  
			WHERE	D_PayGroupOU.PayGroupId		=	@PayGroupId 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupSel]    
(
	@PayGroupID			Numeric(18,0),
	@OUID				BigInt
)
AS
BEGIN
	SELECT	D_PayGroup.PayGroupId,
			D_PayGroup.PayGroupCode,
			D_PayGroup.PayGroupDesc PayGroupDescription,
			D_PayGroup.PayPeriod,
			D_PayGroup.ActiveStatus, 
			D_PayGroup.CreatedBy, 
			D_PayGroup.CreatedDate,
			D_PayGroup.UpdatedBy,
			D_PayGroup.UpdatedDate
	FROM	D_PayGroup WITH (NOLOCK) 
			INNER JOIN D_PayGroupOU WITH (NOLOCK)  ON D_PayGroup.PayGroupId = D_PayGroupOU.PayGroupId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_PayGroupOU.OUId = C_OrganizationNode.OUId
	WHERE	(D_PayGroup.PayGroupId = @PayGroupID OR @PayGroupID = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
	ORDER BY D_PayGroup.PayGroupCode
END

GO
/****** Object:  StoredProcedure [dbo].[prD_PayGroupUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PayGroupUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PayGroupUpd]
GO

/****** Object:  StoredProcedure [dbo].[prD_PayGroupUpd]    Script Date: 6/22/2018 11:50:00 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_PayGroupUpd]    
(
	@PayGroupId		BigInt,
	@PayGroupCode	nVarchar(50),
	@PayGroupDesc	nVarchar(500),
	@PayPeriod		nVarchar(500),
	@IsActive		Bit,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PayGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PayGroupCode))) = LTrim(RTrim(Upper(@PayGroupCode)))
	AND		PayGroupId	!=	@PayGroupId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_PayGroup
		SET		PayGroupCode	=	@PayGroupCode, 
				PayGroupDesc	=	@PayGroupDesc, 
				PayPeriod		=	@PayPeriod,
				ActiveStatus	=	@IsActive, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	PayGroupId		=	@PayGroupId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PublicHolidaysDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PublicHolidaysDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PublicHolidaysDel]    Script Date: 7/6/2018 6:10:13 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_PublicHolidaysDel]
(
	@PublicHolidayId		BigInt 
)
AS
BEGIN
	delete from D_PublicHolidays	 
	WHERE	PublicHolidayId		=	@PublicHolidayId

	SELECT 1
END 
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PublicHolidaysIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PublicHolidaysIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_PublicHolidaysIns]    Script Date: 7/6/2018 6:10:59 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_PublicHolidaysIns]    
(
	@HolidayName		nVarchar(500),
	@HolidayDate		date,
	@IsPaid				bit,
	@HolidayNote		nvarchar(500),
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PublicHolidays WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(HolidayName))) = LTrim(RTrim(Upper(@HolidayName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_PublicHolidays
		(HolidayName, HolidayDate, IsPaid, HolidayNote, CreatedBy, CreatedDate)
		VALUES(@HolidayName, @HolidayDate, @IsPaid, @HolidayNote, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PublicHolidaysSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PublicHolidaysSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_PublicHolidaysSel]    Script Date: 7/6/2018 6:11:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[prD_PublicHolidaysSel]    
(
	@PublicHolidayId			Numeric(18,0)
)
AS
BEGIN
	SELECT	PublicHolidayId,
			HolidayName,
			HolidayDate  ,
			IsPaid,
			HolidayNote, 
			CreatedBy, 
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_PublicHolidays
	WHERE	(PublicHolidayId = @PublicHolidayId	 OR @PublicHolidayId	= 0)
	ORDER BY HolidayDate
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_PublicHolidaysUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_PublicHolidaysUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_PublicHolidaysUpd]    Script Date: 7/6/2018 6:12:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_PublicHolidaysUpd]    
(
	@PublicHolidayId		BigInt,
	@HolidayName			nvarchar(500),
	@HolidayDate			date,
	@IsPaid					bit,
	@HolidayNote			nVarchar(500),	
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PublicHolidays WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(HolidayName))) = LTrim(RTrim(Upper(@HolidayName)))
	AND		PublicHolidayId	!=	@PublicHolidayId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_PublicHolidays
		SET		HolidayName	=	@HolidayName, 
				HolidayDate	=	@HolidayDate, 
				HolidayNote		=	@HolidayNote,
				IsPaid	=	@IsPaid, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	PublicHolidayId		=	@PublicHolidayId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prD_ReliefRuleDel]    
(	
	@RuleId	           BigInt 
)
AS
BEGIN
	 

	Update D_ReliefRule  set ActiveStatus =0 where RuleId =@RuleId 
	SELECT 1
	 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prD_ReliefRuleIns]    
(		
	@OUId					Bigint, 
	@RuleName			nVarchar(1000),
	@RuleDesc			nVarchar(1000),	 
	@ActiveStatus			INT,	 
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ReliefRule WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RuleName))) = LTrim(RTrim(Upper(@RuleName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_ReliefRule
		(RuleName,RuleDesc, OUId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@RuleName, @RuleDesc,@OUId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
Create PROCEDURE [dbo].[prD_ReliefRuleSel]    
(
	@RuleId		bigint ,
	@OUID				BigInt
)
AS
BEGIN
	SELECT 	D_ReliefRule.RuleId,
			D_ReliefRule.OUId, 
			D_ReliefRule.RuleName,
			D_ReliefRule.RuleDesc ,	
			D_ReliefRule.ActiveStatus,  
			D_ReliefRule.CreatedBy, 
			D_ReliefRule.CreatedDate,
			D_ReliefRule.UpdatedBy,
			D_ReliefRule.UpdatedDate
	FROM	D_ReliefRule	  WITH (NOLOCK) 	
	INNER JOIN C_OrganizationNode with (NOLOCK) ON D_ReliefRule.OUId = C_OrganizationNode.OUId		 
	WHERE	(D_ReliefRule.RuleId = @RuleId OR @RuleId = 0)
	 AND		(C_OrganizationNode.OUId = @OUID)
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleSkillDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleSkillDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ReliefRuleSkillDel]
(
	@RuleId		BigInt ,
	@SkillId	bigint
)
AS
BEGIN
	DELETE FROM 	D_ReliefRuleSkill 
	WHERE	RuleId	=	@RuleId and SkillId=@SkillId

	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleSkillIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleSkillIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 
 
Create PROCEDURE [dbo].[prD_ReliefRuleSkillIns]    
(		
	@RuleId				Bigint, 
	@Seq				bigint,	 	 
	@Clause				nvarchar(50),	
	@SkillId			bigint, 
	@OperatingHour		int,
	@NoOfEmployee		int,
	@NoOfActivity		int,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ReliefRuleSkill WITH (NOLOCK)
	WHERE	RuleId = @RuleId and SkillId=@SkillId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_ReliefRuleSkill
		(RuleId,Seq,Clause,SkillId,OperatingHour,NoOfEmployee,NoOfActivity,CreatedBy, CreatedDate)
		VALUES(@RuleId, @Seq,@Clause,@SkillId,@OperatingHour,@NoOfEmployee,@NoOfActivity,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleSkillSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleSkillSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
Create PROCEDURE [dbo].[prD_ReliefRuleSkillSel]    
(
	@RuleId		bigint 
)
AS
BEGIN
	SELECT	D_ReliefRuleSkill.RuleDetId,
			D_ReliefRuleSkill.RuleId,
			D_ReliefRuleSkill.Seq, 
			D_ReliefRuleSkill.Clause,
			D_ReliefRuleSkill.SkillId ,	
			D_ReliefRuleSkill.OperatingHour	,
			D_ReliefRuleSkill.NoOfEmployee,
			D_ReliefRuleSkill.NoOfActivity,	 
			D_ReliefRuleSkill.CreatedBy, 
			D_ReliefRuleSkill.CreatedDate,
			D_ReliefRuleSkill.UpdatedBy,
			D_ReliefRuleSkill.UpdatedDate,
			D_Skill.Skill as SkillName
	FROM	D_ReliefRuleSkill	  WITH (NOLOCK) 
			left outer join D_Skill on D_Skill.SkillId= D_ReliefRuleSkill.SkillId 
	WHERE	(D_ReliefRuleSkill.RuleId = @RuleId OR @RuleId = 0)
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleSkillUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleSkillUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ReliefRuleSkillUpd]    
(
	@RuleDetId			Bigint,
	@RuleId				Bigint, 
	@Seq				bigint,	 	 
	@Clause				nvarchar(50),	
	@SkillId			bigint, 
	@OperatingHour		int,
	@NoOfEmployee		int,
	@NoOfActivity		int,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ReliefRuleSkill WITH (NOLOCK)
	WHERE	RuleId=@RuleId and SkillId=@SkillId
	AND		RuleDetId	!=	@RuleDetId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_ReliefRuleSkill
		SET		RuleId				=	@RuleId, 
				Seq					=	@Seq, 				 
				Clause				=	@Clause, 
				SkillId				=	@SkillId, 
				OperatingHour		=	@OperatingHour ,
				NoOfEmployee		=	@NoOfEmployee,
				NoOfActivity		=	@NoOfActivity,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	RuleDetId			=	@RuleDetId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ReliefRuleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ReliefRuleUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ReliefRuleUpd]    
(
	@RuleId		BigInt,
	@OUId					Bigint, 
	@RuleName			nVarchar(1000),
	@RuleDesc			nVarchar(1000),	 
	@ActiveStatus			INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ReliefRule WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RuleName))) = LTrim(RTrim(Upper(@RuleName)))
	AND		RuleId	!=	@RuleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_ReliefRule
		SET		RuleName				=	@RuleName, 
				RuleDesc				=	@RuleDesc, 				 
				ActiveStatus			=	@ActiveStatus, 
				OUId					=	@OUId,  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	RuleId					=	@RuleId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_RoleDel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 


create PROCEDURE [dbo].[prD_RoleDel]
(
	@RoleId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	D_Roles
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	RoleId	=	@RoleId

	SELECT 1
END 
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleGroupCountSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleGroupCountSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleGroupCountSel]    Script Date: 7/6/2018 7:49:08 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleGroupCountSel]    
(
	@OUID				BigInt
)
AS
BEGIN
	SELECT	D_RoleGroup.RoleGroupName as RoleGroupDescription,
			0 as RoleGroupCount,D_RoleGroup.RoleGroupId as RoleGroupId
	FROM	D_RoleGroup	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_RoleGroup.OUId = C_OrganizationNode.OUId
	WHERE (C_OrganizationNode.OUId = @OUID)	
	ORDER BY D_RoleGroup.RoleGroupName
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleGroupDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleGroupDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleGroupDel]    Script Date: 6/29/2018 6:18:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prD_RoleGroupDel]    
(	
	@RoleGroupId	           BigInt 
)
AS
BEGIN
	DELETE FROM D_RoleGroup 
	WHERE 	RoleGroupId = @RoleGroupId

	Update D_Roles  set RoleGroupId =null where RoleGroupId =@RoleGroupId 
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleGroupIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleGroupIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleGroupIns]    Script Date: 6/29/2018 6:19:56 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleGroupIns]    
(	
	@RoleGroupName			nVarchar(50),
	@OUId	Bigint, 
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_RoleGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleGroupName))) = LTrim(RTrim(Upper(@RoleGroupName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_RoleGroup
		(RoleGroupName, OUId,CreatedBy, CreatedDate)
		VALUES(@RoleGroupName, @OUId,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleGroupSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleGroupSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleGroupSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleGroupSel]    
(
	@RoleGroupId		bigint,
	@OUID				BigInt,
	@FilteredOUList		nVarchar(max)
)
AS
BEGIN
	SELECT	D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			D_RoleGroup.OUId ,			 
			D_RoleGroup.CreatedBy, 
			D_RoleGroup.CreatedDate,
			D_RoleGroup.UpdatedBy,
			D_RoleGroup.UpdatedDate
	FROM	D_RoleGroup	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_RoleGroup.OUId = C_OrganizationNode.OUId
	WHERE	(D_RoleGroup.RoleGroupId = @RoleGroupId OR @RoleGroupId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))) 
	ORDER BY D_RoleGroup.RoleGroupName
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleGroupUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleGroupUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleGroupUpd]    Script Date: 6/29/2018 6:21:36 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_RoleGroupUpd]    
(
	@RoleGroupId		BigInt,
	@RoleGroupName		nVarchar(50),
	@OUId   Bigint,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_RoleGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleGroupId))) = LTrim(RTrim(Upper(@RoleGroupId)))
	AND		RoleGroupId	!=	@RoleGroupId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_RoleGroup
		SET		RoleGroupName			=	@RoleGroupName, 
				OUId		=	@OUId,  
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	RoleGroupId		=	@RoleGroupId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleIns]    Script Date: 6/22/2018 7:14:02 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_RoleIns]    
(	
	@RoleName			nVarchar(50),
	@RoleDesc	nVarchar(500),
	@PreparationTime		Int,
	@DePreparationTime	int,
	@PrimarySkillId int,
	@ActiveStatus bit, 
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Roles WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleName))) = LTrim(RTrim(Upper(@RoleName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_Roles
		(RoleName, RoleDesc, PreparationTime, DePreparationTime,PrimarySkillId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@RoleName, @RoleDesc, @PreparationTime, @DePreparationTime,@PrimarySkillId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_RoleOUDel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_RoleOUDel]    
(	
	@RoleId	           BigInt,
	@OUID				BigInt
)
AS
BEGIN
	DELETE FROM D_RoleOU
	WHERE	OUId = @OUID
	AND		RoleId = @RoleId
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_RoleOUIns]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prD_RoleOUIns]    
(
	@RoleId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @RoleOUId BigInt = 0;
BEGIN

	SELECT	@RoleOUId = IsNull(RoleOUId,0)
	FROM D_RoleOU WITH (NOLOCK)
	WHERE	RoleId =	@RoleId
	AND		OUId	=	@OUId

	If (@RoleOUId = 0)
	BEGIN
		INSERT INTO D_RoleOU
		(RoleId, OUId, CreatedBy, CreatedDate)
		VALUES(@RoleId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_RoleOUSel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_RoleOUSel]    
(
	@RoleId	BigInt
)
AS
BEGIN
	SELECT	D_RoleOU.RoleOUId,
			D_Roles.RoleName,
			D_RoleOU.OUId,
			D_RoleOU.CreatedBy, 
			D_RoleOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_RoleOU WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON D_RoleOU.RoleId = D_Roles.RoleId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_RoleOU.OUId  
			WHERE	D_RoleOU.RoleId		=	@RoleId 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleSel]    Script Date: 6/29/2018 6:22:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleSel]    
(
	@RoleId			Numeric(18,0),
	@OUID				BigInt
)
AS
BEGIN
	SELECT	D_Roles.RoleId,
			D_Roles.RoleName,
			D_Roles.RoleDesc as RoleDescription ,
			D_Roles.ActiveStatus,
			D_Roles.PreparationTime,
			D_Roles.DePreparationTime,
			D_Roles.CreatedBy, 
			D_Roles.CreatedDate,
			D_Roles.UpdatedBy,
			D_Roles.UpdatedDate,
			D_Roles.RoleGroupId,
			D_Roles.PrimarySkillId,
			D_Skill.Skill SkillCode,
			D_Skill.SkillDesc SkillDescription,
			D_Skill.Seq SkillSequence,
			D_Skill.LicenceRequired IsLicenceRequired
	FROM	D_Roles	  WITH (NOLOCK)
			INNER JOIN D_RoleOU WITH (NOLOCK)  ON D_Roles.RoleId  = D_RoleOU.RoleId
			LEFT OUTER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId	  = D_Roles.PrimarySkillId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_RoleOU.OUId = C_OrganizationNode.OUId
	WHERE	(D_Roles.RoleId = @RoleId OR @RoleId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
	ORDER BY D_Roles.RoleName
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RolesIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RolesIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prD_RolesIdByName]    Script Date: 7/31/2018 10:27:00 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 

CREATE PROCEDURE [dbo].[prD_RolesIdByName]     
(
	@RoleName		nvarchar(50)
)
AS
DECLARE @RoleId int = 0
BEGIN

	SELECT	@RoleId =  RoleId
	FROM	D_Roles WITH (NOLOCK)
	WHERE	RoleName =@RoleName
 

 SELECT @RoleId;
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleSkillByOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleSkillByOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleSkillByOUSel]    Script Date: 6/22/2018 6:48:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleSkillByOUSel]    
(
	@OuId	BigInt
)
AS
BEGIN
	SELECT	D_RoleSkill.RoleId ,
			D_RoleSkill.RoleSkillId ,
			D_RoleSkill.SkillId ,
			D_RoleSkill.Priority, 
			D_Skill.Skill SkillCode,
			D_Skill.SkillDesc SkillDescription,
			D_Skill.Seq SkillSequence,
			D_Skill.LicenceRequired IsLicenceRequired,
			D_RoleSkill.CreatedBy, 
			D_RoleSkill.CreatedDate		 
	FROM	D_RoleSkill  WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_RoleSkill.SkillId = D_Skill.SkillId
			--INNER JOIN D_Roles WITH (NOLOCK) ON D_RoleSkill.RoleId = D_Roles.RoleId		 
	WHERE	EXISTS (
					SELECT	D_Roles.RoleId 
					FROM	D_Roles WITH (NOLOCK) 
							INNER JOIN D_RoleOU WITH (NOLOCK) ON D_Roles.RoleId = D_RoleOU.RoleId 
					WHERE D_RoleOU.OUId = @OuId OR @OUID = 0)
	ORDER BY D_Skill.Skill
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleSkillDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleSkillDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleSkillDel]    Script Date: 6/22/2018 6:51:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prD_RoleSkillDel]    
(	
	@RoleId	           BigInt,
	@SkillId				BigInt
)
AS
BEGIN
	DELETE FROM D_RoleSkill 
	WHERE	SkillId  = @SkillId
	AND		RoleId = @RoleId
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleSkillIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleSkillIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleSkillIns]    Script Date: 6/22/2018 6:50:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_RoleSkillIns]    
(	
	@RoleId			bigint,
	@SkillId	bigint,	
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_RoleSkill WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleId))) = LTrim(RTrim(Upper(@RoleId)))
	and LTrim(RTrim(Upper(SkillId))) = LTrim(RTrim(Upper(@SkillId)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_RoleSkill
		(RoleId, SkillId,CreatedBy, CreatedDate)
		VALUES(@RoleId, @SkillId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleSkillSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleSkillSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleSkillSel]    Script Date: 6/22/2018 6:48:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prD_RoleSkillSel]    
(
	@RoleId	BigInt
)
AS
BEGIN
	SELECT	D_RoleSkill.RoleId ,
			D_RoleSkill.RoleSkillId ,
			D_RoleSkill.SkillId ,
			D_RoleSkill.Priority, 
			D_Skill.Skill SkillCode,
			D_Skill.SkillDesc SkillDescription,
			D_Skill.Seq SkillSequence,
			D_Skill.LicenceRequired IsLicenceRequired,
			D_RoleSkill.CreatedBy, 
			D_RoleSkill.CreatedDate		 
	FROM	D_RoleSkill  WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_RoleSkill.SkillId = D_Skill.SkillId
			--INNER JOIN D_Roles WITH (NOLOCK) ON D_RoleSkill.RoleId = D_Roles.RoleId		 
	WHERE	D_RoleSkill.RoleId	=	@RoleId 
	ORDER BY D_Skill.Skill
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleUpd]    Script Date: 6/22/2018 7:16:01 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prD_RoleUpd]    
(
	@RoleId				BigInt,
	@RoleName			nVarchar(50),
	@RoleDesc			nVarchar(500),
	@PreparationTime	Int,
	@DePreparationTime 	int,	
	@PrimarySkillId		BigInt,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Roles WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleId))) = LTrim(RTrim(Upper(@RoleId)))
	AND		RoleId	!=	@RoleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_Roles
		SET		RoleName			=	@RoleName, 
				RoleDesc			=	@RoleDesc, 
				PreparationTime		=	@PreparationTime,
				DePreparationTime	=	@DePreparationTime,
				PrimarySkillId		=	@PrimarySkillId,
				ActiveStatus		=	@ActiveStatus, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	RoleId				=	@RoleId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_RoleUpdByRoleid]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_RoleUpdByRoleid]
GO
/****** Object:  StoredProcedure [dbo].[prD_RoleUpdByRoleid]    Script Date: 6/29/2018 6:23:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prD_RoleUpdByRoleid]    
(
	@RoleId		BigInt,
	 @RoleGroupId bigint,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Roles WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RoleId))) = LTrim(RTrim(Upper(@RoleId)))
	AND		RoleId	!=	@RoleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_Roles
		SET	  RoleGroupId = @RoleGroupId , 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	RoleId		=	@RoleId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_ShiftAuditSel')
	DROP PROC prD_ShiftAuditSel
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_ShiftAuditSel
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prD_ShiftAuditSel] 
	@EmployeeId	      bigInt,
				@StartTime   Datetime,
				@EndTime     Datetime	
	

AS
BEGIN
	SELECT    
                A_Shifts.ShiftId,
	            A_Shifts.Action,
				A_Shifts.ShiftBandName,
				S_Shifts.ShiftStartTime ,
				S_Shifts.ShiftEndTime ,
				S_Shifts.CreatedBy,
				S_Shifts.CreatedDate,
				A_Shifts.ClockIn,
				A_Shifts.ClockOut,
				A_Shifts.ReconStatus,
	            A_Shifts.InStatus,
				A_Shifts.OutStatus,
				A_Shifts.LeaveType,
				A_Shifts.LeaveApprovedBy,
				A_Shifts.LeaveAppliedDate,
				A_Shifts.LeaveApprovedDate,
				A_Shifts.ShiftCost,
				A_Shifts.Remarks,
				A_Shifts.ActionDate
FROM            A_Shifts            WITH (NOLOCK) 
                INNER JOIN S_Shifts WITH (NOLOCK)  ON S_Shifts.ShiftId = A_Shifts.ShiftId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId

WHERE           (C_Employee.EmployeeId	=	 1315 OR 1315 = 0) 
                AND		CONVERT(DATE,S_Shifts.ActualStartTime)>=CONVERT(DATE,@StartTime)
				AND		CONVERT(DATE,S_Shifts.ActualStartTime)<=CONVERT(DATE,@EndTime)
                
ORDER BY        A_Shifts.ShiftBandName
END

GO

				IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandCombinationDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandCombinationDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandCombinationDel]    Script Date: 6/27/2018 7:37:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ShiftBandCombinationDel]    
(	
	@ShiftBandId	           BigInt,
	@ComboShiftBandId				BigInt
)
AS
BEGIN
	DELETE FROM D_ShiftBandCombination
	WHERE	ShiftBandId = @ShiftBandId
	AND		ComboShiftBandId = @ComboShiftBandId
	SELECT 1
	 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandCombinationIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandCombinationIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandCombinationIns]    Script Date: 6/27/2018 7:36:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ShiftBandCombinationIns]    
(
	@ShiftBandId			BigInt,
	@ComboShiftBandId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ComboId BigInt = 0;
BEGIN

	SELECT	@ComboId = IsNull(ComboId,0)
	FROM D_ShiftBandCombination WITH (NOLOCK)
	WHERE	ShiftBandId =	@ShiftBandId
	AND		ComboShiftBandId	=	@ComboShiftBandId

	If (@ComboId = 0)
	BEGIN
		INSERT INTO D_ShiftBandCombination
		(ShiftBandId, ComboShiftBandId, CreatedBy, CreatedDate)
		VALUES(@ShiftBandId, @ComboShiftBandId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandCombinationSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandCombinationSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandCombinationSel]    Script Date: 6/27/2018 7:35:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ShiftBandCombinationSel]    
(
	@ShiftBandId	BigInt
)
AS
BEGIN
	SELECT	D_ShiftBandCombination.ComboId,
			D_ShiftBandCombination.ShiftBandId,
			D_ShiftBandCombination.ComboShiftBandId,
			D_ShiftBandCombination.CreatedBy, 
			D_ShiftBandCombination.CreatedDate			 
	FROM	D_ShiftBandCombination WITH (NOLOCK) 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = D_ShiftBandCombination.ShiftBandId		 
			WHERE	D_ShiftBandCombination.ShiftBandId		=	@ShiftBandId 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandIns]    Script Date: 7/10/2018 3:17:07 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ShiftBandIns]    
(
	@ShiftBandName		nVarchar(500),
	@ShiftBandCode		nVarchar(50),
	@ShiftBandDesc		nVarchar(100),	
	@ShiftTypeId        int,
	@StartTime          datetime,
	@StartRangeBegin    int,
	@StartRangeEnd      int,
	@EndTime            datetime,
	@EndRangeBegin      int,
	@EndRangeEnd        int,
	@ColorCode          nVarchar(50),
	@OvertimeType		nvarchar(50),
	@OverttimeStart		datetime,
	@OvertimeEnd		datetime,
	@ActiveStatus		bit,
	@CreatedBy			nvarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ShiftBand WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandCode))) = LTrim(RTrim(Upper(@ShiftBandCode)))
	--WHERE	LTrim(RTrim(Upper(ShiftBandName))) = LTrim(RTrim(Upper(@ShiftBandName)))
	--AND		LTrim(RTrim(Upper(ShiftBandCode))) = LTrim(RTrim(Upper(@ShiftBandCode)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_ShiftBand
		(ShiftBandName,
		 ShiftBandCode, 
		 ShiftBandDesc, 
		 ShiftTypeId, 
		 StartTime, 
		 StartRangeBegin,
		 StartRangeEnd,
		 EndTime,
		EndRangeBegin,
		EndRangeEnd,
		ColorCode,
		OvertimeType,
		OverttimeStart,
		OvertimeEnd,
		ActiveStatus,
		CreatedBy,
		CreatedDate)
 VALUES(@ShiftBandName, @ShiftBandCode, @ShiftBandDesc, @ShiftTypeId, @StartTime,@StartRangeBegin,@StartRangeEnd,@EndTime,
 @EndRangeBegin,@EndRangeEnd,@ColorCode,@OvertimeType,@OverttimeStart,@OvertimeEnd,@ActiveStatus,@CreatedBy,getdate())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandOUDel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandOUDel]    Script Date: 6/27/2018 7:33:00 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prD_ShiftBandOUDel]    
(	
	@ShiftBandId	           BigInt,
	@OUID				BigInt
)
AS
BEGIN
	DELETE FROM D_ShiftBandOU
	WHERE	OUId = @OUID
	AND		ShiftBandId = @ShiftBandId
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandOUIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandOUIns]    Script Date: 6/27/2018 7:33:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ShiftBandOUIns]    
(
	@ShiftBandId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ShiftBandOUId BigInt = 0;
BEGIN

	SELECT	@ShiftBandOUId = IsNull(ShiftBandOUId,0)
	FROM D_ShiftBandOU WITH (NOLOCK)
	WHERE	ShiftBandId =	@ShiftBandId
	AND		OUId	=	@OUId

	If (@ShiftBandOUId = 0)
	BEGIN
		INSERT INTO D_ShiftBandOU
		(ShiftBandId, OUId, CreatedBy, CreatedDate)
		VALUES(@ShiftBandId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandOUSel]    Script Date: 6/27/2018 7:34:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [dbo].[prD_ShiftBandOUSel]    
(
	@ShiftBandId	BigInt
)
AS
BEGIN
	SELECT	D_ShiftBandOu.ShiftBandOUId,
			D_ShiftBand.ShiftBandCode,
			D_ShiftBandOU.OUId,
			D_ShiftBandOU.CreatedBy, 
			D_ShiftBandOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_ShiftBandOU WITH (NOLOCK) 
			INNER JOIN D_ShiftBand  WITH (NOLOCK) ON D_ShiftBandOU.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_ShiftBandOU.OUId  
			WHERE	D_ShiftBandOU.ShiftBandId		=	@ShiftBandId 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandSel]    Script Date: 7/10/2018 3:18:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prD_ShiftBandSel]   
(
	@ShiftBandId	 bigInt,
	@OUID				BigInt,
	@FilteredOUList		nVarchar(max)
	
)
AS
BEGIN	 
	SELECT	DISTINCT D_ShiftBand.ShiftBandId,
			D_ShiftBand.ShiftBandName	, 
				D_ShiftBand.ShiftBandCode,
				D_ShiftBand. ShiftBandDesc,
				D_ShiftBand.ShiftTypeId, 
				D_ShiftBand.StartTime ,
				DATEADD(MINUTE,D_ShiftBand.StartRangeBegin,D_ShiftBand.StartTime) StartRangeBeginTime,
				DATEADD(MINUTE,D_ShiftBand.StartRangeEnd,D_ShiftBand.StartTime) StartRangeEndTime,
				D_ShiftBand.StartRangeBegin ,
				D_ShiftBand.StartRangeEnd ,
				D_ShiftBand.EndTime,
				DATEADD(MINUTE,D_ShiftBand.EndRangeBegin,D_ShiftBand.EndTime) EndRangeBeginTime,
				DATEADD(MINUTE,D_ShiftBand.EndRangeEnd,D_ShiftBand.EndTime) EndRangeEndTime,
				D_ShiftBand.EndRangeBegin ,
				D_ShiftBand.EndRangeEnd ,
				D_ShiftBand.ShiftLengthMin,
				D_ShiftBand.ShiftLengthMax,
				D_ShiftBand.ColorCode ,
				D_ShiftBand.OvertimeType,
				D_ShiftBand.OverttimeStart ,
				D_ShiftBand.OvertimeEnd ,
				D_ShiftBand.ActiveStatus, 
				D_ShiftBand.CreatedBy,
				D_ShiftBand.CreatedDate,
				D_ShiftBand.UpdatedBy	,
				D_ShiftBand.UpdatedDate	
	FROM	D_ShiftBand WITH (NOLOCK) 	
			INNER JOIN D_ShiftBandOU WITH (NOLOCK)  ON D_ShiftBand.ShiftBandId   = D_ShiftBandOU.ShiftBandId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_ShiftBandOU.OUId = C_OrganizationNode.OUId	
	WHERE	(D_ShiftBandOU.ShiftBandId = @ShiftBandId OR @ShiftBandId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0) --OR  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)))
	Order By D_ShiftBand.ShiftBandDesc
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandTypeDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandTypeDel]
GO
 

CREATE PROCEDURE [dbo].[prD_ShiftBandTypeDel]    
(
	@ShiftTypeId	Int,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	D_ShiftBandType
	SET		IsActive	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	ShiftTypeId		=@ShiftTypeId

	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandTypeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandTypeIns]
GO

Create PROCEDURE [dbo].[prD_ShiftBandTypeIns]    
(
	@ShiftBandTypeDescription		nVarchar(50),
	@Seq		int,	 
	@IsActive		Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ShiftBandType WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandTypeDescription))) = LTrim(RTrim(Upper(@ShiftBandTypeDescription)))
 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_ShiftBandType
		(ShiftBandTypeDescription, Seq,IsActive, CreatedBy, CreatedDate)
		VALUES(@ShiftBandTypeDescription, @Seq, @IsActive, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandTypeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandTypeSel]
GO
 
CREATE PROCEDURE [dbo].[prD_ShiftBandTypeSel]    
(
	@ShiftTypeId	 Int
)
AS
BEGIN	 
	SELECT	ShiftTypeId,
			ShiftBandTypeDescription,
			 Seq,
			 CreatedBy,
			 CreatedDate,
			 UpdatedBy,			 
			 UpdatedDate,
			 IsActive
	FROM	D_ShiftBandType 	
		 
	WHERE	(ShiftTypeId = @ShiftTypeId OR @ShiftTypeId = 0)
	Order By D_ShiftBandType.ShiftBandTypeDescription
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandTypeUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandTypeUpd]
GO

CREATE PROCEDURE [dbo].[prD_ShiftBandTypeUpd]    
(
	@ShiftTypeId		Int,
	@ShiftBandTypeDescription		nVarchar(50),
	@Seq		        int,	
	@IsActive		    bit,
	@UpdatedBy			nVarchar(50)
	
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ShiftBandType WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandTypeDescription))) = LTrim(RTrim(Upper(@ShiftBandTypeDescription))) 
	AND		ShiftTypeId	!=	@ShiftTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_ShiftBandType
		SET		ShiftBandTypeDescription		=	@ShiftBandTypeDescription, 
				Seq				    =	@Seq,  
				IsActive	        =	@IsActive, 
				UpdatedBy		    =	@UpdatedBy,
				UpdatedDate		    =	GETDATE()
		WHERE	ShiftTypeId			=	@ShiftTypeId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ShiftBandUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ShiftBandUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_ShiftBandUpd]    Script Date: 7/10/2018 3:19:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prD_ShiftBandUpd]    
(
	@ShiftBandId				BigInt,
	@ShiftBandName		nVarchar(500),
	@ShiftBandDesc		nvarchar(100),
	@ShiftBandCode		nVarchar(50),
	@ShiftTypeId		Int,
	@StartTime          datetime,
	@StartRangeBegin	 int,
	@StartRangeEnd		int,
	@EndTime			datetime,
	@EndRangeBegin		int,
	@EndRangeEnd		int,
	@ColorCode			nVarchar(50),
	@OvertimeType		nvarchar(50),
	@OverttimeStart		datetime,
	@OvertimeEnd		 datetime,
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_ShiftBand WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandCode))) = LTrim(RTrim(Upper(@ShiftBandCode)))
	--WHERE	LTrim(RTrim(Upper(ShiftBandName))) = LTrim(RTrim(Upper(@ShiftBandName)))
	--AND		LTrim(RTrim(Upper(ShiftBandCode))) = LTrim(RTrim(Upper(@ShiftBandCode)))
	AND	ShiftBandId	!=	@ShiftBandId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_ShiftBand
		SET		ShiftBandName		=	@ShiftBandName, 
				ShiftBandDesc		=	@ShiftBandDesc,
				ShiftBandCode		=	@ShiftBandCode, 
				ShiftTypeId			=	@ShiftTypeId, 
				StartTime			=	@StartTime,
				StartRangeBegin		=	@StartRangeBegin,
				StartRangeEnd		=	@StartRangeEnd,
				EndTime				=	@EndTime,
				EndRangeBegin		=	@EndRangeBegin,
				EndRangeEnd			=	@EndRangeEnd,
				ColorCode			=	@ColorCode,
				OvertimeType		=	@OvertimeType,
				OverttimeStart		=	@OverttimeStart,
				OvertimeEnd			=	@OvertimeEnd,
				ActiveStatus		=	@IsActive, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	ShiftBandId			=	@ShiftBandId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prD_SkillDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillDel]    Script Date: 20/6/2018 10:24:24 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillDel]
(
	@SkillId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	D_Skill
	SET		ActiveStatus		=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	SkillId	=	@SkillId

	SELECT 1
END 

GO





/****** Object:  StoredProcedure [dbo].[prD_SkillGroupIns]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillGroupIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillGroupIns]
GO
/****** Object:  StoredProcedure [dbo].[prD_SkillGroupIns]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillGroupIns]    
(
	@OUId				BigInt,
	@SkillGroupName		nVarchar(50),
	@SkillGroupDesc		nVarchar(500),
	@IsActive			Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_SkillGroups WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(SkillGroupName))) = LTrim(RTrim(Upper(@SkillGroupName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_SkillGroups
		(OUId, SkillGroupName, SkillGroupDesc, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OUId, @SkillGroupName, @SkillGroupDesc, @IsActive, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



GO
/****** Object:  StoredProcedure [dbo].[prD_SkillGroupSel]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillGroupSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillGroupSel]
GO
/****** Object:  StoredProcedure [dbo].[prD_SkillGroupSel]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillGroupSel]    
(
	@SkillGroupID			BigInt
)
AS
BEGIN
	SELECT	SkillGroupId,
			SkillGroupName,
			SkillGroupDesc SkillGroupDescription,
			D_SkillGroups.OUId,
			D_SkillGroups.ActiveStatus IsActive, 
			D_SkillGroups.CreatedBy, 
			D_SkillGroups.CreatedDate,
			D_SkillGroups.UpdatedBy,
			D_SkillGroups.UpdatedDate
	FROM	D_SkillGroups WITH (NOLOCK) 
			LEFT OUTER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON D_SkillGroups.OUId = OrgNode.OUId
	WHERE	(SkillGroupId = @SkillGroupID OR @SkillGroupID = 0)
	ORDER BY D_SkillGroups.SkillGroupName
END



GO
/****** Object:  StoredProcedure [dbo].[prD_SkillGroupUpd]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillGroupUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillGroupUpd]
GO
/****** Object:  StoredProcedure [dbo].[prD_SkillGroupUpd]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillGroupUpd]    
(
	@SkillGroupId		BigInt,
	@OUId				BigInt,
	@SkillGroupName		nVarchar(50),
	@SkillGroupDesc		nVarchar(500),
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_SkillGroups WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(SkillGroupName))) = LTrim(RTrim(Upper(@SkillGroupName)))
	AND		SkillGroupId	!= @SkillGroupId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_SkillGroups
		SET		OUId				=	@OUId, 
				SkillGroupName		=	@SkillGroupName, 
				SkillGroupDesc		=	@SkillGroupDesc, 
				ActiveStatus		=	@IsActive, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	SkillGroupId		=	@SkillGroupId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END


GO
/****** Object:  StoredProcedure [dbo].[prD_SkillIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillIns]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillIns]    
(
	@SkillCode			nVarchar(50),
	@SkillDesc			nVarchar(500),
	@LicenceRequired	Bit,
	@Sequence			Int,
	@ColourCode			nVarchar(20),
	@IsActive			Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Skill WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Skill))) = LTrim(RTrim(Upper(@SkillCode)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_Skill
		(Skill, SkillDesc, LicenceRequired, Seq, ColorCode, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@SkillCode, @SkillDesc, @LicenceRequired, @Sequence, @ColourCode, @IsActive, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prD_SkillOUDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillOUDel]    Script Date: 20/6/2018 10:23:42 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillOUDel]    
(
	@SkillId			BigInt,
	@OUId				BigInt
)
AS
DECLARE @SkillOUId BigInt = 0;
BEGIN

	SELECT	@SkillOUId = IsNull(SkillOUId,0)
	FROM	D_SkillOU WITH (NOLOCK)
	WHERE	SkillId =	@SkillId
	AND		OUId	=	@OUId

	If (@SkillOUId > 0)
	BEGIN
		DELETE FROM D_SkillOU
		WHERE	SkillOUId	= @SkillOUId

		SELECT 1;
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END

GO





/****** Object:  StoredProcedure [dbo].[prD_SkillOUIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillOUIns]    Script Date: 20/6/2018 10:22:26 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillOUIns]    
(
	@SkillId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @SkillOUId BigInt = 0;
BEGIN

	SELECT	@SkillOUId = IsNull(SkillOUId,0)
	FROM	D_SkillOU WITH (NOLOCK)
	WHERE	SkillId =	@SkillId
	AND		OUId	=	@OUId

	If (@SkillOUId = 0)
	BEGIN
		INSERT INTO D_SkillOU
		(SkillId, OUId, CreatedBy, CreatedDate)
		VALUES(@SkillId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END


GO


/****** Object:  StoredProcedure [dbo].[prD_SkillOUSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillOUSel]    Script Date: 20/6/2018 10:22:06 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillOUSel]    
(
	@SkillId	BigInt
)
AS
BEGIN
	SELECT	D_SkillOU.SkillOUId,
			D_Skill.SkillId,
			D_SkillOU.OUId,
			D_SkillOU.CreatedBy, 
			D_SkillOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	D_SkillOU WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_SkillOU.SkillId = D_Skill.SkillId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = D_SkillOU.OUId  
			WHERE	D_SkillOU.SkillId		=	@SkillId 
END

GO
/****** Object:  StoredProcedure [dbo].[prD_SkillSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillSel]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillSel]    Script Date: 20/6/2018 7:07:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prD_SkillSel]    
(
	@SkillID			BigInt,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	D_Skill.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.SkillDesc SkillDescription,
			D_Skill.LicenceRequired,
			D_Skill.Seq Sequence,
			D_Skill.ColorCode ColourCode,
			D_Skill.ActiveStatus, 
			D_Skill.CreatedBy, 
			D_Skill.CreatedDate,
			D_Skill.UpdatedBy,
			D_Skill.UpdatedDate
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK)  ON D_Skill.SkillId = D_SkillOU.SkillId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON D_SkillOU.OUId = C_OrganizationNode.OUId
	WHERE	(D_Skill.SkillId = @SkillID OR @SkillID = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
	ORDER BY D_SKILL.Skill
END

GO
/****** Object:  StoredProcedure [dbo].[prD_SkillUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SkillUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SkillUpd]
GO

/****** Object:  StoredProcedure [dbo].[prD_SkillUpd]    Script Date: 20/6/2018 10:08:38 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_SkillUpd]    
(
	@SkillId			BigInt,
	@SkillCode			nVarchar(50),
	@SkillDesc			nVarchar(500),
	@LicenceRequired	Bit,
	@Sequence			Int,
	@ColourCode			nVarchar(20),
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Skill WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Skill))) = LTrim(RTrim(Upper(@SkillCode)))
	AND		SkillId != @SkillId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_Skill
				SET		Skill		=	@SkillCode, 
				SkillDesc			=	@SkillDesc, 
				LicenceRequired		=	@LicenceRequired, 
				Seq					=	@Sequence,
				ColorCode			=	@ColourCode, 
				ActiveStatus		=	@IsActive, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	SkillId				=	@SkillId
					
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SystemParametersDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SystemParametersDel]
GO

CReate PROCEDURE [dbo].[prD_SystemParametersDel]    
(
	@ParamId	BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	D_SystemParams
	SET		ActiveStatus	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	ParamId		=	@ParamId

	SELECT 1
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SystemParametersIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SystemParametersIns]
GO
 

Create PROCEDURE [dbo].[prD_SystemParametersIns]    
(
	@ParamName		nVarchar(500),
	@ParamValue		nVarchar(4000),
	@ParamDesc		nvarchar(max),
	@ActiveStatus		Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_SystemParams WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ParamValue))) = LTrim(RTrim(Upper(@ParamValue)))
	AND		LTrim(RTrim(Upper(ParamName))) = LTrim(RTrim(Upper(@ParamName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO D_SystemParams
		(ParamName, ParamValue, ParamDesc,ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@ParamName, @ParamValue, @ParamDesc, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SystemParametersSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SystemParametersSel]
GO

Create PROCEDURE [dbo].[prD_SystemParametersSel]    
(
	@ParamId	 BigInt
)
AS
BEGIN	 
	SELECT	ParamId,
			ParamName,
			 ParamValue,
			 ParamDesc,
			 ActiveStatus,
			 CreatedBy,
			 CreatedDate,
			 UpdatedBy,
			 UpdatedDate
	FROM	D_SystemParams 	WITH (NOLOCK)
		 
	WHERE	(ParamId = @ParamId OR @ParamId = 0)
	Order By D_SystemParams.ParamName
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_SystemParametersUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_SystemParametersUpd]
GO
 
Create PROCEDURE [dbo].[prD_SystemParametersUpd]    
(
	@ParamId				BigInt,
	@ParamName		nVarchar(500),
	@ParamValue		nVarchar(4000),
	@ParamDesc		nvarchar(max),
	@ActiveStatus		Bit,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_SystemParams WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ParamValue))) = LTrim(RTrim(Upper(@ParamValue)))
	AND		LTrim(RTrim(Upper(ParamName))) = LTrim(RTrim(Upper(@ParamName)))
	AND		ParamId	!=	@ParamId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_SystemParams
		SET		ParamName		=	@ParamName, 
				ParamValue		=	@ParamValue, 
				ParamDesc		=	@ParamDesc, 
				ActiveStatus	=	@ActiveStatus, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	ParamId			=	@ParamId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_THPPeriodsSel')
	DROP PROC prD_THPPeriodsSel
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_ShiftAuditSel
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prD_THPPeriodsSel] (
	  @EmployeeID      bigInt

)
AS
BEGIN
    Select  
	           S_THPSettings.THPSettingsName,
			   S_THPEmployeePeriods.PeriodStart,
			   S_THPEmployeePeriods.PeriodEnd,
			   C_Employee.EmployeeNumber,
		       C_OrganizationNode.OUName
   FROM   S_THPEmployeePeriods
   LEFT OUTER JOIN S_THPSettings ON S_THPSettings.THPSettingId= S_THPEmployeePeriods.THPSettingsId
   LEFT OUTER  JOIN C_Employee WITH (NOLOCK) ON S_THPEmployeePeriods.EmployeeId = C_Employee.EmployeeId
   LEFT OUTER JOIN C_OrganizationNode ON C_OrganizationNode.OUId = S_THPEmployeePeriods.OUId
   WHERE    (S_THPEmployeePeriods.EmployeeId	= @EmployeeId OR @EmployeeId = 0) 
   
END				
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_UpdatePublicHolidayStatus')
	DROP PROC prD_UpdatePublicHolidayStatus
GO

----------------------------------------------------------------------------
-- Update Public holiday Process Status By Public Holiday Id
----------------------------------------------------------------------------
CREATE PROC prD_UpdatePublicHolidayStatus
	@PublicHolidayId		BigInt,
	@UpdateType				Int,
	@UpdatedBy				nVarchar(50)
AS	
	If (@UpdateType = 1)
	BEGIN
		UPDATE	D_PublicHolidays
		SET		IsLeaveProcess	=	1,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	PublicHolidayId	=	@PublicHolidayId
	END
	Else If (@UpdateType = 2)
	BEGIN
		UPDATE	D_PublicHolidays
		SET		IsShiftProcess	=	1,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	PublicHolidayId	=	@PublicHolidayId
	END

	SELECT 1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_UpdateRamadanPeriod')
	DROP PROC prD_UpdateRamadanPeriod
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_UpdateRamadanPeriod
----------------------------------------------------------------------------
CREATE PROC prD_UpdateRamadanPeriod
	@RamadanPeriodId		BigInt,
	@RamadanYear			Int,
	@PeriodStart			DateTime,
	@PeriodEnd				DateTime,
	@Description			nVarchar(50),
	@DailyOverTimeHours		Decimal(18,2),
	@WeeklyOverTimeHours	Decimal(18,2),
	@UpdatedBy				nVarchar(50)
AS

UPDATE D_RamadanPeriod
SET		RamadanYear			=	@RamadanYear, 
		PeriodStart			=	@PeriodStart, 
		PeriodEnd			=	@PeriodEnd, 
		Description			=	@Description, 
		DailyOverTimeHours	=	@DailyOverTimeHours, 
		WeeklyOverTimeHours	=	@WeeklyOverTimeHours, 
		UpdatedBy			=	@UpdatedBy,
		UpdatedDate			=	GETDATE()
WHERE	RamadanPeriodId		=	@RamadanPeriodId

SELECT  1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_UpdateRamadanPeriodEmployeeList')
	DROP PROC prD_UpdateRamadanPeriodEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_UpdateRamadanPeriodEmployeeList
----------------------------------------------------------------------------
CREATE PROC prD_UpdateRamadanPeriodEmployeeList
	@TranId					BigInt,
	@RamadanPeriodId		BigInt,
	@EmployeeId				BigInt,
	@TypeId					Int,
	@TypeDescription		nVarchar(500),
	@UpdatedBy				nVarchar(50)
AS

UPDATE	D_RamadanPeriodEmployeeList
SET		RamadanPeriodId		=	@RamadanPeriodId, 
		EmployeeId			=	@EmployeeId, 
		TypeId				=	@TypeId, 
		TypeDescription		=	@TypeDescription, 
		UpdatedBy			=	@UpdatedBy,
		UpdatedDate			=	GETDATE()
WHERE	TranId				=	@TranId

SELECT 1

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EqipmentMatrix_ScheduleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleIns]    
(	 
	@MatrixId		    Bigint, 
	@ScheduledValue		 bigint,
	@CreatedBy		nVarchar(50) 
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0
	DECLARE @MatrixScheduleId Bigint = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EqipmentMatrix_Schedule WITH (NOLOCK)
	WHERE	MatrixId=@MatrixId and ScheduledValue=@ScheduledValue

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EqipmentMatrix_Schedule
		(MatrixId,ScheduledValue,CreatedBy, CreatedDate)
		VALUES(@MatrixId,@ScheduledValue,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
	SELECT	@MatrixScheduleId =  MatrixScheduleId
	FROM	E_EqipmentMatrix_Schedule WITH (NOLOCK)
	WHERE	MatrixId=@MatrixId and ScheduledValue=@ScheduledValue

	UPDATE	E_EqipmentMatrix_Schedule
		SET		MatrixId			=	@MatrixId, 
				ScheduledValue		=	@ScheduledValue, 				 
				UpdatedBy		=	@CreatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	MatrixScheduleId		=	@MatrixScheduleId
		--SET @ValidateDuplicate = -1;
		SELECT @MatrixScheduleId;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EqipmentMatrix_ScheduleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleSel]    
(
	@MatrixId			Numeric(18,0)
)
AS
BEGIN
	SELECT	E_EqipmentMatrix_Schedule.MatrixId,
			E_EqipmentMatrix_Schedule.MatrixScheduleId,
			E_EqipmentMatrix_Schedule.ScheduledValue ,		 
			E_EqipmentMatrix_Schedule.CreatedBy, 
			E_EqipmentMatrix_Schedule.CreatedDate,
			E_EqipmentMatrix_Schedule.UpdatedBy,
			E_EqipmentMatrix_Schedule.UpdatedDate
	FROM	E_EqipmentMatrix_Schedule WITH (NOLOCK) 			 
	WHERE	(E_EqipmentMatrix_Schedule.MatrixId = @MatrixId OR @MatrixId = 0)
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EqipmentMatrix_ScheduleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prE_EqipmentMatrix_ScheduleUpd]    
(
	@MatrixScheduleId		BigInt,
	@MatrixId		    Bigint, 
	@ScheduledValue		 bigint,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EqipmentMatrix_Schedule WITH (NOLOCK)
	WHERE	MatrixId=@MatrixId
	AND		MatrixScheduleId	!=	@MatrixScheduleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EqipmentMatrix_Schedule
		SET		MatrixId			=	@MatrixId, 
				ScheduledValue		=	@ScheduledValue, 				 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	MatrixScheduleId		=	@MatrixScheduleId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrixDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrixDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prE_EquipmentMatrixDel]
(
	@MatrixId		BigInt 
)
AS
BEGIN
   DELETE FROM E_EqipmentMatrix_Schedule WHERE MatrixId=@MatrixId

   DELETE FROM E_EquipmentMatrix_EquipmentType WHERE MatrixId=@MatrixId

   DELETE FROM 	E_EquipmentMatrix WHERE	MatrixId	=	@MatrixId



	SELECT 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrixIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrixIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prE_EquipmentMatrixIns]    
(	
	@TemplateName			nVarchar(500),
	@OUId			Bigint, 
	@MatrixEQTypeId bigint,
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentMatrix WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName))) = LTrim(RTrim(Upper(@TemplateName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EquipmentMatrix
		(TemplateName, OUId,MatrixEQTypeId,CreatedBy, CreatedDate)
		VALUES(@TemplateName, @OUId,@MatrixEQTypeId,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrixSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrixSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prE_EquipmentMatrixSel]    
(
	@MatrixId			Numeric(18,0),
	@OUID				BigInt
)
AS
BEGIN
	SELECT	E_EquipmentMatrix.MatrixId,
			E_EquipmentMatrix.OUId,
			E_EquipmentMatrix.MatrixEQTypeId ,
			E_EquipmentMatrix.TemplateName,		 
			E_EquipmentMatrix.CreatedBy, 
			E_EquipmentMatrix.CreatedDate,
			E_EquipmentMatrix.UpdatedBy,
			E_EquipmentMatrix.UpdatedDate
	FROM	E_EquipmentMatrix WITH (NOLOCK) 			 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON E_EquipmentMatrix.OUId = C_OrganizationNode.OUId
	WHERE	(E_EquipmentMatrix.MatrixId = @MatrixId OR @MatrixId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrixUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrixUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prE_EquipmentMatrixUpd]    
(	 
	@MatrixId		    Bigint, 
	@TemplateName		 nvarchar(500),
	@OUId			bigint,
	@MatrixEQTypeId	bigint,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentMatrix WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName))) = LTrim(RTrim(Upper(@TemplateName)))
	AND		MatrixId	!=	@MatrixId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EquipmentMatrix
		SET		TemplateName			=	@TemplateName, 
				OUId		=	@OUId, 	
				MatrixEQTypeId =@MatrixEQTypeId,			 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	MatrixId		=	@MatrixId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrix_EquipmentTypeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeIns]    
(	 
	@MatrixId		    Bigint, 
	@MatrixScheduleId		 bigint,
	@EquipmentTypeId		bigint,
	@EquipmentTypeValue  int,
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0
	DECLARE @MatrixEquipmentTypeId Bigint = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentMatrix_EquipmentType WITH (NOLOCK)
	WHERE	MatrixId=@MatrixId and MatrixScheduleId=@MatrixScheduleId
	and EquipmentTypeId=@EquipmentTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EquipmentMatrix_EquipmentType
		(MatrixId,MatrixScheduleId,EquipmentTypeId,EquipmentTypeValue,CreatedBy, CreatedDate)
		VALUES(@MatrixId,@MatrixScheduleId,@EquipmentTypeId,@EquipmentTypeValue,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
	SELECT	@MatrixEquipmentTypeId = MatrixEquipmentTypeId
	FROM	E_EquipmentMatrix_EquipmentType WITH (NOLOCK)
	WHERE	MatrixId=@MatrixId and MatrixScheduleId=@MatrixScheduleId
	and EquipmentTypeId=@EquipmentTypeId

	UPDATE	E_EquipmentMatrix_EquipmentType
		SET		MatrixId			=	@MatrixId, 
				MatrixScheduleId	=	@MatrixScheduleId, 	
				EquipmentTypeId	    =   @EquipmentTypeId,	
				EquipmentTypeValue  =	@EquipmentTypeValue,		 
				UpdatedBy			=	@CreatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	MatrixEquipmentTypeId		=	@MatrixEquipmentTypeId
		--SET @ValidateDuplicate = -1;
		SELECT @MatrixEquipmentTypeId;
	END
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrix_EquipmentTypeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeSel]    
(
	@MatrixId			Numeric(18,0)
	 
)
AS
BEGIN
	SELECT	E_EquipmentMatrix_EquipmentType.MatrixId,
			E_EquipmentMatrix_EquipmentType.MatrixEquipmentTypeId,
			E_EquipmentMatrix_EquipmentType.MatrixScheduleId ,
			E_EquipmentMatrix_EquipmentType.EquipmentTypeId,	
			E_EquipmentMatrix_EquipmentType.EquipmentTypeValue,		 
			E_EquipmentMatrix_EquipmentType.CreatedBy, 
			E_EquipmentMatrix_EquipmentType.CreatedDate,
			E_EquipmentMatrix_EquipmentType.UpdatedBy,
			E_EquipmentMatrix_EquipmentType.UpdatedDate,
			M_EquipmentType.EquipmentType
	FROM	E_EquipmentMatrix_EquipmentType WITH (NOLOCK)
	 		LEFT OUTER JOIN 	M_EquipmentType  WITH (NOLOCK) on M_EquipmentType.EquipmentTypeId=E_EquipmentMatrix_EquipmentType.EquipmentTypeId 	 
	WHERE	(E_EquipmentMatrix_EquipmentType.MatrixId = @MatrixId)
	ORDER BY M_EquipmentType.EquipmentType
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentMatrix_EquipmentTypeUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[prE_EquipmentMatrix_EquipmentTypeUpd]    
(
	@MatrixEquipmentTypeId bigint,	 
	@MatrixId		    Bigint, 
	@MatrixScheduleId		 bigint,
	@EquipmentTypeId		bigint,
	@EquipmentTypeValue  int,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentMatrix_EquipmentType WITH (NOLOCK)
	WHERE MatrixId=@MatrixId and MatrixScheduleId=@MatrixScheduleId
	and EquipmentTypeId=@EquipmentTypeId
	AND		MatrixEquipmentTypeId	!=	@MatrixEquipmentTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EquipmentMatrix_EquipmentType
		SET		MatrixId			=	@MatrixId, 
				MatrixScheduleId	=	@MatrixScheduleId, 	
				EquipmentTypeId	    =   @EquipmentTypeId,	
				EquipmentTypeValue  =	@EquipmentTypeValue,		 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	MatrixEquipmentTypeId		=	@MatrixEquipmentTypeId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_DetDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
Create PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetDel]
(
	@MatrixEQTypeId		BigInt,
	@EquipmentTypeId	BigInt
)
AS
BEGIN
	Update E_EquipmentType_Matrix_Template  set ActiveStatus =0 where MatrixEQTypeId =@MatrixEQTypeId 
	SELECT 1
END 

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_DetIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetIns]    
(
	@MatrixEQTypeId		bigint,
	@EquipmentTypeId				BigInt,	 
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate BigInt = 0;
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentType_Matrix_Det WITH (NOLOCK)
	WHERE	MatrixEQTypeId=@MatrixEQTypeId and EquipmentTypeId=@EquipmentTypeId
	 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EquipmentType_Matrix_Det
		(MatrixEQTypeId, EquipmentTypeId, CreatedBy, CreatedDate)
		VALUES(@MatrixEQTypeId, @EquipmentTypeId,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_DetSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetSel]    
(
	@MatrixEQTypeId	BigInt
)
AS
BEGIN
	SELECT	E_EquipmentType_Matrix_Det.MatrixEQTypeId,
			E_EquipmentType_Matrix_Det.MatrixEQTypeDetId,
			E_EquipmentType_Matrix_Det.EquipmentTypeId,		 
			E_EquipmentType_Matrix_Det.CreatedBy, 
			E_EquipmentType_Matrix_Det.CreatedDate,			 
			M_EquipmentType.EquipmentType,
			E_EquipmentType_Matrix_Template.TemplateName
	FROM	E_EquipmentType_Matrix_Det WITH (NOLOCK)			 
			INNER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId=E_EquipmentType_Matrix_Det.EquipmentTypeId
			INNER JOIN E_EquipmentType_Matrix_Template WITH (NOLOCK) ON E_EquipmentType_Matrix_Template.MatrixEQTypeId=E_EquipmentType_Matrix_Det.MatrixEQTypeId
			WHERE	E_EquipmentType_Matrix_Det.MatrixEQTypeId		=	@MatrixEQTypeId 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_DetUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prE_EquipmentType_Matrix_DetUpd]    
(
	@MatrixEQTypeDetId  bigint,
	@MatrixEQTypeId		BigInt,
	@EquipmentTypeId		bigint,	 
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentType_Matrix_Det WITH (NOLOCK)
	WHERE	EquipmentTypeId = @EquipmentTypeId and MatrixEQTypeId=@MatrixEQTypeId
	AND		MatrixEQTypeDetId	!=	@MatrixEQTypeDetId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EquipmentType_Matrix_Det
		SET		MatrixEQTypeId			=	@MatrixEQTypeId, 
				EquipmentTypeId		=	@EquipmentTypeId,				  
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	MatrixEQTypeDetId		=	@MatrixEQTypeDetId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END


GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_TemplateIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

Create PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateIns]    
(
	@TemplateName		nvarchar(500),
	@OUId				BigInt,
	@ActiveStatus		int,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate BigInt = 0;
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentType_Matrix_Template WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName))) = LTrim(RTrim(Upper(@TemplateName)))
	 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EquipmentType_Matrix_Template
		(TemplateName, OUId,ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@TemplateName, @OUId, @ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_TemplateSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateSel]    
(
	@MatrixEQTypeId	BigInt,
	@OUId BigInt
)
AS
BEGIN
	SELECT	E_EquipmentType_Matrix_Template.MatrixEQTypeId,
			E_EquipmentType_Matrix_Template.TemplateName,
			E_EquipmentType_Matrix_Template.ActiveStatus,
			E_EquipmentType_Matrix_Template.OUId,
			E_EquipmentType_Matrix_Template.CreatedBy, 
			E_EquipmentType_Matrix_Template.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	E_EquipmentType_Matrix_Template WITH (NOLOCK)			 
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = E_EquipmentType_Matrix_Template.OUId  
			WHERE	(E_EquipmentType_Matrix_Template.MatrixEQTypeId		=	@MatrixEQTypeId or @MatrixEQTypeId=0)
			AND		(OrgNode.OUId = @OUID)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prE_EquipmentType_Matrix_TemplateUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[prE_EquipmentType_Matrix_TemplateUpd]    
(
	@MatrixEQTypeId		BigInt,
	@TemplateName		nVarchar(500),
	@OUId   Bigint,
	@ActiveStatus int,
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EquipmentType_Matrix_Template WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName))) = LTrim(RTrim(Upper(@TemplateName)))
	AND		MatrixEQTypeId	!=	@MatrixEQTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EquipmentType_Matrix_Template
		SET		TemplateName			=	@TemplateName, 
				OUId		=	@OUId,
				ActiveStatus =@ActiveStatus,  
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()				
		WHERE	MatrixEQTypeId		=	@MatrixEQTypeId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prI_AddBoxMomentSummary')
	DROP PROCEDURE prI_AddBoxMomentSummary
GO

CREATE PROC prI_AddBoxMomentSummary
(
	@Date			DateTime,
	@ShiftBandId	BigInt,
	@CMPHTarget		Decimal(18,2),
	@CMPHActual		Decimal(18,2),
	@PMPHTarget		Decimal(18,2),
	@PMPHActual		Decimal(18,2),
	@MovesTarget	Decimal(18,2),
	@MovesActual	Decimal(18,2),
	@ActualGang		Decimal(18,2),
	@ColumnA		Decimal(18,2),
	@ColumnB		Decimal(18,2),
	@ColumnC		Decimal(18,2),
	@ColumnD		Decimal(18,2),
	@CreatedBy		nVarchar(50)
)
AS
	DECLARE @BoxMovementId BigInt = 0
	
	SELECT	@BoxMovementId = IsNull(BoxMovementId, 0) 
	FROM	I_BoxMovementSummary
	WHERE	ShiftBandId			=	@ShiftBandId
	AND		Convert(Date,Date)	=	Convert(Date,@Date)

	If (@BoxMovementId = 0)
	BEGIN
		INSERT INTO I_BoxMovementSummary
		(Date, ShiftBandId, CMPHTarget, CMPHActual, PMPHTarget, PMPHActual, MovesTarget, MovesActual, ActualGang, ColumnA, ColumnB, 
		 ColumnC, ColumnD, CreatedBy, CreatedDate)
		VALUES(@Date, @ShiftBandId, @CMPHTarget, @CMPHActual, @PMPHTarget, @PMPHActual, @MovesTarget, @MovesActual, @ActualGang,
			   @ColumnA, @ColumnB, @ColumnC, @ColumnD, @CreatedBy, GETDATE())		
	
		SELECT  CAST(@@Identity AS INTEGER) 
	END
	ELSE
	BEGIN
		UPDATE	I_BoxMovementSummary
		SET		Date				=	@Date,
				ShiftBandId			=	@ShiftBandId,
				CMPHTarget			=	@CMPHTarget,
				CMPHActual			=	@CMPHActual,
				PMPHTarget			=	@PMPHTarget,
				PMPHActual			=	@PMPHActual,
				MovesTarget			=	@MovesTarget,
				MovesActual			=	@MovesActual,
				ActualGang			=	@ActualGang,
				ColumnA				=	@ColumnA,
				ColumnB				=	@ColumnB,
				ColumnC				=	@ColumnC,
				ColumnD				=	@ColumnD,
				UpdatedBy			=	@CreatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	BoxMovementId		=	@BoxMovementId

		SELECT 1
	END
GO


/****** Object:  StoredProcedure [dbo].[prI_GetBoxMovementSummary]    Script Date: 18-08-2020 14:39:28 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prI_GetBoxMovementSummary]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prI_GetBoxMovementSummary]
GO
/****** Object:  StoredProcedure [dbo].[prI_GetBoxMovementSummary]    Script Date: 18-08-2020 14:39:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

----------------------------------------------------------------------------
-- Insert a single record into prI_GetBoxMovementSummary
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prI_GetBoxMovementSummary] 
(                
	            @ShiftBands  nVarchar(max),
				@StartDate   Datetime,
				@EndDate    Datetime	
)
AS

DECLARE         @__shiftBandsId INT = 0

BEGIN

SELECT TOP 1    @__shiftBandsId = sID FROM fnStringToTable(@ShiftBands)	

SELECT                     
                I_BoxMovementSummary.Date,
			    D_ShiftBand.ShiftBandName ShiftBand,	            
				I_BoxMovementSummary.CMPHTarget ,
				I_BoxMovementSummary.CMPHActual ,
				I_BoxMovementSummary.PMPHTarget,
				I_BoxMovementSummary.PMPHActual,
				I_BoxMovementSummary.MovesTarget,
				I_BoxMovementSummary.MovesActual,
				I_BoxMovementSummary.ActualGang,
	            I_BoxMovementSummary.CreatedBy,
				I_BoxMovementSummary.CreatedDate,
				I_BoxMovementSummary.UpdatedBy,
				I_BoxMovementSummary.UpdatedDate
				
FROM            I_BoxMovementSummary  WITH (NOLOCK) 
                INNER JOIN D_Shiftband WITH (NOLOCK)  ON I_BoxMovementSummary.ShiftBandId = D_Shiftband.ShiftBandId				

WHERE          
                (D_ShiftBand.ShiftBandId IN (SELECT * FROM fnStringToTable( @ShiftBands)) OR @__shiftBandsId= 0)
                AND		CONVERT(DATE,I_BoxMovementSummary.Date)>=CONVERT(DATE,@StartDate )
				AND		CONVERT(DATE,I_BoxMovementSummary.Date)<=CONVERT(DATE,@EndDate)					
END		              
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddActivity')
	DROP PROC prJ_AddActivity
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_AddActivity]
	@OUId bigint = NULL,
	@SkillId bigint = NULL,
	@ShiftBandId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@WorkType int = NULL,
	@ScheduleId bigint = NULL,
	@AttributeId int,
	@ShiftId bigint = NULL,
	@RuleId bigint = NULL,
	@GroupNo int = NULL,
	@AllocationNo int = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@ProgressionState Int = 0,
	@WorkloadId			BigInt = 0
AS
Declare @ActivityId bigint

If (@AllocationNo = 0) 
BEGIN
	SELECT	@AllocationNo = (MAX(IsNull(AllocationNo,0))  + 1)
	FROM	J_Activity WITH (NOLOCK)
	WHERE 	J_Activity.OUId=@OUId
	AND 	(EndTime >= CONVERT(DATETIME, @StartTime)
	AND 	StartTime < CONVERT(DATETIME, @EndTime))

	If (@AllocationNo = NULL) SET @AllocationNo = 1
END

INSERT J_Activity(OUId, SkillId, ShiftBandId,StartTime, EndTime, WorkType,   ShiftId, RuleId, GroupNo, AllocationNo, CreatedBy, CreatedDate, ProgresstionState, WorkloadId)
VALUES (@OUId, @SkillId, @ShiftBandId,@StartTime, @EndTime, COALESCE(@WorkType, (0)),   @ShiftId, @RuleId,@GroupNo, IsNull(@AllocationNo,1), @CreatedBy, GETDATE(), @ProgressionState, @WorkloadId)

select  @ActivityId=CAST(@@Identity AS INTEGER) 


insert into J_ActivityAttributes(ActivityId,AttributeId,ScheduleId,CreatedBy,CreatedDate)
values (@ActivityId,@AttributeId,@ScheduleId,@CreatedBy,GETDATE())

select @ActivityId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddAllocationRule')
	DROP PROC prJ_AddAllocationRule
GO

----------------------------------------------------------------------------
-- Insert a single record into J_AllocationRule
----------------------------------------------------------------------------
CREATE PROC prJ_AddAllocationRule
	@OUId bigint = NULL,
	@RuleName nvarchar(1000) = NULL,
	@RuleDesc text = NULL,
	@ActiveStatus bit = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT J_AllocationRule(OUId, RuleName, RuleDesc, ActiveStatus, CreatedBy, CreatedDate)
VALUES (@OUId, @RuleName, @RuleDesc, @ActiveStatus, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddBroadcastDeployment')
	DROP PROC prJ_AddBroadcastDeployment
GO

----------------------------------------------------------------------------
-- Insert a single record into prJ_AddBroadcastDeployment
----------------------------------------------------------------------------
CREATE PROC prJ_AddBroadcastDeployment
	@OUId				BigInt,
	@BroadcastDate		DateTime,
	@ShiftBandId		BigInt,
	@StartTime			DateTime,
	@EndTime			DateTime,
	@EmployeeId			BigInt,
	@ShiftId			BigInt,
	@Sequence			Int,
	@CreatedBy			nVarchar(50)
AS
BEGIN
	INSERT INTO J_BroadcastDeployment
	(OUId, BroadcastDate, ShiftBandId, StartTime, EndTime, EmployeeId, ShiftId, Sequence, CreatedBy, CreatedDate)
	VALUES(@OUId, @BroadcastDate, @ShiftBandId, @StartTime, @EndTime, @EmployeeId, @ShiftId, @Sequence, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS INTEGER)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddPlanningEquipmentRequirements')
	DROP PROC prJ_AddPlanningEquipmentRequirements
GO

----------------------------------------------------------------------------
-- Insert Data Into prJ_AddPlanningEquipmentRequirements Table
----------------------------------------------------------------------------
create PROC prJ_AddPlanningEquipmentRequirements 
(
	@OUId				BigInt,
	@ShiftBandId		BigInt,
	@ShiftDate			DateTime,
	@ShiftStartTime		DateTime,
	@ShiftEndTime		DateTime,
	@CreatedBy			nVarchar(50)
)	with ENCRYPTION
AS
BEGIN
	DELETE FROM J_PlanningEquipmentRequirements 
	WHERE	Convert(Date,RequirementDate) = Convert(Date,@ShiftDate) 
	AND		ShiftBandId =	@ShiftBandId
	AND		OUId		=	@OUId

	INSERT INTO J_PlanningEquipmentRequirements
	(OUId, EquipmentTypeId, ShiftBandId, RequirementDate, ShiftStartTime, ShiftEndTime, RequirementCount, DeployedCount, CreatedBy, CreatedDate)
	SELECT	@OUId, 0 EquipmentTypeId, @ShiftBandId, @ShiftDate, @ShiftStartTime, @ShiftEndTime, Count(CraneId), 0, @CreatedBy, GETDATE()
	FROM	M_CraneSchedule WITH (NOLOCK)
	WHERE	Convert(DateTime,EndDate) > Convert(DateTime,@ShiftStartTime) 
	AND		Convert(DateTime,StartDate)	< Convert(DateTime,@ShiftEndTime)  
	AND		M_CraneSchedule.OUId = @OUId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddPlanningRequirements')
	DROP PROC prJ_AddPlanningRequirements
GO

----------------------------------------------------------------------------
-- Insert Data Into prJ_AddPlanningRequirements Table
----------------------------------------------------------------------------
CREATE PROC prJ_AddPlanningRequirements
(
	@OUId				BigInt,
	@ShiftBandId		BigInt,
	@ShiftDate			DateTime,
	@ShiftStartTime		DateTime,
	@ShiftEndTime		DateTime,
	@CreatedBy			nVarchar(50)
)	
AS
BEGIN
	DELETE FROM J_PlanningRequirements 
	WHERE	Convert(Date,RequirementDate) = Convert(Date,@ShiftDate) 
	AND		ShiftBandId =	@ShiftBandId
	AND		OUId		=	@OUId

	INSERT INTO J_PlanningRequirements
	(OUId, SkillId, ShiftBandId, RequirementDate, ShiftStartTime, ShiftEndTime, RequirementCount, DeployedCount, CreatedBy, CreatedDate)
	SELECT	@OUId, J_Activity.SkillId, @ShiftBandId, @ShiftDate, @ShiftStartTime, @ShiftEndTime, Count(Distinct AllocationNo), 0, @CreatedBy, GETDATE()
	FROM	J_Activity WITH (NOLOCK)
	WHERE	Convert(DateTime,StartTime) >= Convert(DateTime,@ShiftStartTime) 
	AND		Convert(DateTime,EndTime)	<= Convert(DateTime,@ShiftEndTime)  
	AND		ShiftBandId = @ShiftBandId
	GROUP BY J_Activity.SkillId

	SELECT CAST(@@Identity AS BigInt)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_AddWorkload')
	DROP PROC prJ_AddWorkload
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_AddWorkload
	@OUId bigint = NULL,
	@SkillId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@WorkType int = NULL,
	@CraneScheduleId bigint = NULL,
	@EquipmentScheduleId bigint = NULL,
	@VesselScheduleId	BigInt = NULL,
	@ShiftBandId bigint = NULL,
	@ScheduleId bigint = NULL,
	@Imported bit = NULL,
	@WorkloadGenerated bit = NULL,
	@SignOffStatus bit = NULL,
	@CreatedDate datetime = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdatedDate datetime = NULL
AS

INSERT J_Workload(OUId, SkillId, StartTime, EndTime, WorkType, CraneScheduleId, EquipmentScheduleId, VesselScheduleId, ShiftBandId, ScheduleId, Imported, WorkloadGenerated, SignOffStatus, CreatedDate, CreatedBy, UpdatedBy, UpdatedDate)
VALUES (@OUId, @SkillId, @StartTime, @EndTime, COALESCE(@WorkType, (0)), @CraneScheduleId, @EquipmentScheduleId, @VesselScheduleId, @ShiftBandId, @ScheduleId, @Imported, @WorkloadGenerated, @SignOffStatus, @CreatedDate, @CreatedBy, @UpdatedBy, @UpdatedDate)

select  CAST(@@Identity AS INTEGER) 

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationFactorSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationFactorSel]
GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationFactorSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationFactorSel]    
	@AllocationRuleId bigint
AS
BEGIN
if @AllocationRuleId >0 
begin
	SELECT	J_AllocationFactor.FactorId,
			J_AllocationFactor.FactorName,
			J_AllocationRuleFactor.FactorValue,
			J_AllocationFactor.ActiveStatus,
			J_AllocationFactor.CreatedBy,
			J_AllocationFactor.CreatedDate
	FROM	J_AllocationRuleFactor WITH (NOLOCK)
	inner join J_AllocationFactor WITH (NOLOCK) on J_AllocationFactor.FactorId = J_AllocationRuleFactor.FactorId
	where J_AllocationRuleFactor.AllocationRuleId=@AllocationRuleId
	ORDER BY J_AllocationFactor.FactorName
end
else
begin
	SELECT	J_AllocationFactor.FactorId,
			J_AllocationFactor.FactorName,
			J_AllocationFactor.FactorValue,
			J_AllocationFactor.ActiveStatus,
			J_AllocationFactor.CreatedBy,
			J_AllocationFactor.CreatedDate
	FROM	J_AllocationFactor	WITH (NOLOCK)
	ORDER BY J_AllocationFactor.FactorName
end 
END


GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleDel]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleDel]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleDel]    
(
	@AllocationRuleId	BigInt,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	
	UPDATE	J_AllocationRule
	SET		ActiveStatus		=	@ActiveStatus, 
			UpdatedBy			=	@UpdatedBy
	WHERE	AllocationRuleId	=	@AllocationRuleId

	SELECT 1

END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleEmpBasisDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisDel]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisDel]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisDel]    
(
	@AllocationRuleEmpBasisId	BigInt
)
AS
BEGIN
	
	DELETE FROM J_AllocationRuleEmploymentBasis
	WHERE	AllocationRuleEmployeementBasisId	=	@AllocationRuleEmpBasisId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleEmpBasisIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisIns]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisIns]    
(
	@AllocationRuleId	BigInt,
	@EmploymentBasisId	BigInt,
	@PrioritySeq		BigInt,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	
	INSERT INTO J_AllocationRuleEmploymentBasis
	(AllocationRuleId, EmploymentBasisId, PrioritySeq, CreatedBy, CreatedDate)
	VALUES(@AllocationRuleId, @EmploymentBasisId, @PrioritySeq, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleEmpBasisSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisSel]
GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisSel]    
(
	@AllocationRuleId	BigInt
)
AS
BEGIN
	SELECT	J_AllocationRuleEmploymentBasis.AllocationRuleEmployeementBasisId AllocationRuleEmploymentBasisId,
			J_AllocationRuleEmploymentBasis.AllocationRuleId,
			D_EmploymentBasis.EmploymentBasisCode,
			D_EmploymentBasis.EmploymentBasisDesc,
			J_AllocationRuleEmploymentBasis.EmploymentBasisId,
			J_AllocationRuleEmploymentBasis.PrioritySeq,
			J_AllocationRuleEmploymentBasis.CreatedBy,
			J_AllocationRuleEmploymentBasis.CreatedDate,
			J_AllocationRuleEmploymentBasis.UpdatedBy,
			J_AllocationRuleEmploymentBasis.UpdatedDate
	FROM	J_AllocationRuleEmploymentBasis WITH (NOLOCK)
			INNER JOIN J_AllocationRule WITH (NOLOCK) 
					ON J_AllocationRuleEmploymentBasis.AllocationRuleId = J_AllocationRule.AllocationRuleId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) 
					ON J_AllocationRuleEmploymentBasis.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
	WHERE	J_AllocationRuleEmploymentBasis.AllocationRuleId = @AllocationRuleId
END

GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleEmpBasisUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisUpd]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleEmpBasisUpd]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleEmpBasisUpd]    
(
	@AllocationRuleEmpBasisId	BigInt,
	@AllocationRuleId			BigInt,
	@EmploymentBasisId			BigInt,
	@PrioritySeq				BigInt,
	@UpdatedBy					nVarchar(50)
)
AS
BEGIN
	
	UPDATE	J_AllocationRuleEmploymentBasis
	SET		AllocationRuleId					=	@AllocationRuleId, 
			EmploymentBasisId					=	@EmploymentBasisId, 
			PrioritySeq							=	@PrioritySeq, 
			UpdatedBy							=	@UpdatedBy,
			UpdatedDate							=	GETDATE()
	WHERE	AllocationRuleEmployeementBasisId	=	@AllocationRuleEmpBasisId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleFactorDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleFactorDel]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorDel]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleFactorDel]    
(
	@RuleFactorId		BigInt
)
AS
BEGIN
	
	DELETE FROM J_AllocationRuleFactor
	WHERE	J_AllocationRuleFactor.RuleFactoryId = @RuleFactorId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleFactorIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleFactorIns]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleFactorIns]    
(
	@AllocationRuleId	BigInt,
	@FactorId			Int,
	@FactorValue		BigInt,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	
	INSERT INTO J_AllocationRuleFactor
	(AllocationRuleId, FactorId, FactorValue, CreatedBy, CreatedDate)
	VALUES(@AllocationRuleId, @FactorId, @FactorValue, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleFactorSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleFactorSel]
GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleFactorSel]    
(
	@RuleFactorId		BigInt,
	@AllocationRuleId	BigInt
)
AS
BEGIN
	SELECT	J_AllocationRuleFactor.RuleFactoryId RuleFactorId,
			J_AllocationRuleFactor.AllocationRuleId,
			J_AllocationRuleFactor.FactorId,
			J_AllocationFactor.FactorName,
			J_AllocationRuleFactor.FactorValue,
			J_AllocationRuleFactor.CreatedBy,
			J_AllocationRuleFactor.CreatedDate,
			J_AllocationRuleFactor.UpdatedBy,
			J_AllocationRuleFactor.UpdatedDate
	FROM	J_AllocationRuleFactor WITH (NOLOCK) 
			INNER JOIN J_AllocationFactor WITH (NOLOCK) ON J_AllocationRuleFactor.FactorId = J_AllocationFactor.FactorId
	WHERE	(J_AllocationRuleFactor.FactorId = @RuleFactorId OR @RuleFactorId = 0)
	AND		(J_AllocationRuleFactor.AllocationRuleId = @AllocationRuleId OR @AllocationRuleId = 0)
	AND		J_AllocationFactor.ActiveStatus = 1
	ORDER BY J_AllocationFactor.FactorName

END

GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleFactorUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleFactorUpd]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleFactorUpd]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleFactorUpd]    
(
	@RuleFactorId		BigInt,
	@AllocationRuleId	BigInt,
	@FactorId			Int,
	@FactorValue		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	
	UPDATE	J_AllocationRuleFactor
	SET		AllocationRuleId		=	@AllocationRuleId, 
			FactorId				=	@FactorId, 
			FactorValue				=	@FactorValue, 
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GETDATE()
	WHERE	RuleFactoryId			=	@RuleFactorId
	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleIns]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleIns]    
(
	@OuId			BigInt,
	@RuleName		nVarchar(500),
	@RuleDesc		text,
	@ActiveStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	J_AllocationRule WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RuleName))) = LTrim(RTrim(Upper(@RuleName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO J_AllocationRule
		(OUId, RuleName, RuleDesc, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OuId, @RuleName, @RuleDesc, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleSel]
GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleSel]    
(
	@AllocationRuleId	BigInt,
	@OuId				BigInt
)
AS
BEGIN
	SELECT	J_AllocationRule.AllocationRuleId,
			J_AllocationRule.RuleName,
			J_AllocationRule.RuleDesc,
			C_OrganizationNode.OUName,
			J_AllocationRule.OUId,
			J_AllocationRule.ActiveStatus,
			J_AllocationRule.CreatedBy,
			J_AllocationRule.CreatedDate,
			J_AllocationRule.UpdatedBy,
			J_AllocationRule.UpdatedDate
	FROM	J_AllocationRule WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON J_AllocationRule.OUId = C_OrganizationNode.OUId
	WHERE	(J_AllocationRule.AllocationRuleId = @AllocationRuleId OR @AllocationRuleId = 0)
	AND		J_AllocationRule.OUId = @OuId
END

GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityDel]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleSkillPriorityDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityDel]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityDel]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityDel]
(
	@AllocationRuleSkillId	BigInt
)
AS
BEGIN
	
	DELETE FROM J_AllocationRuleSkillPriority
	WHERE	AllocationRuleSkillId	=	@AllocationRuleSkillId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityIns]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleSkillPriorityIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityIns]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityIns]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityIns]    
(
	@AllocationRuleId	BigInt,
	@SkillId			BigInt,
	@PrioritySeq		Int,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	
	INSERT INTO J_AllocationRuleSkillPriority
	(AllocationRuleId, SkillId, PrioritySeq, CreatedBy, CreatedDate)
	VALUES(@AllocationRuleId, @SkillId, @PrioritySeq, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleSkillPrioritySel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleSkillPrioritySel]
GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPrioritySel]    Script Date: 6/29/2018 6:20:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleSkillPrioritySel]    
(
	@AllocationRuleId	BigInt
)
AS
BEGIN
	SELECT	J_AllocationRule.AllocationRuleId,
			J_AllocationRuleSkillPriority.AllocationRuleSkillId,
			J_AllocationRuleSkillPriority.SkillId,
			J_AllocationRuleSkillPriority.PrioritySeq,
			D_Skill.Skill SkillName,
			J_AllocationRuleSkillPriority.CreatedBy,
			J_AllocationRuleSkillPriority.CreatedDate,
			J_AllocationRuleSkillPriority.UpdatedBy,
			J_AllocationRuleSkillPriority.UpdatedDate
	FROM	J_AllocationRuleSkillPriority WITH (NOLOCK) 
			INNER JOIN J_AllocationRule WITH (NOLOCK) 
					ON J_AllocationRuleSkillPriority.AllocationRuleId = J_AllocationRule.AllocationRuleId
			INNER JOIN D_Skill WITH (NOLOCK) 
					ON J_AllocationRuleSkillPriority.SkillId = D_SKill.SkillId
	WHERE	J_AllocationRuleSkillPriority.AllocationRuleId = @AllocationRuleId
END

GO
/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleSkillPriorityUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityUpd]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleSkillPriorityUpd]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleSkillPriorityUpd]    
(
	@AllocationRuleSkillId		BigInt,
	@AllocationRuleId			BigInt,
	@SkillId					BigInt,
	@PrioritySeq				Int,
	@UpdatedBy					nVarchar(50)
)
AS
BEGIN
	
	UPDATE	J_AllocationRuleSkillPriority
	SET		AllocationRuleId		=	@AllocationRuleId, 
			SkillId					=	@SkillId, 
			PrioritySeq				=	@PrioritySeq, 
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GETDATE()
	WHERE	AllocationRuleSkillId	=	@AllocationRuleSkillId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleUpd]    Script Date: 6/22/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_AllocationRuleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_AllocationRuleUpd]
GO

/****** Object:  StoredProcedure [dbo].[prJ_AllocationRuleUpd]    Script Date: 6/22/2018 11:48:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_AllocationRuleUpd]    
(
	@AllocationRuleId	BigInt,
	@OuId				BigInt,
	@RuleName			nVarchar(500),
	@RuleDesc			text,
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	J_AllocationRule WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RuleName))) = LTrim(RTrim(Upper(@RuleName)))
	AND		AllocationRuleId != @AllocationRuleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	J_AllocationRule
		SET		OUId				=	@OuId, 
				RuleName			=	@RuleName, 
				RuleDesc			=	@RuleDesc, 
				ActiveStatus		=	@ActiveStatus, 
				UpdatedBy			=	@UpdatedBy
		WHERE	AllocationRuleId	=	@AllocationRuleId

		SELECT 1
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_CheckShiftAvilabilityForSelectedActivity')
	DROP PROC prJ_CheckShiftAvilabilityForSelectedActivity
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_CheckShiftAvilabilityForSelectedActivity
	@OUId bigint,
	@ShiftId bigint,	

	@StartTime DateTime,
	@EndTime DateTime
	

AS


select * from s_shifts WITH (NOLOCK)
inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId = s_shifts.ShiftId
where s_shifts.ShiftId=@ShiftId and s_shifts.OUId = @OUId
 and ( J_Activity.StartTime <= @StartTime  and J_Activity.EndTime >= @EndTime
	 or J_Activity.StartTime <= @StartTime  and J_Activity.EndTime < @EndTime and J_Activity.EndTime > @StartTime
	 or J_Activity.StartTime > @StartTime  and J_Activity.EndTime <= @EndTime
	 or J_Activity.StartTime >= @StartTime and StartTime <@EndTime)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_CheckShiftSkillCompetencyForSkillId')
	DROP PROC prJ_CheckShiftSkillCompetencyForSkillId
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_CheckShiftSkillCompetencyForSkillId
	@OUId bigint,
	@ShiftId bigint,	
	@SkillId bigint
	

AS
select * from D_Skill WITH (NOLOCK)
where skillid in (
select D_RoleSkill.SkillId from s_shifts WITH (NOLOCK)
inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.Employeeid= s_shifts.Employeeid
inner join D_RoleSkill WITH (NOLOCK) on D_RoleSkill.RoleId = C_EmployeeRoles.RoleId
where s_shifts.ShiftId = @ShiftId  and OUId=@OUId
)
and SkillId=@SkillId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteActivityByTimeRange')
	DROP PROC prJ_DeleteActivityByTimeRange
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_DeleteActivityByTimeRange
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL
	
AS


delete from J_ActivityAttributes
where ActivityId in (
select ActivityId from J_Activity WITH (NOLOCK)
where OUId=@OUId
and ProgresstionState <=1 and
 ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
	 )
	 
	
delete from J_Activity
where OUId=@OUId
and ProgresstionState <=1 and
 ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
	
select 1


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteEmployeeTHPDetailsByShiftBandIdForDeAll')
	DROP PROC prJ_DeleteEmployeeTHPDetailsByShiftBandIdForDeAll
GO
----------------------------------------------------------------------------
-- Update a single record in prJ_DeleteEmployeeTHPDetailsByShiftBandIdForDeAll
----------------------------------------------------------------------------
Create PROC [dbo].[prJ_DeleteEmployeeTHPDetailsByShiftBandIdForDeAll]
	@OUId bigint = NULL,
	@ShiftDate datetime = NULL,
	@ShiftBandId bigint = NULL
	
AS



delete from S_THPEmployeeDetails
where shiftid in (
SELECT shiftid from S_Shifts WITH (NOLOCK)
where ShiftBandId=@ShiftBandId and CONVERT(date,actualstarttime) = CONVERT(date,@ShiftDate) and OUId=@OUId
)


select 1



GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteVesselScheduleByVesselScheduleId')
	DROP PROC prJ_DeleteVesselScheduleByVesselScheduleId
GO

----------------------------------------------------------------------------
-- Delete a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_DeleteVesselScheduleByVesselScheduleId
	@VesselScheduleId	BigInt
AS
	CREATE TABLE ##DelVesselActivities (ActivityId BigInt);
	
	INSERT INTO ##DelVesselActivities 
	SELECT	J_Activity.ActivityId
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
	WHERE	J_ActivityAttributes.ScheduleId IN 
	(	
		SELECT EquipmentScheduleId FROM M_EquipmentSchedule WITH (NOLOCK) WHERE CraneScheduleId IN 
		(
			SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
		)
	)
	UNION ALL
	SELECT	J_Activity.ActivityId
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 1 -- Equipment Schedule
	WHERE	J_ActivityAttributes.ScheduleId IN 
	(
		SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
	)
	ORDER BY ActivityId
	--SELECT Activities.ActivityId From Activities

	-- Delete From J_WorkLoad
	DELETE FROM J_Workload WHERE VesselScheduleId = @VesselScheduleId

	-- Delete From J_ActivityAttributes Where Work Type = 1 -- Crane Schedule By Vessel Schedule Id
	DELETE FROM J_ActivityAttributes 
	WHERE	ActivityId IN 
			(	
				SELECT	J_Activity.ActivityId
				FROM	J_Activity WITH (NOLOCK)
						INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 1 -- Equipment Schedule
				WHERE	J_ActivityAttributes.ScheduleId IN 
				(
					SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
				)
			)						  

	-- Delete From J_ActivityAttributes Where Work Type = 2 -- Equipment Schedule By Vessel Schedule Id
	DELETE FROM J_ActivityAttributes 
	WHERE	ActivityId IN 
			(	
				SELECT	J_Activity.ActivityId
				FROM	J_Activity WITH (NOLOCK)
						INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Crane Schedule
				WHERE	J_ActivityAttributes.ScheduleId IN 
				(	
					SELECT EquipmentScheduleId FROM M_EquipmentSchedule WITH (NOLOCK) WHERE CraneScheduleId IN 
					(
						SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
					)
				)
			)

	-- Delete Activity Records of those between Selected Shift Start And End Date By WorkType = 1 & 2 [Crane & Equipment Schedule]
	DELETE	FROM J_Activity 
	WHERE	ActivityId IN (SELECT ActivityId FROM ##DelVesselActivities)

	-- Delete From M_EquipmentSchedule
	DELETE	FROM M_EquipmentSchedule 
	WHERE	CraneScheduleId IN 
			(
				SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
			)

	-- Delete From M_CraneSchedule
	DELETE FROM M_CraneSchedule WHERE VesselScheduleId = @VesselScheduleId

	-- Delete From M_VesselList
	DELETE	FROM M_VesselList 
	WHERE	VesselName IN 
			(
				SELECT VesselName FROM M_VesselSchedule WITH (NOLOCK) WHERE VesselScheduleId = @VesselScheduleId
			)

	-- Delete From M_VesselSchedule
	DELETE FROM M_VesselSchedule WHERE VesselScheduleId = @VesselScheduleId

	DROP TABLE ##DelVesselActivities

	SELECT 1
-- DELETE Activity By Equipment Schedule Id By Crane Schedule Id
--delete from J_ActivityAttributes
--where ActivityId in (select J_Activity.ActivityId from J_Activity inner join  J_ActivityAttributes 
--on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=4 where ScheduleId = @VesselScheduleId)

--delete from J_Activity
--where ActivityId in (select J_Activity.ActivityId from J_Activity inner join  J_ActivityAttributes 
--on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=4 where ScheduleId = @VesselScheduleId)

/*
-- DELETE Activity By Equipment Schedule Id By Crane Schedule Id
delete from J_ActivityAttributes
where ActivityId in (select * from J_Activity left outer join J_ActivityAttributes 
on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=3
inner join  where ScheduleId = @VesselScheduleId)

delete from J_Activity
where ActivityId in (select * from J_Activity left outer join J_ActivityAttributes 
on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=4 where ScheduleId = @VesselScheduleId)




DELETE	FROM J_Activity 
WHERE	ActivityId IN (	-- Retrieve Equipment Schedule ID By Crane Schedule ID
									SELECT EquipmentScheduleId FROM M_EquipmentSchedule WHERE CraneScheduleId IN 
									( 
										-- Retrieve Crane Schedule ID List By Vessel Schedule ID
										SELECT CraneScheduleId FROM M_CraneSchedule WHERE VesselScheduleId = @VesselScheduleId
									)
								)

-- DELETE WorkLoad By Equipment Schedule By Crane Schedule Id
DELETE	FROM J_Workload 
WHERE	EquipmentScheduleId IN (	-- Retrieve Equipment Schedule ID By Crane Schedule ID
									SELECT EquipmentScheduleId FROM M_EquipmentSchedule WHERE CraneScheduleId IN 
									( 
										-- Retrieve Crane Schedule ID List By Vessel Schedule ID
										SELECT CraneScheduleId FROM M_CraneSchedule WHERE VesselScheduleId = @VesselScheduleId
									)
								)

-- DELETE Equipment Schedule By Crane Schedule ID
DELETE	FROM M_EquipmentSchedule 
WHERE	CraneScheduleId in ( SELECT CraneScheduleId FROM M_CraneSchedule WHERE VesselScheduleId = @VesselScheduleId)

-- DELETE Activity By Crane Schedule Id
DELETE FROM J_Activity 
WHERE  CraneScheduleId IN (SELECT CraneScheduled FROM M_VesselSchedule WHERE VesselScheduleId = @VesselScheduleId)

-- DELETE Workload By Crane Schedule Id
DELETE	FROM J_Workload 
WHERE	CraneScheduleId IN (SELECT CraneScheduleId FROM M_CraneSchedule WHERE VesselScheduleId = @VesselScheduleId)

-- DELETE Crane Schedule By Vessel Schedule ID
DELETE	FROM M_CraneSchedule	
WHERE	VesselScheduleId = @VesselScheduleId

-- DELETE Vessel Schedule By Id
DELETE	FROM M_VesselSchedule 
WHERE	VesselScheduleId = @VesselScheduleId
*/
SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteWorkloadByCraneScheduleId')
	DROP PROC prJ_DeleteWorkloadByCraneScheduleId
GO

----------------------------------------------------------------------------
-- Delete a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_DeleteWorkloadByCraneScheduleId
	@CraneScheduleId bigint
AS


delete from J_ActivityAttributes
where ActivityId in (select J_Activity.ActivityId from J_Activity WITH (NOLOCK) inner join J_ActivityAttributes WITH (NOLOCK)
on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=1 where ScheduleId = @CraneScheduleId)

delete from J_Activity
where ActivityId in (select J_Activity.ActivityId from J_Activity WITH (NOLOCK) inner join  J_ActivityAttributes  WITH (NOLOCK)
on J_ActivityAttributes.ActivityId = J_Activity.ActivityId and J_Activity.WorkType=1 where ScheduleId = @CraneScheduleId)


/*
DELETE	J_Activity 
WHERE	CraneScheduleId = @CraneScheduleId

DELETE	J_Workload
WHERE 	CraneScheduleId =@CraneScheduleId
*/

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteWorkloadByEquipmentScheduleId')
	DROP PROC prJ_DeleteWorkloadByEquipmentScheduleId
GO

----------------------------------------------------------------------------
-- Delete a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_DeleteWorkloadByEquipmentScheduleId
	@EquipmentScheduleId bigint
AS
CREATE TABLE ##DelEquipmentActivities (ActivityId BigInt);
	
	INSERT INTO ##DelEquipmentActivities 
	SELECT	J_Activity.ActivityId
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
	WHERE	J_ActivityAttributes.ScheduleId IN 
	(	
		SELECT EquipmentScheduleId FROM M_EquipmentSchedule WITH (NOLOCK) WHERE EquipmentScheduleId = @EquipmentScheduleId
	)
	ORDER BY ActivityId
	--SELECT Activities.ActivityId From Activities

	-- Delete From J_WorkLoad
	DELETE FROM J_Workload WHERE EquipmentScheduleId = @EquipmentScheduleId

	-- Delete From J_ActivityAttributes Where Work Type = 2 -- Equipment Schedule By Vessel Schedule Id
	DELETE FROM J_ActivityAttributes 
	WHERE	ActivityId IN 
			(	
				SELECT	J_Activity.ActivityId
				FROM	J_Activity WITH (NOLOCK)
						INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
				WHERE	J_ActivityAttributes.ScheduleId = @EquipmentScheduleId
			)

	-- Delete Activity Records of those between Selected Shift Start And End Date By WorkType = 1 & 2 [Crane & Equipment Schedule]
	DELETE	FROM J_Activity 
	WHERE	ActivityId IN (SELECT ActivityId FROM ##DelEquipmentActivities)

	-- Delete From M_EquipmentSchedule
	DELETE	FROM M_EquipmentSchedule 
	WHERE	EquipmentScheduleId = @EquipmentScheduleId

	DROP TABLE ##DelEquipmentActivities

	SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteWorkloadByScheduleId')
	DROP PROC prJ_DeleteWorkloadByScheduleId
GO

----------------------------------------------------------------------------
-- Delete a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_DeleteWorkloadByScheduleId
	@ScheduleId bigint
AS

DELETE	J_Workload
WHERE  	ScheduleId = @ScheduleId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetActivitiesByAllocationNumber')
	DROP PROC prJ_GetActivitiesByAllocationNumber
GO

----------------------------------------------------------------------------
-- Retrieve Data From Activity Details By Allocation Details
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivitiesByAllocationNumber]
	@AllocationNo	Int,
	@ShiftId		BigInt,
	@ReliefBreakId	BigInt,
	@WorkLoadType	Int,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@OuId			BigInt,
	@ShiftBandId	BigInt
	
AS	
	SELECT	J_Activity.ActivityId,
			M_EquipmentSchedule.EquipmentId,
			M_EquipmentSchedule.EquipmentScheduleId CraneOrEquipmentScheduleId,
			J_Activity.StartTime ActivityStartTime, J_Activity.EndTime ActivityEndTime, J_Activity.SkillId, D_Skill.Skill SkillName, D_Skill.ColorCode SkillColor,
			J_Activity.ShiftId, J_Activity.ShiftBandId,
			CASE J_Activity.SkillId WHEN @ReliefBreakID THEN '' ELSE M_Equipments.EquipmentName END  EquipmentName,
			CASE J_Activity.SkillId WHEN @ReliefBreakID THEN '' ELSE M_Locations.LocationName END CraneOrEquipmentLocaiton,
			J_Activity.AllocationNo, M_Locations.LocationId, J_Activity.WorkType
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId
			INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
			INNER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_ActivityAttributes.ScheduleId = M_EquipmentSchedule.EquipmentScheduleId
			INNER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
			INNER JOIN M_Locations WITH (NOLOCK) ON M_Equipments.LocationId = M_Locations.LocationId
			LEFT OUTER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = J_Activity.ShiftId AND		S_Shifts.ShiftBandId	=	@ShiftBandId
	WHERE	(J_Activity.AllocationNo = @AllocationNo OR (J_Activity.ShiftId = @ShiftId AND @ShiftId != 0))
	AND 	J_Activity.EndTime > CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.StartTime < CONVERT(DATETIME, @EndDate)
	AND		J_Activity.WorkType		=	2
	AND		J_Activity.OUId			=	@OuId
	UNION ALL
	SELECT	J_Activity.ActivityId,
			M_CraneSchedule.CraneId,
			M_CraneSchedule.CraneScheduleId CraneOrEquipmentScheduleId,
			J_Activity.StartTime, J_Activity.EndTime, J_Activity.SkillId, D_Skill.Skill SkillName, D_Skill.ColorCode SkillColor,
			J_Activity.ShiftId, J_Activity.ShiftBandId,
			CASE J_Activity.SkillId WHEN @ReliefBreakID THEN '' ELSE M_Cranes.CraneNumber END  EquimentName,
			CASE J_Activity.SkillId WHEN @ReliefBreakID THEN '' ELSE M_Locations.LocationName END CraneOrEquipmentLocaiton,
			J_Activity.AllocationNo, M_Locations.LocationId, J_Activity.WorkType
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId
			INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
			INNER JOIN M_CraneSchedule WITH (NOLOCK) ON J_ActivityAttributes.ScheduleId = M_CraneSchedule.CraneScheduleId
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
			INNER JOIN M_Locations WITH (NOLOCK) ON M_Cranes.LocationId = M_Locations.LocationId
			LEFT OUTER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = J_Activity.ShiftId AND		S_Shifts.ShiftBandId	=	@ShiftBandId
	WHERE	(J_Activity.AllocationNo = @AllocationNo OR (J_Activity.ShiftId = @ShiftId AND @ShiftId != 0))
	AND 	J_Activity.EndTime > CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.StartTime < CONVERT(DATETIME, @EndDate)
	--AND		S_Shifts.ShiftBandId	=	@ShiftBandId
	AND		J_Activity.WorkType		=	1
	AND		J_Activity.OUId			=	@OuId
	UNION ALL
	SELECT	J_Activity.ActivityId,
			0 EquipmentId,
			0 CraneOrEquipmentScheduleId,
			J_Activity.StartTime ActivityStartTime, J_Activity.EndTime ActivityEndTime, J_Activity.SkillId, D_Skill.Skill SkillName, D_Skill.ColorCode SkillColor,
			J_Activity.ShiftId, J_Activity.ShiftBandId,
			CASE J_Activity.SkillId WHEN @ReliefBreakID THEN '' ELSE D_Skill.Skill END  EquipmentName,
			'' CraneOrEquipmentLocaiton,
			J_Activity.AllocationNo, 0 LocationId, J_Activity.WorkType
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId
			INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
			LEFT OUTER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = J_Activity.ShiftId AND		S_Shifts.ShiftBandId	=	@ShiftBandId
	WHERE	(J_Activity.AllocationNo = @AllocationNo OR (J_Activity.ShiftId = @ShiftId AND @ShiftId != 0))
	AND 	J_Activity.EndTime > CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.StartTime < CONVERT(DATETIME, @EndDate)
	--AND		S_Shifts.ShiftBandId	=	@ShiftBandId
	AND		J_Activity.WorkType		=	3
	AND		J_Activity.OUId			=	@OuId
	ORDER BY StartTime

	--SELECT	DISTINCT C_Employee.EmployeeId, 
	--		C_Employee.EmployeeNumber,
	--		C_Employee.DisplayName EmployeeName,
	--		C_EmployeeRoles.RoleId,
	--		D_Roles.RoleName,
	--		S_Shifts.ShiftBandId,
	--		D_ShiftBand.ShiftBandName,
	--		S_Shifts.ActualStartTime,
	--		S_Shifts.ActualEndTime
	--FROM	J_Activity 
	--		INNER JOIN S_Shifts ON J_Activity.ShiftId = S_Shifts.ShiftId
	--		INNER JOIN C_Employee ON S_Shifts.EmployeeId = C_Employee.EmployeeId AND C_Employee.ActiveStatus = 1
	--		INNER JOIN C_EmployeeRoles ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
	--		INNER JOIN D_Roles ON D_Roles.RoleId  = C_EmployeeRoles.RoleId
	--		INNER JOIN D_ShiftBand ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	--WHERE	J_Activity.AllocationNo = @AllocationNo
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_GetActivityByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_GetActivityByDateRange]
GO
 
CREATE PROCEDURE [dbo].[prJ_GetActivityByDateRange]
	@OUId			BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@Skills			nVarchar(max),
	@EquipmentTypes	nVarchar(max),
	@Equipments		nVarchar(max)
AS
DECLARE @__skillsId BIGINT = 0, @__EquipmentTypesId BIGINT = 0, @__EquipmentsId BIGINT = 0
BEGIN

	SELECT TOP 1 @__skillsId = sID FROM fnStringToTable(@Skills)
	
	SELECT TOP 1 @__EquipmentTypesId = sID FROM fnStringToTable(@EquipmentTypes)

	SELECT TOP 1 @__EquipmentsId = sID FROM fnStringToTable(@Equipments)

	SELECT	J_Activity.ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.ShiftBandId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.AllocationNo,
		--	J_Activity.CraneScheduleId,
			CraneSchedule.ScheduleId CraneScheduleId,
			--J_Activity.EquipmentScheduleId,
			NULL EquipmentScheduleId,
			J_Activity.WorkType,
			M_CraneSchedule.CraneId,
			M_Cranes.CraneNumber,
			M_CraneSchedule.StartDate CraneScheduleStart,
			M_CraneSchedule.EndDate	CraneScheduleEnd,
			NULL EquipmentId,
			NULL EquipmentName,
			NULL EquipmentScheduleStart,
			NULL EquipmentScheduleEnd,
			M_VesselSchedule.VesselScheduleId,
			M_VesselSchedule.VesselName,
			M_VesselSchedule.VisitId VesselVisitId,
			M_VesselSchedule.StartDate VesselScheduleStart,
			M_VesselSchedule.EndDate VesselScheduleEnd,
			D_ShiftBand.ShiftBandCode
	FROM	J_Activity WITH (NOLOCK) INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId 
				AND (D_Skill.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__skillsId = 0)
			INNER JOIN J_ActivityAttributes CraneSchedule WITH (NOLOCK) on CraneSchedule.ActivityId = J_Activity.ActivityId
			INNER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneSchedule.Scheduleid = M_CraneSchedule.CraneScheduleId AND J_Activity.WorkType= 1
			INNER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = J_Activity.ShiftBandId
	WHERE 	J_Activity.OUId=@OUId
	AND 	(J_Activity.StartTime >= CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.EndTime <= CONVERT(DATETIME, @EndDate))
	--AND 	(EndTime > CONVERT(DATETIME, @StartDate)
	--AND 	StartTime < CONVERT(DATETIME, @EndDate))
	AND		J_Activity.ProgresstionState = 2
	AND		(J_Activity.SHIFTID = 0 OR J_Activity.ShiftId IS NULL)
	UNION
	SELECT	J_Activity.ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.ShiftBandId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.AllocationNo,
		--	J_Activity.CraneScheduleId,
			NULL CraneScheduleId,
			--J_Activity.EquipmentScheduleId,
			EquipmentSchedule.ScheduleId EquipmentScheduleId,
			J_Activity.WorkType,
			M_CraneSchedule.CraneId,
			NULL CraneNumber,
			M_CraneSchedule.StartDate CraneScheduleStart,
			M_CraneSchedule.EndDate	CraneScheduleEnd,
			M_Equipments.EquipmentId EquipmentId,
			M_Equipments.EquipmentName,
			M_EquipmentSchedule.StartDate EquipmentScheduleStart,
			M_EquipmentSchedule.EndDate EquipmentScheduleEnd,
			M_VesselSchedule.VesselScheduleId,
			M_VesselSchedule.VesselName,
			M_VesselSchedule.VisitId VesselVisitId,
			M_VesselSchedule.StartDate VesselScheduleStart,
			M_VesselSchedule.EndDate VesselScheduleEnd,
			D_ShiftBand.ShiftBandCode
	FROM	J_Activity WITH (NOLOCK) INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
				AND (D_Skill.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__skillsId = 0) -- Skill Filter
			INNER JOIN J_ActivityAttributes EquipmentSchedule WITH (NOLOCK) on EquipmentSchedule.ActivityId = J_Activity.ActivityId
			INNER JOIN M_EquipmentSchedule WITH (NOLOCK) ON EquipmentSchedule.Scheduleid = M_EquipmentSchedule.EquipmentScheduleId AND J_Activity.WorkType = 2
			INNER JOIN M_Equipments WITH (NOLOCK) ON M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId 
				AND (M_Equipments.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes)) OR @__EquipmentTypesId = 0) -- Equipment Type Filter
				AND (M_Equipments.EquipmentId IN (SELECT * FROM fnStringToTable(@Equipments)) OR @__EquipmentsId = 0) --Equipments Filter
			LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = M_EquipmentSchedule.CraneScheduleId
			LEFT OUTER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = J_Activity.ShiftBandId
	WHERE 	J_Activity.OUId=@OUId
	AND 	(J_Activity.StartTime >= CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.EndTime <= CONVERT(DATETIME, @EndDate))
	--AND 	(EndTime > CONVERT(DATETIME, @StartDate)
	--AND 	StartTime < CONVERT(DATETIME, @EndDate))
	AND		J_Activity.ProgresstionState = 2
	AND		(J_Activity.SHIFTID = 0 OR J_Activity.ShiftId IS NULL)
	UNION
	SELECT	J_Activity.ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.ShiftBandId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.AllocationNo,
		--	J_Activity.CraneScheduleId,
			NULL CraneScheduleId,
			--J_Activity.EquipmentScheduleId,
			NULL EquipmentScheduleId,
			J_Activity.WorkType,
			NULL CraneId,
			NULL CraneNumber,
			NULL CraneScheduleStart,
			NULL CraneScheduleEnd,
			NULL EquipmentId,
			NULL EquipmentName,
			NULL EquipmentScheduleStart,
			NULL EquipmentScheduleEnd,
			M_VesselSchedule.VesselScheduleId,
			M_VesselSchedule.VesselName,
			M_VesselSchedule.VisitId VesselVisitId,
			M_VesselSchedule.StartDate VesselScheduleStart,
			M_VesselSchedule.EndDate VesselScheduleEnd,
			D_ShiftBand.ShiftBandCode
	FROM	J_Activity WITH (NOLOCK) INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
				AND (D_Skill.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__skillsId = 0) -- Skill Filter
			INNER JOIN J_ActivityAttributes VesselSchedule WITH (NOLOCK) on VesselSchedule.ActivityId = J_Activity.ActivityId
			INNER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = VesselSchedule.ScheduleId AND J_Activity.WorkType = 4
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = J_Activity.ShiftBandId
	WHERE 	J_Activity.OUId=@OUId
	AND 	(J_Activity.StartTime >= CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.EndTime <= CONVERT(DATETIME, @EndDate))
	--AND 	(EndTime > CONVERT(DATETIME, @StartDate)
	--AND 	StartTime < CONVERT(DATETIME, @EndDate))
	AND		J_Activity.ProgresstionState = 2
	AND		(J_Activity.SHIFTID = 0 OR J_Activity.ShiftId IS NULL)
	UNION
	SELECT	J_Activity.ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.ShiftBandId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.AllocationNo,
		--	J_Activity.CraneScheduleId,
			NULL CraneScheduleId,
			--J_Activity.EquipmentScheduleId,
			NULL EquipmentScheduleId,
			J_Activity.WorkType,
			NULL CraneId,
			NULL CraneNumber,
			NULL CraneScheduleStart,
			NULL CraneScheduleEnd,
			NULL EquipmentId,
			NULL EquipmentName,
			NULL EquipmentScheduleStart,
			NULL EquipmentScheduleEnd,
			NULL VesselScheduleId,
			NULL VesselName,
			NULL VesselVisitId,
			NULL VesselScheduleStart,
			NULL VesselScheduleEnd,
			D_ShiftBand.ShiftBandCode
	FROM	J_Activity WITH (NOLOCK) INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId 
				AND (D_Skill.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__skillsId = 0) -- Skill Filter
				AND J_Activity.WorkType = 3
				AND	(J_Activity.SHIFTID = 0 OR J_Activity.ShiftId IS NULL)
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = J_Activity.ShiftBandId
	WHERE 	J_Activity.OUId=@OUId
	AND 	(J_Activity.StartTime >= CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.EndTime <= CONVERT(DATETIME, @EndDate))
	--AND 	(EndTime > CONVERT(DATETIME, @StartDate)
	--AND 	StartTime < CONVERT(DATETIME, @EndDate))
	AND		J_Activity.ProgresstionState = 2

	--ORDER BY J_Activity.WorkType, J_Activity.StartTime
	ORDER BY J_Activity.AllocationNo, J_Activity.SkillId, J_Activity.StartTime
END


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetActivityByDateRangeAndSkillAndRBId')
	DROP PROC prJ_GetActivityByDateRangeAndSkillAndRBId
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivityByDateRangeAndSkillAndRBId]
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@SkillId bigint,
	@ReliefBreakId BigInt
	
AS

select * from  J_Activity WITH (NOLOCK)
where OUId=@OUId and (ShiftId =0 or ShiftId is null)
and ProgresstionState >1 and SkillId IN (@SkillId, @ReliefBreakId)
 and ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
order by GroupNo

go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetActivityByDateRangeAndSkillId')
	DROP PROC prJ_GetActivityByDateRangeAndSkillId
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivityByDateRangeAndSkillId]
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@SkillId bigint
	
AS

select * from  J_Activity WITH (NOLOCK)
where OUId=@OUId and (ShiftId =0 or ShiftId is null)
and ProgresstionState >1 and SkillId = @SkillId
 and ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
order by GroupNo

go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetActivityByDateRangeAndSkillIdAndGroupNo')
	DROP PROC prJ_GetActivityByDateRangeAndSkillIdAndGroupNo
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivityByDateRangeAndSkillIdAndGroupNo]
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@SkillId bigint,
	--@GroupNo int
	@AllocationNo INT
	
AS

select * from  J_Activity WITH (NOLOCK)
where  (ShiftId =0 or ShiftId is null) and OUId=@OUId 
and ProgresstionState >1 
--and SkillId = @SkillId
and AllocationNo = @AllocationNo --GroupNo=@GroupNo
 and ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
order by GroupNo


go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_GetActivityWithPayCodeByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_GetActivityWithPayCodeByDateRange]
GO
 
CREATE PROCEDURE [dbo].[prJ_GetActivityWithPayCodeByDateRange]
	--@OUId bigint,
	--@StartDate DateTime,
	--@EndDate DateTime,
	@ShiftId	BigInt
AS

	WITH Activities (SkillName, StartTime, EndTime, TotalHours, EquipmentId, EquipmentName, ActivityId, ActivityAttributeId)
	AS 
		(
		SELECT	D_Skill.Skill SkillName, J_Activity.StartTime, J_Activity.EndTime,
				Convert(Decimal(18,0),DateDiff(HOUR, J_Activity.StartTime, J_Activity.EndTime)) TotalHours,
				M_Cranes.CraneId EquipmentId, M_Cranes.CraneNumber EquipmentName, --'' PayCode,
				J_Activity.ActivityId, J_ActivityAttributes.ActivityAttributeId			
		FROM	J_Activity WITH (NOLOCK)
				INNER JOIN J_ActivityAttributes  WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId AND J_Activity.ProgresstionState = 3
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = J_ActivityAttributes.ScheduleId AND J_Activity.WorkType = 1 -- For Crane Schedule
				INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneSchedule.CraneId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
		WHERE	J_Activity.ShiftId = @ShiftId
		UNION 
		SELECT	D_Skill.Skill SkillName, J_Activity.StartTime, J_Activity.EndTime,
				Convert(Decimal(18,0),DateDiff(HOUR, J_Activity.StartTime, J_Activity.EndTime)) TotalHours,
				M_Equipments.EquipmentId, M_Equipments.EquipmentName, --'' PayCode,
				J_Activity.ActivityId, J_ActivityAttributes.ActivityAttributeId			
		FROM	J_Activity WITH (NOLOCK)
				INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId AND J_Activity.ProgresstionState = 3
				INNER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId= J_ActivityAttributes.ScheduleId AND J_Activity.WorkType = 2 -- For Equipment Schedule
				INNER JOIN M_Equipments WITH (NOLOCK) ON M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
		WHERE	J_Activity.ShiftId = @ShiftId
		UNION 
		SELECT	D_Skill.Skill SkillName, J_Activity.StartTime, J_Activity.EndTime,
				Convert(Decimal(18,0),DateDiff(HOUR, J_Activity.StartTime, J_Activity.EndTime)) TotalHours,
				M_VesselSchedule.VisitId EquipmentId, M_VesselSchedule.VesselName EquipmentName, --'' PayCode,
				J_Activity.ActivityId, J_ActivityAttributes.ActivityAttributeId			
		FROM	J_Activity WITH (NOLOCK)
				INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId AND J_Activity.ProgresstionState = 3
				INNER JOIN M_VesselSchedule  WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = J_ActivityAttributes.ScheduleId AND J_Activity.WorkType = 3 -- For Vessel Schedule
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
		WHERE	J_Activity.ShiftId = @ShiftId
		UNION 
		SELECT	D_Skill.Skill SkillName, J_Activity.StartTime, J_Activity.EndTime,
				Convert(Decimal(18,0),DateDiff(HOUR, J_Activity.StartTime, J_Activity.EndTime)) TotalHours,
				0 EquipmentId, '' EquipmentName, --'' PayCode,
				J_Activity.ActivityId, J_ActivityAttributes.ActivityAttributeId			
		FROM	J_Activity WITH (NOLOCK)
				INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId AND J_Activity.ProgresstionState = 3
				INNER JOIN M_AuxiliaryWork WITH (NOLOCK) ON M_AuxiliaryWork.ScheduleId = J_ActivityAttributes.ScheduleId AND J_Activity.WorkType = 4 -- For Auxiliary Work Schedule
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
		WHERE	J_Activity.ShiftId = @ShiftId
	)
	SELECT * FROM Activities ORDER BY StartTime, SkillName

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetAllocationRuleFactorSeqByAllocationTemplateId')
	DROP PROC prJ_GetAllocationRuleFactorSeqByAllocationTemplateId
GO

----------------------------------------------------------------------------
--
----------------------------------------------------------------------------
CREATE PROC prJ_GetAllocationRuleFactorSeqByAllocationTemplateId
	@AllocationRuleId bigint

AS

select * from J_AllocationRuleFactor WITH (NOLOCK)
where AllocationRuleId=@AllocationRuleId
order by FactorValue desc

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_GetAllocationRules]') AND type in (N'P', N'PC'))
DROP PROC [dbo].[prJ_GetAllocationRules]

GO

Create PROC [dbo].[prJ_GetAllocationRules]   
(
	@AllocationRuleId	BigInt,
	@OUID				BigInt
	
)
AS
BEGIN	 
	SELECT	AllocationRuleId,
			OUId,
			RuleName RuleName,
			RuleDesc RuleDescription,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	J_AllocationRule WITH (NOLOCK)
	WHERE	J_AllocationRule.OuId = @OUID
	AND		(J_AllocationRule.AllocationRuleId = @AllocationRuleId OR @AllocationRuleId = 0)
	Order By J_AllocationRule.RuleName
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_GetAllocationRulesById]') )
DROP PROC [dbo].[prJ_GetAllocationRulesById]
 
GO

Create PROC [dbo].[prJ_GetAllocationRulesById]   
(
	@AllocationRuleId	BigInt
	
)
AS
BEGIN	 
	SELECT	AllocationRuleId,
			OUId,
			RuleName,
			RuleDesc RuleDescription,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	J_AllocationRule WITH (NOLOCK)
	WHERE	J_AllocationRule.AllocationRuleId = @AllocationRuleId
	AND		J_AllocationRule.AllocationRuleId = @AllocationRuleId OR @AllocationRuleId = 0
	Order By J_AllocationRule.RuleName
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetAvailableShiftsByDateShiftBandAndSkills')
	DROP PROC prJ_GetAvailableShiftsByDateShiftBandAndSkills
GO

----------------------------------------------------------------------------
-- Get Employees Who are not being assigned to work on selected date, shiftband and Skills
-- For Suggested Resources
----------------------------------------------------------------------------
CREATE PROC prJ_GetAvailableShiftsByDateShiftBandAndSkills
	@OUId			BigInt,
	@ShiftBandId	BigInt,
	@ShiftDate		DateTime, 
	@SearchSkills	nVarchar(Max)
AS

SELECT	C_Employee.EmployeeId,
		C_Employee.EmployeeNumber,
		C_Employee.EmployeeNumber,
		c_eMPLOYEEROLES.RoleId PrimaryRoleId,
		D_Roles.RoleName, 
		C_OrganizationNode.OUId,
		C_OrganizationNode.OUName
FROM	S_Shifts WITH (NOLOCK)
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId  AND C_EmployeeRoles.RoleId = D_Roles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
WHERE	D_Roles.RoleId IN (SELECT DISTINCT ROLEID FROM D_RoleSkill WITH (NOLOCK) WHERE D_RoleSkill.SkillId IN (SELECT * FROM fnStringToTable(@SearchSkills)))
AND		(S_Shifts.ShiftBandId = @ShiftBandId OR S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId)
AND		S_Shifts.OUId = @OUId
AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ShiftDate)

--AND		NOT EXISTS (SELECT SHIFTID FROM J_Activity WHERE (EndTime >= CONVERT(DATETIME, @StartDate) AND	StartTime < CONVERT(DATETIME, @EndDate))

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetBroadcastDeploymentByDate')
	DROP PROC prJ_GetBroadcastDeploymentByDate
GO

----------------------------------------------------------------------------
-- Insert a single record into prJ_GetBroadcastDeploymentByDate
----------------------------------------------------------------------------
CREATE PROC prJ_GetBroadcastDeploymentByDate
	@OUId				BigInt,
	@ShiftBandId		BigInt,
	@StartTime			DateTime,
	@EndTime			DateTime
AS
BEGIN
	SELECT	BroadcastId, OUId, BroadcastDate, ShiftBandId, StartTime, EndTime, EmployeeId, ShiftId, Sequence, CreatedBy, CreatedDate 
	FROM	J_BroadcastDeployment WITH (NOLOCK)
	WHERE	OUId						=	@OUId
	AND		Convert(DateTime,StartTime) =	Convert(DateTime,@StartTime)
	AND		Convert(DateTime,EndTime)	=	Convert(DateTime,@EndTime)
	AND		ShiftBandId					=	@ShiftBandId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetBroadcastHistoryByDate')
	DROP PROC prJ_GetBroadcastHistoryByDate
GO

----------------------------------------------------------------------------
-- Retrieve Broadcast History By Date
----------------------------------------------------------------------------
CREATE PROC prJ_GetBroadcastHistoryByDate
	@BroadcastDate		DateTime,
	@ShiftBandId		BigInt,
	@OUId				BigInt
AS
	-- Retrieve Broadcast Details By Selected Date
	SELECT	BroadcastId, 
			J_BroadcastDeployment.OUId, 
			J_BroadcastDeployment.BroadcastDate,
			J_BroadcastDeployment.ShiftBandId, 
			J_BroadcastDeployment.StartTime,
			J_BroadcastDeployment.EndTime,
			J_BroadcastDeployment.EmployeeId,
			J_BroadcastDeployment.ShiftId,
			J_BroadcastDeployment.Sequence,
			J_BroadcastDeployment.CreatedBy,
			J_BroadcastDeployment.CreatedDate,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_OrganizationNode.OUName,
			D_ShiftBand.ShiftBandCode,
			D_ShiftBand.ShiftBandName
	FROM	J_BroadcastDeployment WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON J_BroadcastDeployment.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON J_BroadcastDeployment.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON J_BroadcastDeployment.OUId = C_OrganizationNode.OUId
	WHERE	Convert(Date,J_BroadcastDeployment.BroadcastDate) = Convert(Date,@BroadcastDate)
	AND		J_BroadcastDeployment.ShiftBandId	=	@ShiftBandId
	AND		J_BroadcastDeployment.OUId			=	@OUId
	ORDER	BY C_Employee.EmployeeNumber

	-- Retrieve Broadcaset History [Only Summary]
	SELECT	BroadcastDate, 
			J_BroadcastDeployment.ShiftBandId, 
			J_BroadcastDeployment.StartTime, 
			J_BroadcastDeployment.EndTime, 
			Count(EmployeeId) BroadcastCount, 
			Sequence,
			D_ShiftBand.ShiftBandCode,
			D_ShiftBand.ShiftBandName,
			J_BroadcastDeployment.CreatedBy
	FROM	J_BroadcastDeployment WITH (NOLOCK) 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON J_BroadcastDeployment.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	Convert(Date,J_BroadcastDeployment.BroadcastDate) = Convert(Date,@BroadcastDate)
	AND		J_BroadcastDeployment.ShiftBandId	=	@ShiftBandId
	AND		J_BroadcastDeployment.OUId			=	@OUId
	GROUP	BY BroadcastDate, J_BroadcastDeployment.ShiftBandId, J_BroadcastDeployment.StartTime, 
			J_BroadcastDeployment.EndTime, Sequence, D_ShiftBand.ShiftBandCode, D_ShiftBand.ShiftBandName, J_BroadcastDeployment.CreatedBy

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetDeployedShiftsByDateAndShiftBandId')
	DROP PROC prJ_GetDeployedShiftsByDateAndShiftBandId
GO

----------------------------------------------------------------------------
-- Insert a single record into prJ_GetDeployedShiftsByDateAndShiftBandId
----------------------------------------------------------------------------
CREATE PROC prJ_GetDeployedShiftsByDateAndShiftBandId
	@OUId				BigInt,
	@ShiftBandId		BigInt,
	@StartTime			DateTime,
	@EndTime			DateTime
AS
BEGIN
	WITH Activities 
	AS
	(
		SELECT	DISTINCT ShiftId 
		FROM	J_Activity WITH (NOLOCK)
		WHERE	Convert(DateTime,EndTime)	>=	Convert(DateTime,@StartTime)
		AND		Convert(DateTime,StartTime) <=	Convert(DateTime,@EndTime)
		AND		J_Activity.ShiftBandId		=	@ShiftBandId
		AND		J_Activity.OUId				=	@OUId
	)
	SELECT	S_Shifts.OUId, S_Shifts.ShiftBandId, S_Shifts.EmployeeId, S_Shifts.ShiftId,	
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime
	FROM	S_Shifts WITH (NOLOCK)
			INNER JOIN Activities ON S_Shifts.ShiftId = Activities.ShiftId
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_GetDeployedSkillsByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_GetDeployedSkillsByDateRange]
GO
 
CREATE PROCEDURE [dbo].[prJ_GetDeployedSkillsByDateRange]
	@OUId				BigInt,
	@StartDate			DateTime,
	@EndDate			DateTime
AS
BEGIN

	SELECT	J_Activity.ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.ShiftBandId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.AllocationNo,
			J_Activity.WorkType, 
			IsNull(J_Activity.ShiftId,0) ShiftId
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId 
	WHERE 	J_Activity.OUId=@OUId
	AND 	(EndTime >= CONVERT(DATETIME, @StartDate)
	AND 	StartTime < CONVERT(DATETIME, @EndDate))
	--AND		J_Activity.ShiftId IS NOT NULL
	--AND		J_Activity.ProgresstionState = 3
END


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetEmployeesByFilterCriteria')
	DROP PROC prJ_GetEmployeesByFilterCriteria
GO

----------------------------------------------------------------------------
-- Retrieve List of Employees of who are not assigned to Any Shift Or From Off Day
-- This procedure will be used in Add Shift And Other Required Locations (Change other locations with exact location name)
----------------------------------------------------------------------------
CREATE PROC prJ_GetEmployeesByFilterCriteria
	@OUId			BigInt,
	@ShiftBandId	BigInt,
	@ShiftDate		DateTime
AS
	-- List of Employees who are not assinged to any work
	SELECT	C_Employee.EmployeeId,
			C_EmployeeRoles.RoleId PrimaryRoleId,
			D_Roles.RoleName PrimaryRoleName,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_Employee.ContractedHours,
			C_EmployeeSkills.SkillId PrimarySkillId,
			C_EmployeeSkills.IsPrimary IsPrimarySkill,
			D_Skill.Skill PrimarySkillName,
			C_Employee.RosterGroupId,
			IsNull(C_Employee.HourlyRate,0) HourlyRate
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1 
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId AND C_EmployeeSkills.IsPrimary = 1
			INNER JOIN D_Skill WITH (NOLOCK) ON D_SKill.SkillId = C_EmployeeSkills.SkillId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	C_Employee.OUId = @OUId
	AND		C_Employee.EmployeeId NOT IN (SELECT EmployeeId FROM S_Shifts WITH (NOLOCK) WHERE Convert(Date,ActualStartTime) = Convert(Date, @ShiftDate) AND (ShiftBandId != CombinationShiftId OR CombinationShiftId  IS NULL))
	AND		C_Employee.EmployeeId NOT IN (SELECT EMPLOYEEID FROM S_EmployeeLeaves WITH (NOLOCK) WHERE Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date, @ShiftDate))
	
	--AND S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId IS NULL
	

	-- List of Employees Who are assinged to Flexi Shift 
	SELECT C_Employee.EmployeeId,
			C_EmployeeRoles.RoleId PrimaryRoleId,
			D_Roles.RoleName PrimaryRoleName,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_Employee.ContractedHours,
			C_EmployeeSkills.SkillId PrimarySkillId,
			C_EmployeeSkills.IsPrimary IsPrimarySkill,
			D_Skill.Skill PrimarySkillName,
			C_Employee.RosterGroupId,
			IsNull(C_Employee.HourlyRate,0) HourlyRate
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1 
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId AND C_EmployeeSkills.IsPrimary = 1
			INNER JOIN D_Skill WITH (NOLOCK) ON D_SKill.SkillId = C_EmployeeSkills.SkillId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	C_Employee.OUId = @OUId
	AND EXISTS 
	(
		SELECT * FROM S_Shifts  WITH (NOLOCK)
		WHERE	Convert(Date,ActualStartTime) = Convert(Date, @ShiftDate) 
		AND		S_Shifts.OUId = @OUId
		AND S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId
		AND EXISTS  ( SELECT * FROM D_ShiftBandCombination WITH (NOLOCK) WHERE D_ShiftBandCombination.ComboShiftBandId = @ShiftBandId )
	)

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetFlexiShiftsByDateShiftBand')
	DROP PROC prJ_GetFlexiShiftsByDateShiftBand
GO

----------------------------------------------------------------------------
-- Get All Flexi Shifts
----------------------------------------------------------------------------
CREATE PROC prJ_GetFlexiShiftsByDateShiftBand
	@OUId bigint,
	@ShiftBandId bigint,	
	@ShiftDate Date
AS
BEGIN
	-- Retrieve All Shifts Which are of Flexi Shift Type For Selected Date And OU
	SELECT	DISTINCT S_Shifts.ShiftId,
			S_Shifts.EmployeeId,
			S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime,
			IsNull(C_Employee.ScheduleRuleId,0) ScheduleRuleId,
			S_Shifts.OUId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_Employee.ContractedHours,
			C_Employee.ScheduleRuleId,
			D_RoleSkill.SkillId, 
			C_EmployeeRoles.IsPrimaryRole,
			CASE  
				WHEN D_Roles.PrimarySkillId = D_RoleSkill.SkillId THEN Convert(bit,1) ELSE Convert(bit,0) 
			END PrimarySkill,
			C_Employee.EmploymentBasisId,
			D_RoleSkill.RoleId, IsNull(D_Roles.RolePrioritySeq,0) RolePrioritySeq
	FROM	S_Shifts WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId 
			AND S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN D_ShiftBandCombination WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = D_ShiftBandCombination.ShiftBandId
			AND D_ShiftBandCombination.ComboShiftBandId = @ShiftBandId
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_RoleSkill WITH (NOLOCK) ON D_RoleSkill.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = D_RoleSkill.RoleId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ShiftDate)
	AND		S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM S_EmployeeLeaves WITH (NOLOCK)
						   WHERE Convert(Date,@ShiftDate) = Convert(Date,FromDate) 
						   AND S_EmployeeLeaves.OUId = @OUId) 
	and S_Shifts.ouid = @OUId
	---- Retrieve Schedule Period For Selected Date, ShiftBand And OU
	--WITH  SchedulePeriod 
	--(SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate)
	--AS
	--(	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate 
	--	FROM	S_SchedulePeriod
	--	WHERE	Convert(Date, @ShiftDate) >= StartDate And Convert(Date,@ShiftDate) <= EndDate
	--	AND		S_SchedulePeriod.OUId = @OUId
	--	AND		ScheduleRuleId = 2
	--)
	--SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	--FROM	S_SchedulePeriod 
	--WHERE	PeriodNo = (SELECT PeriodNo FROM SchedulePeriod) - 1
	--AND		OUId	=	@OUId
	--UNION ALL
	--SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	--FROM	SchedulePeriod;

	---- Retreive Previous And Current Period Shifts For Shift Validation
	--WITH  SchedulePeriod 
	--AS
	--(	
	--	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate 
	--	FROM	S_SchedulePeriod
	--	WHERE	Convert(Date, @ShiftDate) >= StartDate And Convert(Date,@ShiftDate) <= EndDate
	--	AND		S_SchedulePeriod.OUId = @OUId
	--),
	--SchedulePeriodPrevCurr As 
	--(
	--	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	--	FROM	S_SchedulePeriod 
	--	WHERE	PeriodNo	= (SELECT PeriodNo FROM SchedulePeriod) - 1
	--	AND		OUId		=	@OUId
	--	UNION ALL
	--	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	--	FROM	SchedulePeriod
	--)
	--SELECT	S_Shifts.ShiftId, 
	--		S_Shifts.EmployeeId,
	--		S_Shifts.ShiftBandId,
	--		S_Shifts.ActualStartTime,
	--		S_Shifts.ActualEndTime
	--FROM	S_Shifts
	--WHERE	Convert(Date, ActualStartTime) >= (select MIN(STARTDATE) FROM SchedulePeriodPrevCurr)
	--AND		Convert(Date, ActualStartTime) <= (select MAX(EndDate) FROM SchedulePeriodPrevCurr)
	--AND		S_Shifts.OUId = @OUId
	--AND		S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId

	-- Retrieve Schedule Rules
	SELECT * FROM S_ScheduleRules WITH (NOLOCK)

	-- Retrieve Schedule Rule Period
	SELECT	S_ScheduleRulePeriod.*, S_ScheduleRulePeriodShiftbands.ShiftBandId 
	FROM	S_ScheduleRulePeriod	WITH (NOLOCK)
			INNER JOIN S_ScheduleRulePeriodShiftbands ON S_ScheduleRulePeriod.SCRPeriodId = S_ScheduleRulePeriodShiftbands.SCRPeriodId

	-- Retrieve Schedule Rule Period Shift Bands
	SELECT * FROM S_ScheduleRulePeriodShiftbands WITH (NOLOCK)

	-- Retrieve Shift Band Details By Shift Band Id
	--SELECT * FROM D_ShiftBand WHERE ShiftBandId = @ShiftBandId


END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetManningRatio')
	DROP PROC prJ_GetManningRatio
GO

----------------------------------------------------------------------------
-- Get All Records From prJ_GetManningRatio
----------------------------------------------------------------------------
CREATE PROC prJ_GetManningRatio
AS

SELECT  J_ManningRatio.Activity,
		J_ManningRatio.Employee,
		J_ManningRatio.MaxHour,
		J_ManningRatio.RatioId,
		J_ManningRatio.RBHour,
		J_ManningRatio.ShiftHour
FROM	J_ManningRatio WITH (NOLOCK)
ORDER BY J_ManningRatio.Employee, J_ManningRatio.ShiftHour

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetMaxGroupNoActivityByTimeRange')
	DROP PROC prJ_GetMaxGroupNoActivityByTimeRange
GO

----------------------------------------------------------------------------
-- Insert a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_GetMaxGroupNoActivityByTimeRange
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL
	
AS

select max(GroupNo) GroupNo from  J_Activity WITH (NOLOCK)
where OUId=@OUId
and ProgresstionState >1 and
 ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetRecommendedEmployeesToSwap')
	DROP PROC prJ_GetRecommendedEmployeesToSwap
GO

----------------------------------------------------------------------------
-- Retrieve Recommended Employees To Swap.
----------------------------------------------------------------------------
CREATE PROC prJ_GetRecommendedEmployeesToSwap
	@OUId			BigInt,
	@ShiftId		BigInt,
	@EmployeeId		BigInt,
	@ShiftStartTime	DateTime,
	@ShiftEndTime	DateTime
AS
BEGIN
	WITH ACTIVITIES (ShiftId)
	AS
	(
		SELECT	DISTINCT J_Activity.ShiftID 
		FROM	J_Activity  WITH (NOLOCK)
		WHERE	J_Activity.SkillId IN (SELECT SKILLID FROM C_EmployeeSkills WITH (NOLOCK) WHERE EmployeeId = @EmployeeId) --AND IsPrimary = 1)
		AND Convert(DateTime,EndTime) > Convert(DateTime,@ShiftStartTime)
		AND Convert(DateTime,StartTime) < Convert(DateTime,@ShiftEndTime)
		AND	J_Activity.ShiftId != @ShiftId
		AND J_Activity.OUId = @OUId
	)
	SELECT	C_Employee.EmployeeId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftId,
			D_Roles.RoleId PrimaryRoleId, 
			D_Roles.RoleName PrimaryRoleName,
			C_Employee.EmployeeId id,
			C_Employee.EmployeeNumber + ' - ' + Replace(LTRIM(RTRIM(C_Employee.DisplayName)),'-','') + ' - ' + D_Roles.RoleName [text]
	FROM	S_Shifts WITH (NOLOCK)
			INNER JOIN ACTIVITIES WITH (NOLOCK) ON S_Shifts.ShiftId = ACTIVITIES.ShiftId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	S_Shifts.ShiftId != @ShiftId
END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetSchedulePeriodAndShiftsByEmployeeId')
	DROP PROC prJ_GetSchedulePeriodAndShiftsByEmployeeId
GO

----------------------------------------------------------------------------
-- Get All Flexi Shifts
----------------------------------------------------------------------------
CREATE PROC prJ_GetSchedulePeriodAndShiftsByEmployeeId
	@OUId			BigInt,
	@ShiftBandId	BigInt,	
	@ShiftDate		Date,
	@ScheduleRuleId	BigInt,
	@EmployeeId		BigInt
AS
BEGIN
	-- Retrieve Schedule Period For Selected Date, ShiftBand And OU
	WITH  SchedulePeriod 
	(SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate)
	AS
	(	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate 
		FROM	S_SchedulePeriod WITH (NOLOCK)
		WHERE	Convert(Date, @ShiftDate) >= StartDate And Convert(Date,@ShiftDate) <= EndDate
		AND		S_SchedulePeriod.OUId = @OUId
		AND		S_SchedulePeriod.ScheduleRuleId	=	@ScheduleRuleId
	)
	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	FROM	S_SchedulePeriod  WITH (NOLOCK)
	WHERE	PeriodNo	= (SELECT PeriodNo FROM SchedulePeriod) - 1
	AND		OUId		=	@OUId
	AND		S_SchedulePeriod.ScheduleRuleId	=	@ScheduleRuleId
	UNION ALL
	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	FROM	SchedulePeriod;

	-- Retreive Previous And Current Period Shifts For Shift Validation
	WITH  SchedulePeriod 
	AS
	(	
		SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate 
		FROM	S_SchedulePeriod WITH (NOLOCK)
		WHERE	Convert(Date, @ShiftDate) >= StartDate And Convert(Date,@ShiftDate) <= EndDate
		AND		S_SchedulePeriod.OUId = @OUId
		AND		S_SchedulePeriod.ScheduleRuleId	=	@ScheduleRuleId
	),
	SchedulePeriodPrevCurr As 
	(
		SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
		FROM	S_SchedulePeriod  WITH (NOLOCK)
		WHERE	PeriodNo	= (SELECT PeriodNo FROM SchedulePeriod) - 1
		AND		OUId		=	@OUId
		AND		S_SchedulePeriod.ScheduleRuleId	=	@ScheduleRuleId
		UNION ALL
		SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
		FROM	SchedulePeriod
	)
	SELECT	S_Shifts.ShiftId, 
			S_Shifts.EmployeeId,
			S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	Convert(Date, ActualStartTime) >= (select MIN(STARTDATE) FROM SchedulePeriodPrevCurr)
	AND		Convert(Date, ActualStartTime) <= (select MAX(EndDate) FROM SchedulePeriodPrevCurr)
	AND		S_Shifts.OUId = @OUId
	AND		(S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId  IS NULL)
	AND		S_Shifts.EmployeeId = @EmployeeId
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetShiftsForRecommendedResources')
	DROP PROC prJ_GetShiftsForRecommendedResources
GO

----------------------------------------------------------------------------
-- Retrieve All Shifts By Start And End Date Time
-- For Recommended Resources
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsForRecommendedResources
	@OUId			BigInt,
	@ShiftStartTime	DateTime,
	@ShiftEndTime	DateTime
AS

-- Retrieve Shifts Between Selected Shift Band Start And End Time
SELECT	S_Shifts.ShiftId,
		S_Shifts.EmployeeId,
		S_Shifts.OUId,
		C_EmployeeRoles.RoleId PrimaryRoleId,
		D_Roles.RoleName PrimaryRoleName,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName
FROM	S_Shifts WITH (NOLOCK)
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1 
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
AND		(ActualEndTime >= CONVERT(DATETIME, @ShiftStartTime) 
AND		ActualStartTime < CONVERT(DATETIME, @ShiftEndTime))
AND		S_Shifts.OUId = @OUId
AND		C_Employee.ActiveStatus = 1

-- Retrieve Activities Between Selected Shift Band Start And End Time
SELECT	J_Activity.ActivityId,
		J_Activity.OUId,
		J_Activity.SkillId,
		J_Activity.ShiftBandId,
		J_Activity.ShiftId,
		J_Activity.StartTime,
		J_Activity.EndTime,
		J_Activity.WorkType
FROM	J_Activity WITH (NOLOCK)
WHERE	J_Activity.OUId = @OUId
AND		(EndTime >= CONVERT(DATETIME, @ShiftStartTime) AND	StartTime < CONVERT(DATETIME, @ShiftEndTime))

-- Retrieve Employee Skills By Selected OU
SELECT	C_EmployeeSkills.*
FROM	C_EmployeeSkills WITH (NOLOCK) INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId 
WHERE	C_Employee.OUId = @OUId

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetShiftsBySchedulePeriod')
	DROP PROC prJ_GetShiftsBySchedulePeriod
GO

----------------------------------------------------------------------------
-- Retrieve Shifts Between Schedule Periods By Date And OU
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsBySchedulePeriod
	@OuId			BigInt,
	@ShiftDate		Date,
	@FilterValue	nVarchar(100)
AS	
	-- 1. Retrieve Schedule Period By Current Date And OUID
	SELECT	*
	FROM	S_SchedulePeriod WITH (NOLOCK)
	WHERE	(OUId		=	@OuId OR @OuId = 0)
	AND		Convert(Date,@ShiftDate) >= Convert(Date,StartDate)
	AND		Convert(Date,@ShiftDate) <= Convert(Date,EndDate)

	-- 2. Retrieve List Of Employees Between Min And Max Dates Of Schedule Period
	;WITH SchedulePeriods (StartDate, EndDate) AS 
	(
		SELECT	Min(StartDate) StartDate, Max(EndDate) EndDate
		FROM	S_SchedulePeriod WITH (NOLOCK)
		WHERE	(OUId		=	@OuId OR @OuId = 0)
		AND		Convert(Date,@ShiftDate) >= Convert(Date,StartDate)
		AND		Convert(Date,@ShiftDate) <= Convert(Date,EndDate)
	) 
	SELECT	ShiftId, C_Employee.EmployeeId,  C_Employee.ScheduleRuleId, S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
	WHERE	(S_Shifts.OUId		=	@OuId OR @OuId = 0)
	AND		Convert(Date,ActualStartTime) >= (SELECT StartDate FROM SchedulePeriods)
	AND		Convert(Date,ActualEndTime) <= (SELECT EndDate FROM SchedulePeriods)
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)		
	AND		(D_EmploymentBasis.EmploymentBasisCode IN (SELECT * FROM fnStringToTable(@FilterValue)) OR @FilterValue = '')
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetShiftsForAllocation')
	DROP PROC prJ_GetShiftsForAllocation
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsForAllocation
	@OUId bigint,
	@ShiftBandId bigint,	
	@ShiftDate Date
AS

	-- Retrieve Available Shifts For Deployment Process
	select s_shifts.OUId,s_shifts.Employeeid,s_shifts.ShiftId,D_RoleSkill.SkillId,C_EmployeeRoles.IsPrimaryRole,
	C_Employee.EmployeeNumber,C_Employee.ContractedHours,C_Employee.EmploymentBasisId, 
	case
	when D_Roles.PrimarySkillId = D_RoleSkill.SkillId then Convert(bit,1) else Convert(bit,0) end PrimarySkill,
	D_RoleSkill.RoleId, IsNull(D_Roles.RolePrioritySeq,0) RolePrioritySeq
	 from s_shifts WITH (NOLOCK)
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.Employeeid= s_shifts.Employeeid
	inner join D_RoleSkill WITH (NOLOCK) on D_RoleSkill.RoleId = C_EmployeeRoles.RoleId
	inner join d_Roles WITH (NOLOCK) on d_roles.RoleId = D_RoleSkill.Roleid
	inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = s_shifts.EmployeeId
	where ShiftBandId = @ShiftBandId
	 --and s_shifts.employeeid=419
	and CONVERT(date, ShiftStartTime) = CONVERT(date, @ShiftDate)
	AND S_Shifts.OUId = @OUId
	and s_shifts.ShiftId not in (select shiftid from J_Activity WITH (NOLOCK) where (shiftid is not null and shiftid != 0 ))
	AND S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM S_EmployeeLeaves  WITH (NOLOCK)
						   WHERE Convert(Date,@ShiftDate) = Convert(Date,FromDate) 
						   AND S_EmployeeLeaves.OUId = @OUId) 
	order by C_Employee.EmployeeNumber


	-- Retrieve THP Period Start And End Date For Selected Shift Date
	SELECT	PeriodStart, PeriodEnd, EmployeeId 
	FROM	S_THPEmployeePeriods WITH (NOLOCK)
	WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate

	-- Retrieve Shift And Activity Counters Between Selected Shift Date
	SELECT	SUM(ShiftCounter) ShiftCounter, SUM(ActivityCounter) ActivityCounter, EmployeeId 	 
	FROM	S_THPEmployeeDetails WITH (NOLOCK)
	WHERE	CONVERT(date,ShiftDate) >= (SELECT	TOP 1 PeriodStart FROM	S_THPEmployeePeriods
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate)
	AND		CONVERT(date,ShiftDate) <= (SELECT	TOP 1 PeriodEnd FROM	S_THPEmployeePeriods
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate)
	GROUP BY EmployeeId


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetShiftsForDeAllocation')
	DROP PROC prJ_GetShiftsForDeAllocation
GO

----------------------------------------------------------------------------
-- Retrieve Only Shift Ids Which are required for Deallocation, Will be used for Audit
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsForDeAllocation
	@StartTime		DateTime,
	@EndTime		DateTime,
	@OUId			BigInt
	
AS
BEGIN
	SELECT	ShiftId 
	From	S_Shifts WITH (NOLOCK)
	WHERE	CombinationShiftId IS NOT NULL
	AND		ActualStartTime		=	@StartTime
	AND		ActualEndTime		=	@EndTime
	AND		OUId				=	@OUId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetShiftsForRecommendedResources')
	DROP PROC prJ_GetShiftsForRecommendedResources
GO

----------------------------------------------------------------------------
-- Retrieve All Shifts By Start And End Date Time
-- For Recommended Resources
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsForRecommendedResources
	@OUId			BigInt,
	@ShiftStartTime	DateTime,
	@ShiftEndTime	DateTime,
	@ShiftBandId	BigInt
AS

-- Retrieve Shifts Between Selected Shift Band Start And End Time
SELECT	S_Shifts.ShiftId,	
		D_ShiftBand.ShiftBandName,
		S_Shifts.EmployeeId,
		S_Shifts.OUId,
		C_EmployeeRoles.RoleId PrimaryRoleId,
		D_Roles.RoleName PrimaryRoleName,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		C_Employee.ContractedHours,
		C_EmployeeSkills.SkillId PrimarySkillId,
		C_EmployeeSkills.IsPrimary IsPrimarySkill,
		D_Skill.Skill PrimarySkillName,
		S_Shifts.ActualStartTime ShiftStartTime,
		S_Shifts.ActualEndTime ShiftEndTime
FROM	S_Shifts WITH (NOLOCK)
		INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1 
		INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId AND C_EmployeeSkills.IsPrimary = 1
		INNER JOIN D_Skill WITH (NOLOCK) ON D_SKill.SkillId = C_EmployeeSkills.SkillId
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
WHERE	(ShiftEndTime >= CONVERT(DATETIME, @ShiftStartTime) 
AND		ShiftStartTime <= CONVERT(DATETIME, @ShiftEndTime)) -- OR S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId)
AND		(S_Shifts.ShiftBandId	=	@ShiftBandId OR @ShiftBandId = 0)
AND		S_Shifts.OUId = @OUId
AND		C_Employee.ActiveStatus = 1
AND		SHIFTID NOT IN (SELECT SHIFTID FROM S_EmployeeLeaves Where ShiftId Is Not Null)
UNION ALL
SELECT	S_Shifts.ShiftId,	
		D_ShiftBand.ShiftBandName,
		S_Shifts.EmployeeId,
		S_Shifts.OUId,
		C_EmployeeRoles.RoleId PrimaryRoleId,
		D_Roles.RoleName PrimaryRoleName,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		C_Employee.ContractedHours,
		C_EmployeeSkills.SkillId PrimarySkillId,
		C_EmployeeSkills.IsPrimary IsPrimarySkill,
		D_Skill.Skill PrimarySkillName,
		S_Shifts.ActualStartTime ShiftStartTime,
		S_Shifts.ActualEndTime ShiftEndTime
FROM	S_Shifts WITH (NOLOCK)
		INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1 
		INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId AND C_EmployeeSkills.IsPrimary = 1
		INNER JOIN D_Skill WITH (NOLOCK) ON D_SKill.SkillId = C_EmployeeSkills.SkillId
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
WHERE	Convert(Date,ShiftStartTime) = CONVERT(DATE, @ShiftStartTime) 
AND		S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId
AND		S_Shifts.OUId = @OUId
AND		C_Employee.ActiveStatus = 1
AND		SHIFTID NOT IN (SELECT SHIFTID FROM S_EmployeeLeaves Where ShiftId Is Not Null)

-- Retrieve Activities Between Selected Shift Band Start And End Time
SELECT	J_Activity.ActivityId,
		J_Activity.OUId,
		J_Activity.SkillId,
		J_Activity.ShiftBandId,
		J_Activity.ShiftId,
		J_Activity.StartTime,
		J_Activity.EndTime,
		J_Activity.WorkType
FROM	J_Activity WITH (NOLOCK)
WHERE	J_Activity.OUId = @OUId
AND		(EndTime >= CONVERT(DATETIME, @ShiftStartTime) AND	StartTime <= CONVERT(DATETIME, @ShiftEndTime))
AND		(J_Activity.ShiftBandId	=	@ShiftBandId OR @ShiftBandId = 0)

-- Retrieve Employee Skills By Selected OU
SELECT	C_EmployeeSkills.*
FROM	C_EmployeeSkills WITH (NOLOCK) INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId 
WHERE	C_Employee.OUId = @OUId

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetSkillSeqByAllocationTemplateId')
	DROP PROC prJ_GetSkillSeqByAllocationTemplateId
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_GetSkillSeqByAllocationTemplateId
	@AllocationRuleId bigint
	
	

AS

select D_Skill.SkillId,SkillDesc SkillCode 
from J_AllocationRuleSkillPriority WITH (NOLOCK)
inner join D_Skill WITH (NOLOCK) on D_Skill.SkillId= J_AllocationRuleSkillPriority.SkillId
where AllocationRuleId=@AllocationRuleId
order by PrioritySeq

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetSliceSeq')
	DROP PROC prJ_GetSliceSeq
GO

----------------------------------------------------------------------------
-- Get All Records From J_SliceSeq
----------------------------------------------------------------------------
CREATE PROC prJ_GetSliceSeq
AS

SELECT  J_SliceSeq.SliceId,
		J_SliceSeq.ActHour ActivityHour,
		J_SliceSeq.ActivityNo,
		J_SliceSeq.RatioId,
		J_SliceSeq.Seq,
		J_SliceSeq.AllocationNo
FROM	J_SliceSeq WITH (NOLOCK)
ORDER BY J_SliceSeq.Seq

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetSliceSeqByEmployee')
	DROP PROC prJ_GetSliceSeqByEmployee
GO

----------------------------------------------------------------------------
-- Select a single record from J_SliceSeq
----------------------------------------------------------------------------
CREATE PROC prJ_GetSliceSeqByEmployee
	@Employee bigint,
	@Activity bigInt,
	@ShiftHour bigint
AS

SELECT	
	ActivityNo,
	Seq,
	ActHour
FROM	J_SliceSeq WITH (NOLOCK)
inner join J_ManningRatio WITH (NOLOCK) on J_ManningRatio.RatioId = J_SliceSeq.RatioId
WHERE 	J_ManningRatio.Employee=@Employee
and J_ManningRatio.Activity=@Activity
and J_ManningRatio.ShiftHour=@ShiftHour

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetWorkloadByCraneScheduleId')
	DROP PROC prJ_GetWorkloadByCraneScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkloadByCraneScheduleId
	@CraneScheduleId bigint
AS

SELECT	WorkloadId,
		OUId,
		SkillId,
		StartTime,
		EndTime,
		WorkType,
		CraneScheduleId,
		EquipmentScheduleId,
		ShiftBandId,
		ScheduleId,
		Imported,
		WorkloadGenerated,
		SignOffStatus,
		CreatedDate,
		CreatedBy,
		UpdatedBy,
		UpdatedDate
FROM	J_Workload WITH (NOLOCK)
WHERE 	CraneScheduleId = @CraneScheduleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetWorkloadByDateRange')
	DROP PROC prJ_GetWorkloadByDateRange
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkloadByDateRange
	@OUId		BigInt,
	@StartDate	DateTime,
	@EndDate	DateTime
AS

SELECT	WorkloadId,
		OUId,
		J_Workload.SkillId,
		StartTime,
		EndTime,
		WorkType,
		CraneScheduleId,
		EquipmentScheduleId,
		ShiftBandId,
		ScheduleId,
		Imported,
		WorkloadGenerated,
		SignOffStatus,
		J_Workload.CreatedDate,
		J_Workload.CreatedBy,
		J_Workload.UpdatedBy,
		J_Workload.UpdatedDate
FROM	J_Workload WITH (NOLOCK)  
WHERE 	OUId = @OUId AND (EndTime >= CONVERT(DATETIME, @StartDate) AND	StartTime < CONVERT(DATETIME, @EndDate))

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetWorkloadByEquipmentScheduleId')
	DROP PROC prJ_GetWorkloadByEquipmentScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkloadByEquipmentScheduleId
	@EquipmentScheduleId bigint
AS

SELECT	WorkloadId,
	OUId,
	SkillId,
	StartTime,
	EndTime,
	WorkType,
	CraneScheduleId,
	EquipmentScheduleId,
	ShiftBandId,
	ScheduleId,
	Imported,
	WorkloadGenerated,
	SignOffStatus,
	CreatedDate,
	CreatedBy,
	UpdatedBy,
	UpdatedDate
FROM	J_Workload WITH (NOLOCK)
WHERE 	EquipmentScheduleId = @EquipmentScheduleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetWorkloadByScheduleId')
	DROP PROC prJ_GetWorkloadByScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkloadByScheduleId
	@ScheduleId bigint
AS

SELECT	WorkloadId,
	OUId,
	SkillId,
	StartTime,
	EndTime,
	WorkType,
	CraneScheduleId,
	EquipmentScheduleId,
	ShiftBandId,
	ScheduleId,
	Imported,
	WorkloadGenerated,
	SignOffStatus,
	CreatedDate,
	CreatedBy,
	UpdatedBy,
	UpdatedDate
FROM	J_Workload WITH (NOLOCK)
WHERE 	ScheduleId = @ScheduleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateActivity')
	DROP PROC prJ_UpdateActivity
GO

----------------------------------------------------------------------------
-- Update a single record into J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_UpdateActivity]
	@ActivityId	BigInt = Null,
	@OUId bigint = NULL,
	@SkillId bigint = NULL,
	@ShiftBandId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@WorkType int = NULL,
	@ScheduleId bigint = NULL,
	@AttributeId int,
	@ShiftId bigint = NULL,
	@RuleId bigint = NULL,
	@GroupNo int = NULL,
	@AllocationNo int = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@ProgressionState Int = 0,
	@WorkloadId			BigInt = 0
AS


UPDATE	J_Activity	
SET		OUId				=	@OUId, 
		SkillId				=	@SkillId, 
		ShiftBandId			=	@ShiftBandId,
		StartTime			=	@StartTime, 
		EndTime				=	@EndTime, 
		WorkType			=	@WorkType,   
		ShiftId				=	@ShiftId, 
		RuleId				=	@RuleId, 
		GroupNo				=	@GroupNo, 
		AllocationNo		=	@AllocationNo, 
		UpdatedBy			=	@UpdatedBy, 
		UpdatedDate			=	GETDATE(), 
		ProgresstionState	=	@ProgressionState,
		WorkloadId			=	@WorkloadId
WHERE	ActivityId			=	@ActivityId

UPDATE	J_ActivityAttributes
SET		ScheduleId			=	@ScheduleId,
		UpdatedBy			=	@UpdatedBy,
		UpdatedDate			=	GETDATE()
WHERE	ActivityId			=	@ActivityId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateActivityForUnAllocation')
	DROP PROC prJ_UpdateActivityForUnAllocation
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_UpdateActivityForUnAllocation]
	@OUId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@UpdatedBy nvarchar(50),
	@ShiftBandId	BigInt
	
AS
UPDATE	J_Activity
SET	
	ShiftId = 0,
	ProgresstionState = 2,
	DeployedDate = null,
	DeployedUser = null,	
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	ProgresstionState=3 and shiftid>0
and  ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
AND		ShiftBandId = @ShiftBandId
and OUId=@OUId

UPDATE	S_Shifts
SET		ShiftBandId			=	CombinationShiftId,
		ActualStartTime		=	Convert(Date,@StartTime),
		ActualEndTime		=	Convert(Date,@StartTime),
		OTStartTime			=	Convert(Date,@StartTime),
		OTEndTime			=	Convert(Date,@StartTime),
		ShiftStartTime		=	Convert(Date,@StartTime),
		ShiftEndTime		=	Convert(Date,@StartTime),
		UpdatedBy			=	@UpdatedBy,
		UpdatedDate			=	GETDATE()
WHERE	CombinationShiftId IS NOT NULL
AND		ActualStartTime		= @StartTime
AND		ActualEndTime		= @EndTime
AND		OUId				=	@OUId
select 1

go


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateActivityForUnAllocationByShiftId')
	DROP PROC prJ_UpdateActivityForUnAllocationByShiftId
GO

----------------------------------------------------------------------------
-- Update a single record in prJ_UpdateActivityForUnAllocationByShiftId
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_UpdateActivityForUnAllocationByShiftId]
	@ShiftId	BigInt,
	@UpdatedBy	nVarchar(50)
AS
UPDATE	J_Activity
SET	
	ShiftId = NULL,
	ProgresstionState = 2,
	DeployedDate = null,
	DeployedUser = null,	
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE ShiftId = @ShiftId

UPDATE	S_Shifts
SET		ShiftBandId =	CombinationShiftId,
		UpdatedBy	=	@UpdatedBy,
		UpdatedDate	=	GETDATE()
WHERE	CombinationShiftId IS NOT NULL
AND		ShiftId = @ShiftId

SELECT 1

GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateActivityShiftIdByActivityId')
	DROP PROC prJ_UpdateActivityShiftIdByActivityId
GO

----------------------------------------------------------------------------
-- Update a single record in J_Activity
----------------------------------------------------------------------------
CREATE PROC prJ_UpdateActivityShiftIdByActivityId
	@ActivityId bigint,	
	@ShiftId bigint = NULL,	
	@ShiftBandId	BigInt,
	@StartTime		DateTime,
	@EndTime		DateTime,
	@UpdatedBy nvarchar(100) = NULL
AS

UPDATE	J_Activity
SET		ShiftId				=	@ShiftId,
		ProgresstionState	=	3,
		DeployedDate		=	GETDATE(),
		DeployedUser		=	@UpdatedBy,	
		UpdatedBy			=	@UpdatedBy,
		UpdatedDate			=	GETDATE()
WHERE 	ActivityId			=	@ActivityId

If (@ShiftBandId != 0)
BEGIN
	UPDATE	S_Shifts
	SET		ShiftBandId			=	@ShiftBandId,
			ActualStartTime		=	@StartTime,
			ActualEndTime		=	@EndTime,
			OTStartTime			=	@StartTime,
			OTEndTime			=	@EndTime,
			ShiftStartTime		=	@StartTime,
			ShiftEndTime		=	@EndTime,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	ShiftId				=	@ShiftId
	AND		CombinationShiftId	IS NOT NULL
END

select @ShiftId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateAsOnCallShift')
	DROP PROC prJ_UpdateAsOnCallShift
GO

----------------------------------------------------------------------------
-- Update Shift As On Call Shift
----------------------------------------------------------------------------
CREATE PROC prJ_UpdateAsOnCallShift
	@ShiftId		BigInt,
	@UpdatedBy		nVarchar(50)
AS	
	UPDATE	S_Shifts
	SET		OnCallShift =	1,
			ReconTime					=	Null,
			Reconciled					=	0,
			ReconStatusId				=	null,
			ReconFailureReasonId		=	NULL,
			ReconFailureReasonDetail	=	NULL,
			RPGId						=	NULL,
			ActualStartTime				=	ShiftStartTime,
			ActualEndTime				=	ShiftEndTime,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate =	GETDATE()
	WHERE	ShiftId		=	@ShiftId

	SELECT 1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateShiftIdByActivityId')
	DROP PROC prJ_UpdateShiftIdByActivityId
GO

----------------------------------------------------------------------------
-- Update Activity Shift Id based on activity swap records
----------------------------------------------------------------------------
CREATE PROC prJ_UpdateShiftIdByActivityId
	@ActivityId	BigInt,
	@ShiftId	BigInt,
	@UpdatedBy	nVarchar(50)
AS

	UPDATE	J_Activity
	SET		ShiftId		=	@ShiftId,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GETDATE()
	WHERE	ActivityId	=	@ActivityId

	SELECT 1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateShiftToFlexByShiftId')
	DROP PROC prJ_UpdateShiftToFlexByShiftId
GO

----------------------------------------------------------------------------
-- Update a single record in S_Shifts
----------------------------------------------------------------------------
CREATE PROCEDURE prJ_UpdateShiftToFlexByShiftId
	@ShiftId	BigInt,
	@ShiftDate	DateTime,
	@UpdatedBy	nVarchar(50)
AS
	UPDATE	S_Shifts
	SET		ShiftBandId =	CombinationShiftId,
			ActualStartTime		=	Convert(Date,@ShiftDate),
			ActualEndTime		=	Convert(Date,@ShiftDate),
			OTStartTime			=	Convert(Date,@ShiftDate),
			OTEndTime			=	Convert(Date,@ShiftDate),
			ShiftStartTime		=	Convert(Date,@ShiftDate),
			ShiftEndTime		=	Convert(Date,@ShiftDate),
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GETDATE()
	WHERE	CombinationShiftId IS NOT NULL
	AND		ShiftId = @ShiftId

	SELECT 1
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateWorkloadByWorkLoadId')
	DROP PROC prJ_UpdateWorkloadByWorkLoadId
GO

----------------------------------------------------------------------------
-- Update a single record in J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_UpdateWorkloadByWorkLoadId
	@WorkloadId bigint,
	@OUId bigint = NULL,
	@SkillId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@WorkType int = NULL,
	@CraneScheduleId bigint = NULL,
	@EquipmentScheduleId bigint = NULL,
	@VesselScheduleId	BigInt = NULL,
	@ShiftBandId bigint = NULL,
	@ScheduleId bigint = NULL,
	@Imported bit = NULL,
	@WorkloadGenerated bit = NULL,
	@SignOffStatus bit = NULL,	
	@UpdatedBy nvarchar(100) = NULL
AS

	UPDATE	J_Workload
	SET	OUId = @OUId,
		SkillId = @SkillId,
		StartTime = @StartTime,
		EndTime = @EndTime,
		WorkType = COALESCE(@WorkType, (0)),
		CraneScheduleId = @CraneScheduleId,
		EquipmentScheduleId = @EquipmentScheduleId,
		VesselScheduleId = @VesselScheduleId,
		ShiftBandId = @ShiftBandId,
		ScheduleId = @ScheduleId,
		Imported = @Imported,
		WorkloadGenerated = @WorkloadGenerated,
		SignOffStatus = @SignOffStatus,
		UpdatedBy = @UpdatedBy
	WHERE 	WorkloadId = @WorkloadId

	SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddEmployeeLeaveProfile')
	DROP PROC prL_AddEmployeeLeaveProfile
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddEmployeeLeaveProfile
----------------------------------------------------------------------------
CREATE PROC prL_AddEmployeeLeaveProfile
(
	@EmployeeId				BigInt,
	@LeaveProfileHeaderId	BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	--@ActionDate				DateTime,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeeLeaveProfile
	(EmployeeId, LeaveProfileHeaderId, StartDate, EndDate, ActionDate, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @LeaveProfileHeaderId, @StartDate, @EndDate, GETDATE(), @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS bigint) 

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddEmployeeLeaveProfiles')
	DROP PROC prL_AddEmployeeLeaveProfiles
GO

----------------------------------------------------------------------------
-- Insert a single record into L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_AddEmployeeLeaveProfiles
	@EmployeeId bigint = NULL,
	@LeaveProfileId int = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@LeaveYear int = NULL,
	@ExceptionId bigint = NULL,
	@EntitlementDays decimal(18, 2) = NULL,
	@CarryForwardDays decimal(18, 2) = NULL,
	@EarnedDays decimal(18, 2) = NULL,
	@DaysUsed decimal(18, 2) = NULL,
	@AdjustDays decimal(18, 2) = NULL,
	@DaysLieu decimal(18, 2) = NULL,
	@UsedDays decimal(18, 2) = NULL,
	@BalanceDays decimal(18, 2) = NULL,
	@EarnedDays_Cal decimal(18, 2) = NULL,
	@EarnedDays_Adj decimal(18, 2) = NULL,
	@EarnedMonth int = NULL,
	@AdjustmentRemakrs text = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@CreatedDate datetime = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdatedDate datetime = NULL
AS

INSERT L_EmployeeLeaveProfiles(EmployeeId, LeaveProfileId, StartDate, EndDate, LeaveYear, ExceptionId, EntitlementDays, CarryForwardDays, EarnedDays, DaysUsed, AdjustDays, DaysLieu, UsedDays, BalanceDays, EarnedDays_Cal, EarnedDays_Adj, EarnedMonth, AdjustmentRemakrs, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate)
VALUES (@EmployeeId, @LeaveProfileId, @StartDate, @EndDate, @LeaveYear, @ExceptionId, @EntitlementDays, @CarryForwardDays, @EarnedDays, @DaysUsed, @AdjustDays, @DaysLieu, @UsedDays, @BalanceDays, @EarnedDays_Cal, @EarnedDays_Adj, @EarnedMonth, @AdjustmentRemakrs, @CreatedBy, @CreatedDate, @UpdatedBy, @UpdatedDate)

SELECT  CAST(@@Identity AS INTEGER)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddEmployeeWorkflowRoute')
	DROP PROC prL_AddEmployeeWorkflowRoute
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddEmployeeWorkflowRoute
----------------------------------------------------------------------------
CREATE PROC prL_AddEmployeeWorkflowRoute
(
	@EmployeeId				BigInt,
	@ModuleId				int,
	@RouteId				BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeeWorkflow
	(EmployeeId, ModuleId, RouteId, StartDate, EndDate, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @ModuleId, @RouteId, @StartDate, @EndDate, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS bigint) 

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeave')
	DROP PROC prL_AddLeave
GO

----------------------------------------------------------------------------
-- Insert a single record into L_Leaves
----------------------------------------------------------------------------
CREATE PROC prL_AddLeave
(
	@OuId				BigInt,
	@EmployeeId			BigInt,
	@ExceptionCodeId	BigInt,
	@LeaveStart			DateTime,
	@LeaveEnd			DateTime,
	@LeaveType			Int,
	@NoOfDays			Decimal(18,2),
	@ReasonId			Int,
	@IsEmergency		Bit,
	@ApprovalStatusId	Int,
	@ReferenceNo		nVarchar(50),
	@Remarks			text,
	@AppliedBy			nVarchar(50),
	@AppliedDate		DateTime,
	@ApprovedBy			nVarchar(50),
	@ApprovedDate		DateTime,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	--TODO: This is Temporary Solution. Required To Find Root Cause of Why Some Employees Leaves Inserted with OUId = 0 ???
	If (@OuId = 0) SELECT @OuId = OUId From C_Employee WITH (NOLOCK) WHERE EmployeeId = @EmployeeId

	INSERT INTO L_Leaves
	(OUId, EmployeeId, ExceptionCodeId, LeaveStart, LeaveEnd, LeaveType, NoOfDays, ReasonId, IsEmergency, ApprovalStatusId,
	 ReferenceNo, Remarks, AppliedBy, AppliedDate, ApprovedBy, ApprovedDate, CreatedBy, CreatedDate)
	VALUES(@OuId, @EmployeeId, @ExceptionCodeId, @LeaveStart, @LeaveEnd, @LeaveType, @NoOfDays, @ReasonId, @IsEmergency, @ApprovalStatusId,
			@ReferenceNo, @Remarks, @AppliedBy, @AppliedDate, @ApprovedBy, @ApprovedDate, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS bigint) 
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeaveBalanceAudit')
	DROP PROC prL_AddLeaveBalanceAudit
GO

----------------------------------------------------------------------------
-- Insert a single record into L_LeaveBalanceAudit
----------------------------------------------------------------------------
CREATE PROC prL_AddLeaveBalanceAudit
	@ActionDate datetime = NULL,
	@ReferenceNo nvarchar(100) = NULL,
	@EmployeeId bigint = NULL,
	@ExceptionCodeId bigint = NULL,
	@LeaveStart datetime = NULL,
	@LeaveEnd datetime = NULL,
	@ActionCode nvarchar(100) = NULL,
	@ActionDesc nvarchar(2000) = NULL,
	@NoOfDays decimal(18, 2) = NULL,
	@EntitlementDays decimal(18, 2) = NULL,
	@CarryForwardDays decimal(18, 2) = NULL,
	@EarnedDays decimal(18, 2) = NULL,
	@DaysUsed decimal(18, 2) = NULL,
	@BalanceDays decimal(18, 2) = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@CreatedDate datetime = NULL
AS

INSERT L_LeaveBalanceAudit(ActionDate, ReferenceNo, EmployeeId, ExceptionCodeId, LeaveStart, LeaveEnd, ActionCode, ActionDesc, NoOfDays, EntitlementDays, CarryForwardDays, EarnedDays, DaysUsed, BalanceDays, CreatedBy, CreatedDate)
VALUES (@ActionDate, @ReferenceNo, @EmployeeId, @ExceptionCodeId, @LeaveStart, @LeaveEnd, @ActionCode, @ActionDesc, @NoOfDays, @EntitlementDays, @CarryForwardDays, @EarnedDays, @DaysUsed, @BalanceDays, @CreatedBy, @CreatedDate)

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeaveProfile')
	DROP PROC prL_AddLeaveProfile
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddLeaveProfile
----------------------------------------------------------------------------
CREATE PROC prL_AddLeaveProfile
(
	@LeaveProfileHeaderId	Int,
	@ExceptionCodeId		BigInt			=	NULL,
	@EntitlementDays		Decimal(18,2),
	@CarryForward			Bit,
	@MaximumDaysPerYear		Decimal(18,2),
	@Accural				Bit,
	@CarryForwardDateType	Int,
	@CarryForwardDate		DateTime,
	@DayCalculation			Int,
	@DaysInAdvance			Decimal(18,2),
	@MinimumDaysRequest		Decimal(18,2),
	@MaximumDaysRequest		Decimal(18,2),
	@RequestPerYear			Int,
	@NegativeBalance		Bit,
	@MaximumDaysNegative	Decimal(18,2),
	@HalfDays				Bit,
	@ActiveStatus			Bit,
	@CreatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	L_LeaveProfiles WITH (NOLOCK)
	WHERE	ExceptionCodeId	= @ExceptionCodeId
	AND		LeaveProfileHeaderId = @LeaveProfileHeaderId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO L_LeaveProfiles
		(LeaveProfileHeaderId, ExceptionCodeId, EntitlementDays, CarryForward, MaximumDaysPerYear, Accural,
		 CarryforwardDateType, CarryforwardDate, DayCalculation, DaysInAdvance, MinimumDaysRequest, 
		 MaximumDaysRequest, RequestPerYear, NegativeBalance, MaximumDaysNegative,
		 HalfDays, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@LeaveProfileHeaderId, @ExceptionCodeId, @EntitlementDays, @CarryForward, @MaximumDaysPerYear, @Accural,
			   @CarryForwardDateType, @CarryForwardDate, @DayCalculation, @DaysInAdvance, @MinimumDaysRequest,
			   @MaximumDaysRequest, @RequestPerYear, @NegativeBalance, @MaximumDaysNegative, @HalfDays, 
			   @ActiveStatus, @CreatedBy, GETDATE())

		SELECT  CAST(@@Identity AS bigint) 
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeaveProfileHeader')
	DROP PROC prL_AddLeaveProfileHeader
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddLeaveProfileHeader
----------------------------------------------------------------------------
CREATE PROC prL_AddLeaveProfileHeader
(
	@LeaveProfileName		nVarchar(50),
	@Remarks				nVarchar(1000),
	@ActiveStatus			Bit,
	@CreatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	L_LeaveProfileHeader WITH (NOLOCK)
	WHERE	ProfileName	= @LeaveProfileName

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO L_LeaveProfileHeader
		(ProfileName, Remarks, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@LeaveProfileName, @Remarks, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT  CAST(@@Identity AS int) 
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeaveProfileOU')
	DROP PROC prL_AddLeaveProfileOU
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddLeaveProfileOU
----------------------------------------------------------------------------
CREATE PROC prL_AddLeaveProfileOU
(
	@LeaveProfileHeaderId	Int,
	@OUId					BigInt,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN

	INSERT INTO L_LeaveProfileOU
	(LeaveProfileHeaderId, OUId, CreatedBy, CreatedDate)
	VALUES(@LeaveProfileHeaderId, @OUId, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS int) 
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddLeaveThreshold')
	DROP PROC prL_AddLeaveThreshold
GO

----------------------------------------------------------------------------
-- Insert a single record into L_LeaveThreshold
----------------------------------------------------------------------------
CREATE PROC prL_AddLeaveThreshold
	@RosterGroupId bigint = NULL,
	@RoleGroupId bigint = NULL,
	@ExceptionCodeId bigint = NULL,
	@ThresholdValue decimal(18, 5) = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT L_LeaveThreshold(RosterGroupId, RoleGroupId, ExceptionCodeId, ThresholdValue, CreatedBy, CreatedDate)
VALUES (@RosterGroupId, @RoleGroupId, @ExceptionCodeId, @ThresholdValue, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddPublicHolidayProcessAudit')
	DROP PROC prL_AddPublicHolidayProcessAudit
GO

----------------------------------------------------------------------------
-- Insert a single record into L_PublicHolidayProcessAudit
----------------------------------------------------------------------------
CREATE PROC prL_AddPublicHolidayProcessAudit
	@PublicHolidayId bigint = NULL,
	@ProcessDate datetime = NULL,
	@EmployeeId int = NULL,
	@ActionType int = NULL,
	@ActionCode nvarchar(100) = NULL,
	@ActionDesc nvarchar(200) = NULL,
	@ActionLog text = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@CreatedDate datetime = NULL
AS

INSERT L_PublicHolidayProcessAudit(PublicHolidayId, ProcessDate, EmployeeId, ActionType, ActionCode, ActionDesc, ActionLog, CreatedBy, CreatedDate)
VALUES (@PublicHolidayId, @ProcessDate, @EmployeeId, @ActionType, @ActionCode, @ActionDesc, @ActionLog, @CreatedBy, @CreatedDate)

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddRequestDaysInLieu')
	DROP PROC prL_AddRequestDaysInLieu
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddRequestDaysInLieu
----------------------------------------------------------------------------
CREATE PROC prL_AddRequestDaysInLieu
(
	@EmployeeId			BigInt,
	@RequestedDate		DateTime,
	@Remarks			nVarchar(100),
	@ApprovalStatusId	Int,
	@ApproverId			BigInt,
	@AppliedDate		DateTime,
	@ApprovedDate		DateTime,
	@CreatedBy			nVarchar(50)
)
AS

BEGIN

	INSERT INTO L_RequestDaysInLieu
	(EmployeeId, RequestedDate, Remarks, ApprovalStatusId, ApproverId, AppliedDate, ApprovedDate, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @RequestedDate, @Remarks, @ApprovalStatusId, @ApproverId, @AppliedDate, @ApprovedDate, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS bigint) 
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_AddTimeOff')
	DROP PROC prL_AddTimeOff
GO

----------------------------------------------------------------------------
-- Insert a single record into L_TimeOff
----------------------------------------------------------------------------
CREATE PROC prL_AddTimeOff
(
	@EmployeeId			BigInt,
	@StartTime			DateTime,
	@Duration			Decimal(18,2),
	@BreakHours			Decimal(18,2),
	@Remarks			nVarchar(100),
	@ApprovalStatusId	Int,
	@ApproverId			BigInt,
	@AppliedDate		DateTime,
	@ApprovedDate		DateTime,
	@ShiftId			BigInt,
	@CreatedBy			nVarchar(50)
)
AS

BEGIN
	INSERT INTO L_TimeOff
	(EmployeeId, StartTime, Duration, BreakHours, Remarks, ApprovalStatusId, ApproverId, AppliedDate, ApprovedDate, 
	 ShiftId, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @StartTime, @Duration, @BreakHours, @Remarks, @ApprovalStatusId, @ApproverId, @AppliedDate, @ApprovedDate,
		   @ShiftId, @CreatedBy, GETDATE())
		
	SELECT  CAST(@@Identity AS bigint) 
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_ApproveRejectTransactionByTransRouteDetId')
	DROP PROC prL_ApproveRejectTransactionByTransRouteDetId
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_ApproveRejectTransactionByTransRouteDetId
----------------------------------------------------------------------------
CREATE PROC prL_ApproveRejectTransactionByTransRouteDetId
(
	@TransRouteDetId		BigInt,
	@ApproveRejectStatus	BigInt,
	@ApproveRejectRemarks	nVarchar(1000),
	@RequestTransId			BigInt,
	@ApprovalModuleId		Int,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @IsApproved Int = 0

	If(@ApprovalModuleId = 201)
	BEGIN
		SELECT	@IsApproved = COUNT(*) 
		FROM	L_Leaves WITH (NOLOCK)
		WHERE	L_Leaves.LeaveId	=	@RequestTransId
		And		L_Leaves.ApprovalStatusId IN (1, 2, 5, 7)
	END

	Else If (@ApprovalModuleId = 202)
	BEGIN
		SELECT	@IsApproved = COUNT(*) 
		FROM	L_RequestDaysInLieu WITH (NOLOCK)
		WHERE	L_RequestDaysInLieu.DaysInLieuId	=	@RequestTransId
		And		L_RequestDaysInLieu.ApprovalStatusId IN (1, 2, 5, 7)
	END
	Else If (@ApprovalModuleId = 203)
	BEGIN
		SELECT	@IsApproved = COUNT(*) 
		FROM	L_TimeOff WITH (NOLOCK)
		WHERE	L_TimeOff.TimeOffId	=	@RequestTransId
		And		L_TimeOff.ApprovalStatusId IN (1, 2, 5, 7)
	END

	If (@IsApproved = 0)
	BEGIN
		UPDATE	W_TRN_Approval_RouteDetails
		SET		UserAction		=	@ApproveRejectStatus,
				ActionDate		=	GETDATE(),
				Remarks			=	@ApproveRejectRemarks
		WHERE	TransRouteDetID	=	@TransRouteDetId

		SELECT  1
	END
	ELSE	SELECT 99
		
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_CancelLeave')
	DROP PROCEDURE prL_CancelLeave
GO

CREATE PROC prL_CancelLeave
(
	@LeaveId			BigInt,
	@ApprovalStatusId	Int,
	@UpdatedBy			nVarchar(50)
)
AS
	DECLARE @@TransRouteId	BigInt = 0
	SELECT	@@TransRouteId = TransRouteID
	FROM	W_TRN_ApprovalRoute 
	WHERE	RequestTransId	=	@LeaveId

	If (@@TransRouteId != 0)
	BEGIN
		DELETE	FROM W_TRN_Approval_RouteDetails
		WHERE	TransRouteID	=	@@TransRouteId

		DELETE	FROM W_TRN_ApprovalRoute
		WHERE	RequestTransId	=	@LeaveId

		UPDATE	S_Shifts
		SET		LeaveId			=	NULL
		WHERE	LeaveId			=	@LeaveId

		UPDATE	L_Leaves
		SET		ApprovalStatusId	=	@ApprovalStatusId,
				UpdatedBy			=	@UpdatedBy
		WHERE	LeaveId				=	@LeaveId
		
		SELECT 1
	END
	ELSE
	BEGIN
		UPDATE	L_Leaves
		SET		ApprovalStatusId	=	@ApprovalStatusId,
				UpdatedBy			=	@UpdatedBy
		WHERE	LeaveId				=	@LeaveId
		
		SELECT 1
	END	
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_CancelRequestDaysInLieu')
	DROP PROCEDURE prL_CancelRequestDaysInLieu
GO

CREATE PROC prL_CancelRequestDaysInLieu
(
	@RequestDaysInLieuId	BigInt,
	@ApprovalStatusId		Int,
	@WorkflowModuleId		Int
)
AS
	DECLARE @@TransRouteId	BigInt = 0
	SELECT	@@TransRouteId = TransRouteID
	FROM	W_TRN_ApprovalRoute 
	WHERE	RequestTransId		=	@RequestDaysInLieuId
	AND		ApprovalModuleID	=	@WorkflowModuleId

	If (@@TransRouteId != 0)
	BEGIN
		DELETE	FROM W_TRN_Approval_RouteDetails
		WHERE	TransRouteID	=	@@TransRouteId

		DELETE	FROM W_TRN_ApprovalRoute
		WHERE	RequestTransId		=	@RequestDaysInLieuId
		AND		ApprovalModuleID	=	@WorkflowModuleId
	END

	UPDATE	L_RequestDaysInLieu
	SET		ApprovalStatusId	=	@ApprovalStatusId
	WHERE	DaysInLieuId		=	@RequestDaysInLieuId


	SELECT	1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_CancelTimeOff')
	DROP PROCEDURE prL_CancelTimeOff
GO

CREATE PROC prL_CancelTimeOff
(
	@TimeOffId			BigInt,
	@ApprovalStatusId	Int,
	@UpdatedBy			nVarchar(50),
	@WorkflowModuleId	Int
)
AS
	DECLARE @@TransRouteId	BigInt = 0
	SELECT	@@TransRouteId = TransRouteID
	FROM	W_TRN_ApprovalRoute 
	WHERE	RequestTransId		=	@TimeOffId
	AND		ApprovalModuleID	=	@WorkflowModuleId

	If (@@TransRouteId != 0)
	BEGIN
		DELETE	FROM W_TRN_Approval_RouteDetails
		WHERE	TransRouteID	=	@@TransRouteId

		DELETE	FROM W_TRN_ApprovalRoute
		WHERE	RequestTransId		=	@TimeOffId
		AND		ApprovalModuleID	=	@WorkflowModuleId
	END

	UPDATE	L_TimeOff
	SET		ApprovalStatusId	=	@ApprovalStatusId
	WHERE	TimeOffId			=	@TimeOffId

	SELECT	1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_DeleteEmployeeLeaveProfile')
	DROP PROC prL_DeleteEmployeeLeaveProfile
GO

----------------------------------------------------------------------------
-- Delete Single Employee Leave Profile Record
----------------------------------------------------------------------------
CREATE PROC prL_DeleteEmployeeLeaveProfile
(
	@EmployeeLeaveProfileId	BigInt
)
AS
BEGIN
	
	DELETE FROM C_EmployeeLeaveProfile
	WHERE	EmployeeLeaveProfileId	= @EmployeeLeaveProfileId
	
	SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_DeleteEmployeeWorkflowRoute')
	DROP PROC prL_DeleteEmployeeWorkflowRoute
GO

----------------------------------------------------------------------------
-- Delete Single Employee Workflow Route Record
----------------------------------------------------------------------------
CREATE PROC prL_DeleteEmployeeWorkflowRoute
(
	@EmployeeWorkflowId	BigInt
)
AS
BEGIN
	
	DELETE FROM C_EmployeeWorkflow
	WHERE	EmployeeWorkflowId	= @EmployeeWorkflowId
	
	SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_DeleteLeaveProfile')
	DROP PROC prL_DeleteLeaveProfile
GO

----------------------------------------------------------------------------
-- Update a single record into prL_DeleteLeaveProfile
----------------------------------------------------------------------------
CREATE PROC prL_DeleteLeaveProfile
(
	@LeaveProfileId			BigInt
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	DELETE	FROM L_LeaveProfiles 
	WHERE	LeaveProfileId			=	@LeaveProfileId

	SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_DeleteLeaveProfileOU')
	DROP PROC prL_DeleteLeaveProfileOU
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_DeleteLeaveProfileOU
----------------------------------------------------------------------------
CREATE PROC prL_DeleteLeaveProfileOU
(
	@LeaveProfileHeaderId	Int,
	@OUId					BigInt
)
AS
BEGIN

	DELETE FROM L_LeaveProfileOU
	WHERE	L_LeaveProfileOU.LeaveProfileHeaderId = @LeaveProfileHeaderId 
	AND		L_LeaveProfileOU.OUId = @OUId

	SELECT  1
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetAllPendingLeaveRecords]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_GetAllPendingLeaveRecords]
GO
/****** Object:  StoredProcedure [dbo].[prL_GetAllPendingLeaveRecords]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_GetAllPendingLeaveRecords]    
AS
BEGIN
	SELECT	L_Leaves.LeaveId,
			L_Leaves.OUId,
			L_Leaves.EmployeeId,
			L_Leaves.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
			D_ExceptionCodes.ExceptionCodeDesc ExceptionDescription,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			L_Leaves.LeaveStart,
			L_Leaves.LeaveEnd,
			L_Leaves.LeaveType,
			L_Leaves.NoOfDays,
			L_Leaves.ReasonId,
			L_Leaves.IsEmergency,
			L_Leaves.ApprovalStatusId,
			W_ApprovalStatus.ApprovalStatus,
			W_ApprovalStatus.ApprovalStatusDesc,
			L_Leaves.ReferenceNo,
			L_Leaves.Remarks,
			L_Leaves.AppliedDate,
			L_Leaves.AppliedBy,
			L_Leaves.ApprovedBy,
			L_Leaves.ApprovedDate,
			C_OrganizationNode.OUName
	FROM	L_Leaves 
			INNER JOIN C_Employee ON C_Employee.EmployeeId = L_Leaves.EmployeeId
			INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
			INNER JOIN C_OrganizationNode ON C_OrganizationNode.OUId = L_Leaves.OUId
			LEFT OUTER JOIN W_ApprovalStatus ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
	WHERE	L_Leaves.ApprovalStatusId in (3,6)
	ORDER BY C_Employee.EmployeeNumber, L_Leaves.LeaveStart DESC
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetClinicLeaveRecords')
	DROP PROCEDURE prL_GetClinicLeaveRecords
GO
/****** Object:  StoredProcedure [dbo].[prL_GetClinicLeaveRecords]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE prL_GetClinicLeaveRecords    
(
	@ApprovalStatusId			Int,
	@LeaveCancellationAction	Int,
	@EmployeeId					BigInt,
	@ExceptionCodeId			BigInt
)
AS
DECLARE @clinicalLeaveIds nvarchar(100)
BEGIN
	SELECT @clinicalLeaveIds  = ParamValue FROM D_SystemParams Where ParamName='ClinicalPortalLeaveIds'

	If (@LeaveCancellationAction = 0)
	BEGIN
		SELECT	L_Leaves.LeaveId,
				L_Leaves.OUId,
				L_Leaves.EmployeeId,
				L_Leaves.ExceptionCodeId,
				D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
				D_ExceptionCodes.ExceptionCodeDesc ExceptionDescription,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_Employee.EmailAddress ApplicantEmailId,
				L_Leaves.LeaveStart,
				L_Leaves.LeaveEnd,
				L_Leaves.LeaveType,
				L_Leaves.NoOfDays,
				L_Leaves.ReasonId,
				L_Leaves.IsEmergency,
				L_Leaves.ApprovalStatusId,
				W_ApprovalStatus.ApprovalStatus,
				W_ApprovalStatus.ApprovalStatusDesc,
				L_Leaves.ReferenceNo,
				L_Leaves.Remarks,
				L_Leaves.AppliedDate,
				L_Leaves.AppliedBy,
				L_Leaves.ApprovedBy,
				L_Leaves.ApprovedDate
		FROM	L_Leaves 
				INNER JOIN C_Employee ON C_Employee.EmployeeId = L_Leaves.EmployeeId
				INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_OrganizationNode ON C_OrganizationNode.OUId = L_Leaves.OUId
				LEFT OUTER JOIN W_ApprovalStatus ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
		Where	L_Leaves.ExceptionCodeId in ( SELECT * FROM fnStringToTable(@clinicalLeaveIds))	
		--AND		Convert(Date,DATEADD(d,30,LeaveEnd)) >= Convert(Date,GETDATE())
		AND		L_Leaves.ApprovalStatusId = @ApprovalStatusId
		AND		(L_Leaves.EmployeeId = @EmployeeId OR @EmployeeId = 0)
		AND		(L_Leaves.ExceptionCodeId = @ExceptionCodeId OR @ExceptionCodeId = 0)
		ORDER BY L_Leaves.LeaveStart DESC
	END 
	ELSE
	BEGIN
		SELECT	L_Leaves.LeaveId,
				L_Leaves.OUId,
				L_Leaves.EmployeeId,
				L_Leaves.ExceptionCodeId,
				D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
				D_ExceptionCodes.ExceptionCodeDesc ExceptionDescription,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_Employee.EmailAddress ApplicantEmailId,
				L_Leaves.LeaveStart,
				L_Leaves.LeaveEnd,
				L_Leaves.LeaveType,
				L_Leaves.NoOfDays,
				L_Leaves.ReasonId,
				L_Leaves.IsEmergency,
				L_Leaves.ApprovalStatusId,
				W_ApprovalStatus.ApprovalStatus,
				W_ApprovalStatus.ApprovalStatusDesc,
				L_Leaves.ReferenceNo,
				L_Leaves.Remarks,
				L_Leaves.AppliedDate,
				L_Leaves.AppliedBy,
				L_Leaves.ApprovedBy,
				L_Leaves.ApprovedDate
		FROM	L_Leaves 
				INNER JOIN C_Employee ON C_Employee.EmployeeId = L_Leaves.EmployeeId
				INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_OrganizationNode ON C_OrganizationNode.OUId = L_Leaves.OUId
				LEFT OUTER JOIN W_ApprovalStatus ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
		Where	L_Leaves.ExceptionCodeId NOT IN ( SELECT * FROM fnStringToTable(@clinicalLeaveIds))	
		AND		Convert(Date,GETDATE()) >= Convert(Date,DATEADD(d,30,ApprovedDate))
		AND		L_Leaves.ApprovalStatusId = @ApprovalStatusId
		AND		(L_Leaves.EmployeeId = @EmployeeId OR @EmployeeId = 0)
		AND		(L_Leaves.ExceptionCodeId = @ExceptionCodeId OR @ExceptionCodeId = 0)
		ORDER BY L_Leaves.LeaveStart DESC
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetDaysInLieuByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_GetDaysInLieuByEmployeeId]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_GetDaysInLieuByEmployeeId]    
(
	@EmployeeId		BigInt
)
AS
BEGIN
	SELECT	L_RequestDaysInLieu.DaysInLieuId,
			L_RequestDaysInLieu.EmployeeId,
			L_RequestDaysInLieu.RequestedDate,
			L_RequestDaysInLieu.Remarks,
			L_RequestDaysInLieu.ApprovalStatusId,
			W_ApprovalStatus.ApprovalStatus,
			W_ApprovalStatus.ApprovalStatusDesc,
			L_RequestDaysInLieu.AppliedDate,
			L_RequestDaysInLieu.CreatedBy,
			L_RequestDaysInLieu.CreatedDate,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName
	FROM	L_RequestDaysInLieu
			INNER JOIN C_Employee ON C_Employee.EmployeeId = L_RequestDaysInLieu.EmployeeId
			INNER JOIN W_ApprovalStatus ON L_RequestDaysInLieu.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
	WHERE	(L_RequestDaysInLieu.EmployeeId = @EmployeeId OR @EmployeeId = 0)
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetDaysInLieuByEmployeeIdDate]') AND type in (N'P', N'PC'))
	DROP PROCEDURE prL_GetDaysInLieuByEmployeeIdDate
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE prL_GetDaysInLieuByEmployeeIdDate
(
	@EmployeeId		BigInt,
	@RequestedDate	Date
)
AS
BEGIN
	SELECT	L_RequestDaysInLieu.DaysInLieuId,
			L_RequestDaysInLieu.EmployeeId,
			L_RequestDaysInLieu.RequestedDate,
			L_RequestDaysInLieu.Remarks,
			L_RequestDaysInLieu.ApprovalStatusId,
			W_ApprovalStatus.ApprovalStatus,
			W_ApprovalStatus.ApprovalStatusDesc,
			L_RequestDaysInLieu.AppliedDate,
			L_RequestDaysInLieu.CreatedBy,
			L_RequestDaysInLieu.CreatedDate,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName
	FROM	L_RequestDaysInLieu WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_RequestDaysInLieu.EmployeeId
			INNER JOIN W_ApprovalStatus WITH (NOLOCK) ON L_RequestDaysInLieu.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
	WHERE	L_RequestDaysInLieu.EmployeeId	=	@EmployeeId
	AND		Convert(Date,RequestedDate)		=	Convert(Date,@RequestedDate)
	AND		L_RequestDaysInLieu.ApprovalStatusId IN (1,3,6)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveApplicationSummary')
	DROP PROC prL_GetEmployeeLeaveApplicationSummary
GO

CREATE PROC prL_GetEmployeeLeaveApplicationSummary
	@EmployeeId			Bigint,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ExceptionCodeId	BigInt,
	@EntitlementYear	Int,
	@PendingForApproval	Int,
	@ModuleId			Int
AS
BEGIN
	-- 1. Leave Profile For Balance
	SELECT	L_EmployeeLeaveProfiles.BalanceDays CurrentBalance
	FROM	L_EmployeeLeaveProfiles WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON L_EmployeeLeaveProfiles.EmployeeId = C_Employee.EmployeeId 
						AND C_Employee.ActiveStatus = 1
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId  
						AND D_ExceptionCodes.ActiveStatus = 1
			INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileId
						AND L_LeaveProfiles.ActiveStatus = 1
			INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON C_EmployeeLeaveProfile.EmployeeId = C_Employee.EmployeeId
	WHERE 	L_EmployeeLeaveProfiles.EmployeeId				=	@EmployeeId
	AND		L_EmployeeLeaveProfiles.LeaveYear				=	@EntitlementYear
	AND		L_EmployeeLeaveProfiles.ExceptionId				=	@ExceptionCodeId
	--AND		Convert(Date,L_EmployeeLeaveProfiles.EndDate)	>= Convert(Date,@StartDate)
	--AND		Convert(Date,L_EmployeeLeaveProfiles.StartDate) <= Convert(Date,@EndDate)

	--2 Get Public Holidays Between Leave Start And End
	SELECT Count(*) PublicHolidaysCount
	FROM	D_PublicHolidays WITH (NOLOCK)
	WHERE	Convert(Date,D_PublicHolidays.HolidayDate)	>= Convert(Date,@StartDate)
	AND		Convert(Date,D_PublicHolidays.HolidayDate) <= Convert(Date,@EndDate)

	--3 Get Shifts Between Leave Start And End
	SELECT	Count(*) ShiftsCount
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	Convert(Date,S_Shifts.ActualStartTime)	>= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.EmployeeId = @EmployeeId

	--4 Get Pending Leaves Between Leave Start And End
	SELECT	Count(*) PendingLeavesCount
	FROM	L_Leaves WITH (NOLOCK)
	WHERE	L_Leaves.ApprovalStatusId = @PendingForApproval
	AND		L_Leaves.EmployeeId = @EmployeeId
	AND		Year(L_Leaves.LeaveStart) = @EntitlementYear

	--5 Get Approvers List By Employee Leave Profile
	SELECT	W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.RouteLevel,
			W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.ApprovalRequirement,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			IsNull(C_Employee.EmailAddress,'') ApproverEmailId,
			C_EmployeeWorkflow.RouteId,
			C_EmployeeWorkflow.ModuleId
	FROM	W_WorkflowRouteDetails WITH (NOLOCK)
			INNER JOIN W_WorkflowRoute WITH (NOLOCK) ON W_WorkflowRouteDetails.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = W_WorkflowRouteDetails.EmployeeId
	WHERE	C_EmployeeWorkflow.EmployeeId = @EmployeeId
	AND		Convert(Date,C_EmployeeWorkflow.EndDate)   >= Convert(Date,@StartDate)
	AND		Convert(Date,C_EmployeeWorkflow.StartDate) <= Convert(Date,@EndDate)
	AND		C_EmployeeWorkflow.ModuleId = @ModuleId
	ORDER BY W_WorkflowRouteDetails.RouteLevel, W_WorkflowRouteDetails.RouteDetId

	-- 6 Retrieve L_EmployeeLeaveProfiles By Employee Id
	SELECT	L_EmployeeLeaveProfiles.EmpProfileId,
			L_EmployeeLeaveProfiles.EmployeeId,
			L_EmployeeLeaveProfiles.LeaveProfileId,
			L_EmployeeLeaveProfiles.StartDate,
			L_EmployeeLeaveProfiles.EndDate,
			L_EmployeeLeaveProfiles.LeaveYear,
			L_EmployeeLeaveProfiles.ExceptionId,
			L_EmployeeLeaveProfiles.EntitlementDays,
			L_EmployeeLeaveProfiles.CarryForwardDays,
			L_EmployeeLeaveProfiles.EarnedDays,
			L_EmployeeLeaveProfiles.DaysUsed,
			L_EmployeeLeaveProfiles.AdjustDays,
			L_EmployeeLeaveProfiles.DaysLieu,
			L_EmployeeLeaveProfiles.UsedDays,
			L_EmployeeLeaveProfiles.BalanceDays,
			L_EmployeeLeaveProfiles.EarnedDays_Adj,
			L_EmployeeLeaveProfiles.EarnedDays_Cal,
			L_EmployeeLeaveProfiles.EarnedMonth,
			C_Employee.HiredDate,
			L_LeaveProfiles.DayCalculation,
			L_Leaveprofiles.NegativeBalance,
			L_LeaveProfiles.MaximumDaysNegative,
			D_EmploymentBasis.EmploymentBasisId,
			D_EmploymentBasis.EmploymentBasisCode
	FROM	L_EmployeeLeaveProfiles WITH (NOLOCK) 
			INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfileHeader.LeaveProfileHeaderId
			INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_LeaveProfileHeader.LeaveProfileHeaderId = L_LeaveProfiles.LeaveProfileHeaderId
				AND L_EmployeeLeaveProfiles.ExceptionId = L_LeaveProfiles.ExceptionCodeId
			INNER JOIN C_Employee WITH (NOLOCK) ON L_EmployeeLeaveProfiles.EmployeeId = C_Employee.EmployeeId			
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
			INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON C_EmployeeLeaveProfile.EmployeeId = C_Employee.EmployeeId
	WHERE	L_EmployeeLeaveProfiles.EmployeeId	=	@EmployeeId
	AND		L_EmployeeLeaveProfiles.ExceptionId =	@ExceptionCodeId
	AND		L_EmployeeLeaveProfiles.LeaveYear	=	Year(GETDATE())
	--Convert(Date,L_EmployeeLeaveProfiles.EndDate)	>= Convert(Date,@StartDate)
	--AND		Convert(Date,L_EmployeeLeaveProfiles.StartDate) <= Convert(Date,@EndDate)
	--AND		

	-- 7 Retrieve Last Leave Of Current Applied Exception Code
	SELECT	TOP 1 *
	FROM	L_Leaves WITH (NOLOCK)
	WHERE	L_Leaves.ExceptionCodeId	=	@ExceptionCodeId
	AND		L_Leaves.EmployeeId			=	@EmployeeId
	AND		L_Leaves.ApprovalStatusId NOT IN (2,4,5) --[2 => Rejected, 4 => Cancel, 5 => Canceled (Cancellation Approved)]
	ORDER BY L_Leaves.LeaveStart DESC


	-- 8 Retrieve Employee Leave Threshold Limit By Employee Roster Group And Role Group For Current Leave Start Date
	-- Validate On Employees Primary Role And Leave Type
	SELECT  L_LeaveThreshold.ThresholdId, 
			L_LeaveThreshold.ThresholdValue,
			L_LeaveThreshold.RoleGroupId,
			L_LeaveThreshold.RosterGroupId 
	FROM	L_LeaveThreshold WITH (NOLOCK)
			INNER JOIN D_Roles WITH (NOLOCK) ON L_LeaveThreshold.RoleGroupId = D_Roles.RoleGroupId   
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId 
				AND C_EmployeeRoles.EmployeeId = @EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
	WHERE	L_LeaveThreshold.ExceptionCodeId = @ExceptionCodeId;

	-- 9 Retrieve List Of Employees On Leave By Current Employee Role Group (Including Pending And Approved)
	-- 1 => Pending, 3 => Approved, 6 => Pending Cancellation Approval
	-- Retrieve Current Employee Role Group
	WITH CurrentEmployeeRoleGroup 
	AS 
	(
		SELECT	D_Roles.RoleGroupId, C_Employee.RosterGroupId
		FROM	C_EmployeeRoles WITH (NOLOCK)
				INNER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId
		WHERE	C_Employee.EmployeeId = @EmployeeId
	),
	EmployeeListByRosterGroupAndRoleGroups As (
		SELECT	C_Employee.EmployeeId ,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName
		FROM	C_Employee WITH (NOLOCK)
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId
				INNER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId 
		WHERE	RosterGroupId = (SELECT CurrentEmployeeRoleGroup.RosterGroupId from CurrentEmployeeRoleGroup)
		AND		D_Roles.RoleGroupId = (SELECT CurrentEmployeeRoleGroup.RoleGroupId From CurrentEmployeeRoleGroup)
	)
	-- Total Leaves Taken with combination of all employees By Roster Group And Role Group Id Of Current Employee
	SELECT	Count(*) As TotalLeavesTaken 
	FROM	L_Leaves WITH (NOLOCK)
			INNER JOIN EmployeeListByRosterGroupAndRoleGroups WITH (NOLOCK) ON L_Leaves.EmployeeId = EmployeeListByRosterGroupAndRoleGroups.EmployeeId
	WHERE	L_Leaves.ApprovalStatusId IN (1,3,6) 
	AND		Convert(Date,L_Leaves.LeaveEnd) >= Convert(Date,@StartDate)
	AND		Convert(Date,L_Leaves.LeaveStart) <= Convert(Date,@EndDate);

	-- 10. Get Total Employee Count By Employee Roster Group And Role Group
	WITH CurrentEmployeeRoleGroup 
	AS 
	(
		SELECT	D_Roles.RoleGroupId, C_Employee.RosterGroupId
		FROM	C_EmployeeRoles WITH (NOLOCK)
				INNER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId
		WHERE	C_Employee.EmployeeId = @EmployeeId
	),
	EmployeeListByRosterGroupAndRoleGroups As (
		SELECT	C_Employee.EmployeeId ,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName
		FROM	C_Employee WITH (NOLOCK)
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId
				INNER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId 
		WHERE	RosterGroupId = (SELECT CurrentEmployeeRoleGroup.RosterGroupId from CurrentEmployeeRoleGroup)
		AND		D_Roles.RoleGroupId = (SELECT CurrentEmployeeRoleGroup.RoleGroupId From CurrentEmployeeRoleGroup)
	)
	SELECT COUNT(*) TotalEmployeesByRosterAndRoleGroups FROM EmployeeListByRosterGroupAndRoleGroups

	-- 11. Retrieve Leave Validation Procedures 
	SELECT	ValidationId,
			ExceptionCodeId,
			ProcedureToExecute,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	L_Validations WITH (NOLOCK)
	WHERE	ActiveStatus = 1 
	AND		ExceptionCodeId = @ExceptionCodeId
	ORDER BY ValidationId 

	-- 12. Get Count of Pending And Approved Leaves Between Selected Leave Start And End Dates
	SELECT	COUNT(LeaveId) DuplicateLeavesInRange
	FROM	L_Leaves WITH (NOLOCK)
	WHERE	Convert(Date,LeaveEnd) >= Convert(Date, @StartDate)
	AND		Convert(Date,LeaveStart) <= Convert(Date, @EndDate)
	AND		L_Leaves.ApprovalStatusId In (1, 3, 7, 6)
	AND		L_Leaves.EmployeeId = @EmployeeId

	--13 Get Number Of Count From All Pending Leaves
	SELECT	Sum(L_Leaves.NoOfDays) PendingLeaveDaysCount
	FROM	L_Leaves WITH (NOLOCK)
	WHERE	L_Leaves.ApprovalStatusId = @PendingForApproval
	AND		L_Leaves.EmployeeId = @EmployeeId
	AND		Year(L_Leaves.LeaveStart) = @EntitlementYear
	AND		ExceptionCodeId = @ExceptionCodeId

	--14 Get Total Number Of Shifts Available In Selected Leave Range Public Holiday
	;WITH PublicHolidaysInRange
	AS 
	(
		SELECT	Min(Convert(Date,HolidayDate)) HolidayStart, 
				Max(Convert(Date,HolidayDate)) HolidayEnd
		FROM	D_PublicHolidays WITH (NOLOCK) Where Convert(Date,HolidayDate) >= Convert(Date,@StartDate)
		And		Convert(Date,HolidayDate) <= Convert(Date,@EndDate) 
	)
	SELECT COUNT(*) NoOfShiftsInPublicHoliday
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	S_Shifts.EmployeeId		=	@EmployeeId
	AND		Convert(Date,S_Shifts.ActualStartTime)	>= (SELECT Convert(Date,HolidayStart) FROM PublicHolidaysInRange)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= (SELECT Convert(Date,HolidayEnd) FROM PublicHolidaysInRange)
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveProfile')
	DROP PROC prL_GetEmployeeLeaveProfile
GO

----------------------------------------------------------------------------
-- Get Employee Leave Profile Records
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeLeaveProfile
(
	@EmployeeLeaveProfileId	BigInt,
	@EmployeeId				BigInt
)
AS
BEGIN
	
	SELECT	EmployeeLeaveProfileId,
			EmployeeId,
			L_LeaveProfileHeader.LeaveProfileHeaderId,
			L_LeaveProfileHeader.ProfileName LeaveProfileName,
			StartDate,
			EndDate,
			ActionDate,
			Convert(nVarchar(10),ActionDate,120) ActionDateString,
			Convert(nVarchar(10),StartDate,120) StartDateString,
			Convert(nVarchar(10),EndDate,120) EndDateString,
			C_EmployeeLeaveProfile.CreatedBy,
			--C_EmployeeLeaveProfile.CreatedDate,
			C_EmployeeLeaveProfile.UpdatedBy
			--C_EmployeeLeaveProfile.UpdatedDate
	FROM	C_EmployeeLeaveProfile WITH (NOLOCK) INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) 
			ON C_EmployeeLeaveProfile.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId
	WHERE	(EmployeeLeaveProfileId = @EmployeeLeaveProfileId OR @EmployeeLeaveProfileId = 0)
	AND		EmployeeId = @EmployeeId

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveProfileByExceptionid')
	DROP PROC prL_GetEmployeeLeaveProfileByExceptionid
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeLeaveProfileByExceptionid
	@EmployeeId bigint,
	@ExceptionId bigint,
	@LeaveYear int

AS

select * from L_EmployeeLeaveProfiles with (nolock)
where employeeid= @EmployeeId
and ExceptionId = @ExceptionId 
and LeaveYear=@LeaveYear

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveProfilesByDateAndYear')
	DROP PROC prL_GetEmployeeLeaveProfilesByDateAndYear
GO

----------------------------------------------------------------------------
-- Select a single record from L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeLeaveProfilesByDateAndYear
	@EmployeeId			Bigint,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ExceptionCodeId	BigInt,
	@EntitlementYear	BigInt
AS

SELECT	EmpProfileId,
		L_EmployeeLeaveProfiles.EmployeeId,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		L_EmployeeLeaveProfiles.LeaveProfileId,
		StartDate,
		EndDate,
		LeaveYear,
		ExceptionId,
		D_ExceptionCodes.ExcpetionCodeName LeaveCode,
		D_ExceptionCodes.ExceptionCodeDesc LeaveDescription,
		L_EmployeeLeaveProfiles.EntitlementDays,
		CarryForwardDays,
		EarnedDays,
		DaysUsed,
		AdjustDays,
		DaysLieu,
		UsedDays,
		BalanceDays,
		EarnedDays_Cal,
		EarnedDays_Adj,
		EarnedMonth,
		AdjustmentRemakrs,
		L_EmployeeLeaveProfiles.CreatedBy,
		L_EmployeeLeaveProfiles.CreatedDate,
		L_EmployeeLeaveProfiles.UpdatedBy,
		L_EmployeeLeaveProfiles.UpdatedDate
FROM	L_EmployeeLeaveProfiles WITH (NOLOCK)
		INNER JOIN C_Employee WITH (NOLOCK) ON L_EmployeeLeaveProfiles.EmployeeId = C_Employee.EmployeeId 
					AND C_Employee.ActiveStatus = 1
		INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId  
					AND D_ExceptionCodes.ActiveStatus = 1
		INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileId
					AND L_LeaveProfiles.ActiveStatus = 1
WHERE 	L_EmployeeLeaveProfiles.EmployeeId				=	@EmployeeId
AND		L_EmployeeLeaveProfiles.LeaveYear				=	@EntitlementYear
AND		L_EmployeeLeaveProfiles.ExceptionId				=	@ExceptionCodeId
AND		Convert(Date,L_EmployeeLeaveProfiles.EndDate)	>= Convert(Date,@StartDate)
AND		Convert(Date,L_EmployeeLeaveProfiles.StartDate) <= Convert(Date,@EndDate)
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveProfilesByEmployeeId')
	DROP PROC prL_GetEmployeeLeaveProfilesByEmployeeId
GO

----------------------------------------------------------------------------
-- Select a single record from L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeLeaveProfilesByEmployeeId
	@EmployeeId			Bigint,
	@EntitlementYear	BigInt
AS

SELECT	EmpProfileId,
		L_EmployeeLeaveProfiles.EmployeeId,
		C_Employee.EmployeeNumber,
		C_Employee.DisplayName EmployeeName,
		L_EmployeeLeaveProfiles.LeaveProfileId,
		StartDate,
		EndDate,
		LeaveYear,
		ExceptionId,
		D_ExceptionCodes.ExcpetionCodeName LeaveCode,
		D_ExceptionCodes.ExceptionCodeDesc LeaveDescription,
		L_EmployeeLeaveProfiles.EntitlementDays,
		CarryForwardDays,
		EarnedDays,
		DaysUsed,
		AdjustDays,
		DaysLieu,
		UsedDays,
		BalanceDays,
		EarnedDays_Cal,
		EarnedDays_Adj,
		EarnedMonth,
		AdjustmentRemakrs,
		L_EmployeeLeaveProfiles.CreatedBy,
		L_EmployeeLeaveProfiles.CreatedDate,
		L_EmployeeLeaveProfiles.UpdatedBy,
		L_EmployeeLeaveProfiles.UpdatedDate
FROM	L_EmployeeLeaveProfiles WITH (NOLOCK)
		INNER JOIN C_Employee WITH (NOLOCK) ON L_EmployeeLeaveProfiles.EmployeeId = C_Employee.EmployeeId 
					--AND C_Employee.ActiveStatus = 1
		INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId  
					AND D_ExceptionCodes.ActiveStatus = 1
		INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileId
					AND L_LeaveProfiles.ActiveStatus = 1
WHERE 	(L_EmployeeLeaveProfiles.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)
AND		L_EmployeeLeaveProfiles.LeaveYear	=	@EntitlementYear
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeLeaveProfilesByEmpProfileId')
	DROP PROC prL_GetEmployeeLeaveProfilesByEmpProfileId
GO

----------------------------------------------------------------------------
-- Select a single record from L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeLeaveProfilesByEmpProfileId
	@EmpProfileId bigint
AS

SELECT	EmpProfileId,
	EmployeeId,
	LeaveProfileId,
	StartDate,
	EndDate,
	LeaveYear,
	ExceptionId,
	EntitlementDays,
	CarryForwardDays,
	EarnedDays,
	DaysUsed,
	AdjustDays,
	DaysLieu,
	UsedDays,
	BalanceDays,
	EarnedDays_Cal,
	EarnedDays_Adj,
	EarnedMonth,
	AdjustmentRemakrs,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	L_EmployeeLeaveProfiles WITH (NOLOCK)
WHERE 	EmpProfileId = @EmpProfileId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeListToProcessEntitlment')
	DROP PROC prL_GetEmployeeListToProcessEntitlment
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeListToProcessEntitlment
	@Date DateTime
AS
--select C_Employee.EmployeeId,LeaveProfileHeaderId from C_Employee
--inner join C_EmployeeLeaveProfile on c_employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
--where convert(date, C_EmployeeLeaveProfile.StartDate) <= convert(date,@Date) and convert(date, C_EmployeeLeaveProfile.Enddate) >= convert(date,@Date)
--AND C_Employee.ActiveStatus = 1 

select C_Employee.EmployeeId,LeaveProfileHeaderId from C_Employee WITH (NOLOCK)
inner join C_EmployeeLeaveProfile WITH (NOLOCK) on c_employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
where convert(date, C_EmployeeLeaveProfile.StartDate) <= convert(date,@Date) 
and convert(date, C_EmployeeLeaveProfile.Enddate) >= convert(date,@Date)
ANd C_Employee.EmployeeId NOT IN 
								(	SELECT	EmployeeId 
									FROM	C_EmployeeDiciplinary 
									Where	Convert(Date,EndDate) >= Convert(Date,@Date) 
									And		Convert(Date,StartDate) <= Convert(Date,@date)
								)
--AND	C_Employee.EmployeeId= 1161
AND C_Employee.ActiveStatus = 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeTimeOffApprovers')
	DROP PROC prL_GetEmployeeTimeOffApprovers
GO

CREATE PROC prL_GetEmployeeTimeOffApprovers
	@EmployeeId			Bigint,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ModuleId			Int
AS
BEGIN
	--5 Get Approvers List By Employee Leave Profile
	SELECT	W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.RouteLevel,
			W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.ApprovalRequirement,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_Employee.EmailAddress ApproverEmailId,
			C_EmployeeWorkflow.RouteId,
			C_EmployeeWorkflow.ModuleId
	FROM	W_WorkflowRouteDetails WITH (NOLOCK)
			INNER JOIN W_WorkflowRoute WITH (NOLOCK) ON W_WorkflowRouteDetails.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = W_WorkflowRouteDetails.EmployeeId
	WHERE	C_EmployeeWorkflow.EmployeeId = @EmployeeId
	AND		Convert(Date,C_EmployeeWorkflow.EndDate)   >= Convert(Date,@StartDate)
	AND		Convert(Date,C_EmployeeWorkflow.StartDate) <= Convert(Date,@EndDate)
	AND		C_EmployeeWorkflow.ModuleId = @ModuleId
	ORDER BY W_WorkflowRouteDetails.RouteLevel, W_WorkflowRouteDetails.RouteDetId
END


go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetEmployeeWorkflowRoute')
	DROP PROC prL_GetEmployeeWorkflowRoute
GO

----------------------------------------------------------------------------
-- Get Employee Workflow Route Records
----------------------------------------------------------------------------
CREATE PROC prL_GetEmployeeWorkflowRoute
(
	@EmployeeWorkflowId		BigInt,
	@EmployeeId				BigInt
)
AS
BEGIN
	SELECT	EmployeeWorkflowId,
			EmployeeId,
			C_EmployeeWorkflow.ModuleId,
			W_Modules.ModuleName,
			C_EmployeeWorkflow.RouteId,
			W_WorkflowRoute.RouteName,
			StartDate,
			Convert(nVarchar(10),StartDate,120) StartDateString,
			EndDate,
			Convert(nVarchar(10),EndDate,120) EndDateString,
			C_EmployeeWorkflow.CreatedBy,
			C_EmployeeWorkflow.CreatedDate,
			C_EmployeeWorkflow.UpdatedBy,
			C_EmployeeWorkflow.UpdatedDate 
	FROM	C_EmployeeWorkflow WITH (NOLOCK) INNER JOIN W_WorkflowRoute WITH (NOLOCK)
			ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN W_Modules WITH (NOLOCK) ON C_EmployeeWorkflow.ModuleId = W_Modules.ModuleId
	WHERE	(EmployeeWorkflowId = @EmployeeWorkflowId OR @EmployeeWorkflowId = 0)
	AND		EmployeeId = @EmployeeId

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveBalanceAuditByEmployeeId')
	DROP PROC prL_GetLeaveBalanceAuditByEmployeeId
GO

----------------------------------------------------------------------------
-- Get Leave Balance Audit By Employee Id
----------------------------------------------------------------------------
CREATE PROC prL_GetLeaveBalanceAuditByEmployeeId
	@EmployeeId			BigInt,
	@ExceptionCodeId	BigInt
AS
	SELECT	L_LeaveBalanceAudit.LeaveAuditId,
			L_LeaveBalanceAudit.ActionDate,
			L_LeaveBalanceAudit.ReferenceNo,
			L_LeaveBalanceAudit.EmployeeId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			L_LeaveBalanceAudit.ExceptionCodeId ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
			D_ExceptionCodes.ExceptionCodeDesc ExceptionCodeDesc,
			L_LeaveBalanceAudit.LeaveStart,
			L_LeaveBalanceAudit.LeaveEnd,
			L_LeaveBalanceAudit.ActionCode,
			L_LeaveBalanceAudit.ActionDesc,
			L_LeaveBalanceAudit.NoOfDays,
			L_LeaveBalanceAudit.EntitlementDays,
			L_LeaveBalanceAudit.CarryForwardDays,
			L_LeaveBalanceAudit.EarnedDays,
			L_LeaveBalanceAudit.DaysUsed,
			L_LeaveBalanceAudit.BalanceDays,
			L_LeaveBalanceAudit.CreatedBy,
			L_LeaveBalanceAudit.CreatedDate
	FROM	L_LeaveBalanceAudit 
			INNER JOIN C_Employee ON C_Employee.EmployeeId = L_LeaveBalanceAudit.EmployeeId
			INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = L_LeaveBalanceAudit.ExceptionCodeId
	WHERE	L_LeaveBalanceAudit.EmployeeId = @EmployeeId
	AND		(L_LeaveBalanceAudit.ExceptionCodeId = @ExceptionCodeId OR @ExceptionCodeId = 0)
	--ORDER BY ExcpetionCodeName ASC, ActionDate DESC
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveProfileByHeaderId')
	DROP PROC prL_GetLeaveProfileByHeaderId
GO

CREATE PROC prL_GetLeaveProfileByHeaderId
(
	@LeaveProfileId			Int,
	@LeaveProfileHeaderId	Int

)
AS
BEGIN

	SELECT	LeaveProfileId,
			L_LeaveProfileHeader.LeaveProfileHeaderId,
			L_LeaveProfiles.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName,
			D_ExceptionCodes.ExceptionCodeDesc,
			EntitlementDays,
			CarryForward,
			MaximumDaysPerYear,
			Accural,
			CarryforwardDateType CarryForwardDateType,
			CarryforwardDate,
			DayCalculation,
			DaysInAdvance,
			MinimumDaysRequest,
			MaximumDaysRequest,
			RequestPerYear,
			NegativeBalance,
			MaximumDaysNegative,
			HalfDays,
			L_LeaveProfiles.ActiveStatus,
			L_LeaveProfiles.CreatedBy,
			L_LeaveProfiles.CreatedDate,
			L_LeaveProfiles.UpdatedBy,
			L_LeaveProfiles.UpdatedDate
	FROM	L_LeaveProfiles 
			INNER JOIN L_LeaveProfileHeader ON L_LeaveProfiles.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId
			RIGHT OUTER JOIN D_ExceptionCodes ON L_LeaveProfiles.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHERE	(L_LeaveProfiles.LeaveProfileId = @LeaveProfileId OR @LeaveProfileId = 0)
	AND		L_LeaveProfiles.ExceptionCodeId IS NOT NULL
	AND		L_LeaveProfileHeader.LeaveProfileHeaderId = @LeaveProfileHeaderId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveProfileHeaderByOU')
	DROP PROC prL_GetLeaveProfileHeaderByOU
GO

CREATE PROC prL_GetLeaveProfileHeaderByOU
(
	@LeaveProfileHeaderId	Int,
	@OUId					BigInt
)
AS
BEGIN

	SELECT	ProfileName,
			Remarks,
			L_LeaveProfileHeader.LeaveProfileHeaderId,
			L_LeaveProfileHeader.ActiveStatus,
			L_LeaveProfileHeader.CreatedBy,
			L_LeaveProfileHeader.UpdatedBy
	FROM	L_LeaveProfileHeader
			INNER JOIN L_LeaveProfileOU ON L_LeaveProfileHeader.LeaveProfileHeaderId = L_LeaveProfileOU.LeaveProfileHeaderId
	WHERE	(L_LeaveProfileHeader.LeaveProfileHeaderId = @LeaveProfileHeaderId OR @LeaveProfileHeaderId = 0)
	AND		L_LeaveProfileOU.OUId = @OUId

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveProfileOUByProfileHeaderId')
	DROP PROC prL_GetLeaveProfileOUByProfileHeaderId
GO

CREATE PROC prL_GetLeaveProfileOUByProfileHeaderId
(
	@LeaveProfileHeaderId	Int
)
AS
BEGIN

	SELECT	L_LeaveProfileOU.LeaveProfileOUId,
			L_LeaveProfileOU.LeaveProfileHeaderId,
			L_LeaveProfileOU.OUId,
			C_OrganizationNode.OUName,
			L_LeaveProfileHeader.ProfileName
	FROM	L_LeaveProfileOU 
			INNER JOIN L_LeaveProfileHeader ON L_LeaveProfileOU.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId
			INNER JOIN C_OrganizationNode ON L_LeaveProfileOU.OUId = C_OrganizationNode.OUId
	WHERE	L_LeaveProfileOU.LeaveProfileHeaderId = @LeaveProfileHeaderId
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetLeaveRecordsByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_GetLeaveRecordsByEmployeeId]
GO
/****** Object:  StoredProcedure [dbo].[prL_GetLeaveRecordsByEmployeeId]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_GetLeaveRecordsByEmployeeId]    
(
	@EmployeeId		BigInt
)
AS
BEGIN
	SELECT	L_Leaves.LeaveId,
			L_Leaves.OUId,
			L_Leaves.EmployeeId,
			L_Leaves.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
			D_ExceptionCodes.ExceptionCodeDesc ExceptionDescription,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			L_Leaves.LeaveStart,
			L_Leaves.LeaveEnd,
			L_Leaves.LeaveType,
			L_Leaves.NoOfDays,
			L_Leaves.ReasonId,
			L_Leaves.IsEmergency,
			L_Leaves.ApprovalStatusId,
			W_ApprovalStatus.ApprovalStatus,
			W_ApprovalStatus.ApprovalStatusDesc,
			L_Leaves.ReferenceNo,
			L_Leaves.Remarks,
			L_Leaves.AppliedDate,
			L_Leaves.AppliedBy,
			L_Leaves.ApprovedBy,
			L_Leaves.ApprovedDate
	FROM	L_Leaves 
			INNER JOIN C_Employee ON C_Employee.EmployeeId = L_Leaves.EmployeeId
			INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
			INNER JOIN C_OrganizationNode ON C_OrganizationNode.OUId = L_Leaves.OUId
			LEFT OUTER JOIN W_ApprovalStatus ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
	WHERE	(L_Leaves.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	ORDER BY L_Leaves.LeaveStart DESC
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveThresholdByRosterGroupIdAndRoleGroupId')
	DROP PROC prL_GetLeaveThresholdByRosterGroupIdAndRoleGroupId
GO

----------------------------------------------------------------------------
-- Select a single record from L_LeaveThreshold
----------------------------------------------------------------------------
CREATE PROC prL_GetLeaveThresholdByRosterGroupIdAndRoleGroupId
	@RosterGroupId bigint,
	@RoleGroupId bigint
AS

SELECT	IsNull(L_LeaveThreshold.ThresholdId,0) ThresholdId,
		L_LeaveThreshold.RosterGroupId,
		L_LeaveThreshold.RoleGroupId,
		D_ExceptionCodes.ExceptionCodeId,
		D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
		IsNull(L_LeaveThreshold.ThresholdValue,0) ThresholdValue,
		S_RosterGroup.GroupName RosterGroupName,
		D_RoleGroup.RoleGroupName,
		L_LeaveThreshold.CreatedBy,
		L_LeaveThreshold.CreatedDate,
		L_LeaveThreshold.UpdatedBy,
		L_LeaveThreshold.UpdatedDate
FROM	D_ExceptionCodes WITH (NOLOCK) 
		LEFT OUTER JOIN L_LeaveThreshold WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_LeaveThreshold.ExceptionCodeId
		AND L_LeaveThreshold.RosterGroupId	= @RosterGroupId AND L_LeaveThreshold.RoleGroupId = @RoleGroupId
		LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON L_LeaveThreshold.RosterGroupId = S_RosterGroup.RosterGroupId --AND S_RosterGroup.RosterGroupId	=		@RosterGroupId
		LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON L_LeaveThreshold.RoleGroupId = D_RoleGroup.RoleGroupId --AND D_RoleGroup.RoleGroupId		=		@RoleGroupId
--WHERE 	S_RosterGroup.RosterGroupId	=		6
--AND		D_RoleGroup.RoleGroupId		=		6
--WHERE 	L_LeaveThreshold.RosterGroupId	=		@RosterGroupId
--AND		L_LeaveThreshold.RoleGroupId	=		@RoleGroupId
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveValidationProcedures')
	DROP PROC prL_GetLeaveValidationProcedures
GO

CREATE PROC prL_GetLeaveValidationProcedures
AS
BEGIN

	SELECT	ValidationId,
			ExceptionCodeId,
			ProcedureToExecute,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	L_Validations
	WHERE	ActiveStatus = 1
	ORDER BY ValidationId 
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetPendingApproversCountByRouteLevelNo')
	DROP PROC prL_GetPendingApproversCountByRouteLevelNo
GO

CREATE PROC prL_GetPendingApproversCountByRouteLevelNo
	@RouteLevelNo		Int,
	@TransRouteId	BigInt
AS
BEGIN
	
	SELECT	COUNT(*) PendingApproversCount
	FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
	WHERE	RouteLevel		=	@RouteLevelNo
	AND		TransRouteID	=	@TransRouteId
	AND		UserAction	IS NULL
	AND		ActionDate	IS NULL

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetPendingForApprovalByApproverId')
	DROP PROC prL_GetPendingForApprovalByApproverId
GO

CREATE PROC prL_GetPendingForApprovalByApproverId
	@ApproverId			Bigint,
	@ModuleId			Int
AS
BEGIN
	If (@ModuleId = 201) -- Leave Module
	BEGIN
		SELECT	W_TRN_Approval_RouteDetails.TransRouteDetID,
				W_TRN_Approval_RouteDetails.TransRouteID,
				W_TRN_Approval_RouteDetails.ApprovalTransID,
				W_TRN_Approval_RouteDetails.ApplicantId,
				W_TRN_Approval_RouteDetails.AppliedDate,
				W_TRN_Approval_RouteDetails.ApproverId,
				W_TRN_Approval_RouteDetails.RouteLevel,
				W_TRN_Approval_RouteDetails.ApprovalRequirement,
				W_TRN_Approval_RouteDetails.UserAction,
				W_TRN_Approval_RouteDetails.ActionDate,
				W_TRN_Approval_RouteDetails.Remarks,
				C_Employee.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_Employee.OUId,
				C_OrganizationNode.OUName OUName,
				D_ExceptionCodes.ExceptionCodeId,
				D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
				D_ExceptionCodes.ExceptionCodeDesc,
				D_ExceptionCodes.ColorCode ExceptionColor,
				D_ExceptionCodes.ShiftLength,
				D_ExceptionCodes.IsPaid,
				D_ExceptionCodes.ColorCode,
				L_Leaves.LeaveStart,
				L_Leaves.LeaveEnd,
				L_Leaves.NoOfDays,
				L_Leaves.IsEmergency,
				L_Leaves.AppliedDate,
				L_Leaves.Remarks,
				W_TRN_ApprovalRoute.RequestTransId,
				W_TRN_ApprovalRoute.ApprovalModuleID,
				L_Leaves.ApprovalStatusId
		FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = C_Employee.EmployeeId
				INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
				INNER JOIN L_Leaves WITH (NOLOCK) ON L_Leaves.LeaveId = W_TRN_ApprovalRoute.RequestTransId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		WHERE	W_TRN_Approval_RouteDetails.ApproverId	=	@ApproverId
		AND		(W_TRN_ApprovalRoute.ApprovalModuleID	=	@ModuleId OR @ModuleId = 0)
		AND		W_TRN_Approval_RouteDetails.UserAction IS NULL
		AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	END
	Else If (@ModuleId = 202) -- WorkFlow DIL Module
	BEGIN
		
		SELECT	W_TRN_Approval_RouteDetails.TransRouteDetID,
				W_TRN_Approval_RouteDetails.TransRouteID,
				W_TRN_Approval_RouteDetails.ApprovalTransID,
				W_TRN_Approval_RouteDetails.ApplicantId,
				W_TRN_Approval_RouteDetails.AppliedDate,
				W_TRN_Approval_RouteDetails.ApproverId,
				W_TRN_Approval_RouteDetails.RouteLevel,
				W_TRN_Approval_RouteDetails.ApprovalRequirement,
				W_TRN_Approval_RouteDetails.UserAction,
				W_TRN_Approval_RouteDetails.ActionDate,
				W_TRN_Approval_RouteDetails.Remarks,
				C_Employee.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_Employee.OUId,
				C_OrganizationNode.OUName OUName,
				'Days In Liue' ExceptionCodeName,
				'Days In Liue' ExceptionCodeDesc,
				'' ExceptionColor,
				--Convert(int,0) ShiftLength,
				--Convert(Bit,0) IsPaid,
				--D_ExceptionCodes.ExceptionCodeId,
				--D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
				--D_ExceptionCodes.ExceptionCodeDesc,
				--D_ExceptionCodes.ColorCode ExceptionColor,
				--D_ExceptionCodes.ShiftLength,
				--D_ExceptionCodes.IsPaid,
				--D_ExceptionCodes.ColorCode,
				L_RequestDaysInLieu.RequestedDate LeaveStart,
				NULL LeaveEnd,
				Convert(decimal,1) NoOfDays,
				Convert(Bit,0) IsEmergency,
				L_RequestDaysInLieu.AppliedDate,
				L_RequestDaysInLieu.Remarks,
				W_TRN_ApprovalRoute.RequestTransId,
				W_TRN_ApprovalRoute.ApprovalModuleID,
				L_RequestDaysInLieu.ApprovalStatusId
		FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = C_Employee.EmployeeId
				INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
				INNER JOIN L_RequestDaysInLieu WITH (NOLOCK) ON L_RequestDaysInLieu.DaysInLieuId = W_TRN_ApprovalRoute.RequestTransId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		WHERE	W_TRN_Approval_RouteDetails.ApproverId	=	@ApproverId
		AND		(W_TRN_ApprovalRoute.ApprovalModuleID	=	@ModuleId OR @ModuleId = 0)
		AND		W_TRN_Approval_RouteDetails.UserAction IS NULL
		AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	END
	Else If (@ModuleId = 203)  -- WorkFlow Time Off Module
	BEGIN
		-- Retrieve Time off Exception Code From System Parameters
		DECLARE @TimeOffId BigInt = 0, @TimeOffExceptionCode nVarchar(50) = ''

		SELECT	@TimeOffExceptionCode = IsNull(LTrim(RTrim(D_SystemParams.ParamValue)),'') 
		FROM	D_SystemParams WHERE ParamName = 'TimeOffExceptionCode'

		-- Retrieve Time Off Id From D_ExceptionCodes By Time Off Code 
		SELECT	@TimeOffId = IsNull(D_ExceptionCodes.ExceptionCodeId, 0)
		FROM	D_ExceptionCodes	
		WHERE	LTrim(RTrim(ExcpetionCodeName)) = @TimeOffExceptionCode

		SELECT	W_TRN_Approval_RouteDetails.TransRouteDetID,
				W_TRN_Approval_RouteDetails.TransRouteID,
				W_TRN_Approval_RouteDetails.ApprovalTransID,
				W_TRN_Approval_RouteDetails.ApplicantId,
				W_TRN_Approval_RouteDetails.AppliedDate,
				W_TRN_Approval_RouteDetails.ApproverId,
				W_TRN_Approval_RouteDetails.RouteLevel,
				W_TRN_Approval_RouteDetails.ApprovalRequirement,
				W_TRN_Approval_RouteDetails.UserAction,
				W_TRN_Approval_RouteDetails.ActionDate,
				W_TRN_Approval_RouteDetails.Remarks,
				C_Employee.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_Employee.OUId,
				C_OrganizationNode.OUName OUName,
				Convert(BigInt,@TimeOffId) ExceptionCodeId,
				'Time Off' ExceptionCodeName,
				'Time Off' ExceptionCodeDesc,
				'' ExceptionColor,
				Convert(numeric(10,0),0) ShiftLength,
				Convert(Bit,0) IsPaid,
				--D_ExceptionCodes.ExceptionCodeId,
				--D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
				--D_ExceptionCodes.ExceptionCodeDesc,
				--D_ExceptionCodes.ColorCode ExceptionColor,
				--D_ExceptionCodes.ShiftLength,
				--D_ExceptionCodes.IsPaid,
				--D_ExceptionCodes.ColorCode,
				L_TimeOff.StartTime LeaveStart,
				NULL LeaveEnd,
				L_TimeOff.Duration NoOfDays,
				Convert(Bit,0) IsEmergency,
				L_TimeOff.AppliedDate,
				L_TimeOff.Remarks,
				W_TRN_ApprovalRoute.RequestTransId,
				W_TRN_ApprovalRoute.ApprovalModuleID,
				L_TimeOff.ApprovalStatusId
		FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = C_Employee.EmployeeId
				INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
				INNER JOIN L_TimeOff WITH (NOLOCK) ON L_TimeOff.TimeOffId = W_TRN_ApprovalRoute.RequestTransId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		WHERE	W_TRN_Approval_RouteDetails.ApproverId	=	@ApproverId
		AND		(W_TRN_ApprovalRoute.ApprovalModuleID	=	@ModuleId OR @ModuleId = 0)
		AND		W_TRN_Approval_RouteDetails.UserAction IS NULL
		AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	END
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetTimeOffRecordsByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_GetTimeOffRecordsByEmployeeId]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_GetTimeOffRecordsByEmployeeId]    
(
	@EmployeeId		BigInt
)
AS
BEGIN
	SELECT	L_TimeOff.TimeOffId,
			L_TimeOff.EmployeeId,
			L_TimeOff.StartTime,
			L_TimeOff.Duration,
			L_TimeOff.Remarks,
			L_TimeOff.ApprovalStatusId,
			W_ApprovalStatus.ApprovalStatus,
			W_ApprovalStatus.ApprovalStatusDesc,
			L_TimeOff.AppliedDate,
			L_TimeOff.CreatedBy,
			L_TimeOff.CreatedDate,
			L_TimeOff.ShiftId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_Employee.EmailAddress ApplicantEmailId
	FROM	L_TimeOff
			INNER JOIN C_Employee ON C_Employee.EmployeeId = L_TimeOff.EmployeeId
			LEFT OUTER JOIN W_ApprovalStatus ON L_TimeOff.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
	WHERE	(L_TimeOff.EmployeeId = @EmployeeId OR @EmployeeId = 0)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetViewExceptionDetailsById')
	DROP PROC prL_GetViewExceptionDetailsById
GO

CREATE PROC prL_GetViewExceptionDetailsById
	@RequestTransId			BigInt, -- Leave / Days In Lieu / Time Off / Time Attendance (ShiftId) Transaction Id
	@ModuleId				Int,
	@RequestedBy			nVarchar(255)
AS
BEGIN
	DECLARE @InUseSeconds Int = 0
	 
	-- 1. Retrieve Leave Details
	If (@ModuleId = 201)
	BEGIN
		-- Refer To Jira Issue With Reference # E10-36 
		-- Check Whether The Record Is Being used By other user for more than 30sec
		SELECT	@InUseSeconds = DATEDIFF(SECOND, L_Leaves.LastViewDateTime,GETDATE()) 
		From	L_Leaves WITH (NOLOCK) 
		Where	LeaveId = @RequestTransId

		-- Update Last Access Date & Time Status Along With User Requesting This Operation
		If (@InUseSeconds IS NULL OR @InUseSeconds >= 30)
		BEGIN
			UPDATE	L_Leaves 
			SET		LastViewDateTime	=	GETDATE(),
					LastViewedUser		=	@RequestedBy
			WHERE	L_Leaves.LeaveId	=	@RequestTransId
		END

		SELECT	L_Leaves.EmployeeId,
				C_Employee.EmailAddress ApplicantEmailId, 
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
				D_ExceptionCodes.ExceptionCodeDesc ExceptionDescription,
				L_Leaves.LeaveStart,
				L_Leaves.LeaveEnd,
				L_Leaves.NoOfDays,
				L_Leaves.AppliedDate,
				L_Leaves.Remarks,
				L_Leaves.LeaveId,
				W_ApprovalStatus.ApprovalStatus,
				W_ApprovalStatus.ApprovalStatusDesc,
				L_Leaves.ApprovalStatusId, 
				L_Leaves.LastViewDateTime,
				L_Leaves.LastViewedUser
		FROM	L_Leaves WITH (NOLOCK)
				LEFT OUTER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON L_Leaves.LeaveId = W_TRN_ApprovalRoute.RequestTransId 		
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_Leaves.EmployeeId
				LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON W_ApprovalStatus.ApprovalStatusId = L_Leaves.ApprovalStatusId
		WHERE	L_Leaves.LeaveId = @RequestTransId
	END
	Else If (@ModuleId = 202) -- WorkFlow DIL Module
	BEGIN
		-- Refer To Jira Issue With Reference # E10-36 
		-- Check Whether The Record Is Being used By other user for more than 30sec
		SELECT	@InUseSeconds = DATEDIFF(SECOND, L_RequestDaysInLieu.LastViewDateTime,GETDATE()) 
		From	L_RequestDaysInLieu WITH (NOLOCK) 
		Where	DaysInLieuId = @RequestTransId

		-- Update Last Access Date & Time Status Along With User Requesting This Operation
		If (@InUseSeconds IS NULL OR @InUseSeconds >= 30)
		BEGIN
			UPDATE	L_RequestDaysInLieu 
			SET		LastViewDateTime					=	GETDATE(),
					LastViewedUser						=	@RequestedBy
			WHERE	L_RequestDaysInLieu.DaysInLieuId	=	@RequestTransId
		END

		SELECT	L_RequestDaysInLieu.EmployeeId,
				C_Employee.EmailAddress ApplicantEmailId, 
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				'Days In Liue' ExceptionCode,
				'Days In Liue' ExceptionDescription,
				L_RequestDaysInLieu.RequestedDate LeaveStart,
				NULL LeaveEnd,
				Convert(decimal,1) NoOfDays,
				L_RequestDaysInLieu.AppliedDate,
				L_RequestDaysInLieu.Remarks,
				L_RequestDaysInLieu.DaysInLieuId,
				W_ApprovalStatus.ApprovalStatus,
				W_ApprovalStatus.ApprovalStatusDesc,
				L_RequestDaysInLieu.ApprovalStatusId, 
				L_RequestDaysInLieu.LastViewDateTime,
				L_RequestDaysInLieu.LastViewedUser
		FROM	L_RequestDaysInLieu WITH (NOLOCK)
				LEFT OUTER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON L_RequestDaysInLieu.DaysInLieuId = W_TRN_ApprovalRoute.RequestTransId 		
				--INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_RequestDaysInLieu.EmployeeId
				LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON W_ApprovalStatus.ApprovalStatusId = L_RequestDaysInLieu.ApprovalStatusId
		WHERE	L_RequestDaysInLieu.DaysInLieuId = @RequestTransId
	END
	Else If (@ModuleId = 203) -- WorkFlow Time Off Module
	BEGIN
		-- Refer To Jira Issue With Reference # E10-36 
		-- Check Whether The Record Is Being used By other user for more than 30sec
		SELECT	@InUseSeconds = DATEDIFF(SECOND, L_TimeOff.LastViewDateTime,GETDATE()) 
		From	L_TimeOff WITH (NOLOCK) 
		Where	TimeOffId = @RequestTransId

		-- Update Last Access Date & Time Status Along With User Requesting This Operation
		If (@InUseSeconds IS NULL OR @InUseSeconds >= 30)
		BEGIN
			UPDATE	L_TimeOff 
			SET		LastViewDateTime		=	GETDATE(),
					LastViewedUser			=	@RequestedBy
			WHERE	L_TimeOff.TimeOffId		=	@RequestTransId
		END

		SELECT	L_TimeOff.EmployeeId,
				C_Employee.EmailAddress ApplicantEmailId, 
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				'Time Off' ExceptionCode,
				'Time Off' ExceptionDescription,
				L_TimeOff.StartTime LeaveStart,
				NULL LeaveEnd,
				L_TimeOff.Duration NoOfDays,
				L_TimeOff.AppliedDate,
				L_TimeOff.Remarks,
				L_TimeOff.TimeOffId,
				W_ApprovalStatus.ApprovalStatus,
				W_ApprovalStatus.ApprovalStatusDesc,
				L_TimeOff.ApprovalStatusId, 
				L_TimeOff.LastViewDateTime,
				L_TimeOff.LastViewedUser
		FROM	L_TimeOff WITH (NOLOCK)
				LEFT OUTER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON L_TimeOff.TimeOffId = W_TRN_ApprovalRoute.RequestTransId 		
				--INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_TimeOff.EmployeeId
				LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON W_ApprovalStatus.ApprovalStatusId = L_TimeOff.ApprovalStatusId
		WHERE	L_TimeOff.TimeOffId = @RequestTransId
	END

	-- 2.  Retrieve Application Status Details From Approval Transactions
	SELECT	W_TRN_Approvals.ApproverId,
			W_TRN_Approval_RouteDetails.UserAction UserActionId,
			W_ApprovalStatus.ApprovalStatus UserAction,
			W_TRN_Approval_RouteDetails.ActionDate ,
			W_TRN_Approval_RouteDetails.Remarks,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName
	FROM	W_TRN_Approvals WITH (NOLOCK)
			LEFT OUTER JOIN W_TRN_Approval_RouteDetails WITH (NOLOCK) ON W_TRN_Approvals.TranId = W_TRN_Approval_RouteDetails.ApprovalTransID
			INNER JOIN C_Employee WITH (NOLOCK)ON W_TRN_Approvals.ApproverId = C_Employee.EmployeeId
			LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON W_ApprovalStatus.ApprovalStatusId = W_TRN_Approval_RouteDetails.UserAction
	WHERE	W_TRN_Approvals.RequestTransID		=	@RequestTransId
	AND		W_TRN_Approvals.ApprovalModuleID	=	@ModuleId

	-- Retrieve Attachment Details By Request Transaction Id (Leave Id)
	SELECT	AttachmentId,
			EmployeeId,
			AttachmentSourceId,
			AttachmentContents,
			AttachmentName,
			AttachmentSavedAs,
			AttachmentType,
			ModuleName,
			CreatedBy,
			CreatedDate,
			'' RowAction
	FROM	T_Attachments WITH (NOLOCK)
	WHERE	AttachmentSourceId	=	@RequestTransId

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateApplicationCancellationStatus')
	DROP PROC prL_UpdateApplicationCancellationStatus
GO

CREATE PROC prL_UpdateApplicationCancellationStatus
	@RequestTransId		BigInt,
	@ApprovalStatusId	Int,
	@ModuleTypeId		Int,
	@UpdatedBy			nVarchar(50)
AS
BEGIN
	If (@ModuleTypeId = 201)
	BEGIN
		UPDATE	L_Leaves
		SET		ApprovalStatusId	=	@ApprovalStatusId,
				UpdatedBy			=	@UpdatedBy,
				AppliedDate			=	GETDATE(),
				UpdatedDate			=	GETDATE(),
				ApprovedBy			=	NULL,
				ApprovedDate		=	NULL
		WHERE	LeaveId				=	@RequestTransId
	END
	Else If (@ModuleTypeId = 202)
	BEGIN
		UPDATE	L_RequestDaysInLieu
		SET		ApprovalStatusId	=	@ApprovalStatusId,
				AppliedDate			=	GETDATE(),
				ApproverId			=	NULL,
				ApprovedDate		=	NULL
		WHERE	DaysInLieuId		=	@RequestTransId
	END
	Else If (@ModuleTypeId = 203)
	BEGIN
		UPDATE	L_TimeOff
		SET		ApprovalStatusId	=	@ApprovalStatusId,
				AppliedDate			=	GETDATE(),
				ApproverId			=	NULL,
				ApprovedDate		=	NULL
		WHERE	TimeOffId			=	@RequestTransId
	END

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateEmployeeLeaveProfile')
	DROP PROC prL_UpdateEmployeeLeaveProfile
GO

----------------------------------------------------------------------------
-- Update Single Employee Leave Profile Record
----------------------------------------------------------------------------
CREATE PROC prL_UpdateEmployeeLeaveProfile
(
	@EmployeeLeaveProfileId	BigInt,
	@EmployeeId				BigInt,
	@LeaveProfileHeaderId	BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	--@ActionDate				DateTime,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN

	UPDATE	C_EmployeeLeaveProfile
	SET		EmployeeId				=	@EmployeeId, 
			LeaveProfileHeaderId	=	@LeaveProfileHeaderId, 
			StartDate				=	@StartDate, 
			EndDate					=	@EndDate, 
			ActionDate				=	GETDATE(), 
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GETDATE()
	WHERE	EmployeeLeaveProfileId	=	@EmployeeLeaveProfileId

	SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateEmployeeLeaveProfileAdjustmentDays')
	DROP PROC prL_UpdateEmployeeLeaveProfileAdjustmentDays
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_UpdateEmployeeLeaveProfileAdjustmentDays
	@AdjustmentDays decimal(18,2),
	@EmpLeaveProfileId BigInt,
	@UpdatedBy	nVarchar(50)
AS
	DECLARE @DaysInLieuId BigInt = 0, @RamadanDaysInLieuId BigInt = 0, @ExceptionCodeId BigInt = 0, @DayCalculationType Int = 0, @ExceptionId BigInt = 0

	SELECT @DayCalculationType = IsNull(L_LeaveProfiles.DayCalculation,0), @ExceptionId = IsNull(L_EmployeeLeaveProfiles.ExceptionId,0)
	FROM	L_EmployeeLEaveProfiles WITH (NOLOCK) 
			INNER JOIN L_LeaveProfiles WITH (NOLOCK)  ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileHeaderId
			AND		L_LeaveProfiles.ExceptionCodeId = L_EmployeeLeaveProfiles.ExceptionId
	WHERE	L_EmployeeLEaveProfiles.EmpProfileId = @EmpLeaveProfileId


	--SELECT	@DaysInLieuId = IsNull(ParamValue,0) FROM D_SystemParams WITH (NOLOCK) Where ParamName = 'DaysInLieuId' 

	--SELECT	@RamadanDaysInLieuId =  IsNull(D_ExceptionCodes.ExceptionCodeId, 0)
	--FROM	D_ExceptionCodes WITH (NOLOCK)
	--WHERE	ExcpetionCodeName = (SELECT ParamValue FROM D_SystemParams WITH (NOLOCK) Where ParamName = 'RamadanDaysInLieuCode')

	If @DayCalculationType = 1 --AND @ExceptionId != @DaysInLieuId And @ExceptionId != @RamadanDaysInLieuId
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		AdjustDays		=	@AdjustmentDays,
				BalanceDays		= IsNull(EarnedDays,0) + IsNull(CarryForwardDays,0) + IsNull(@AdjustmentDays,0) + IsNull(DaysLieu,0) - IsNull(DaysUsed,0) + IsNull(EarnedDays_Adj,0),
				UpdatedBy		=	@UpdatedBy
		WHERE	L_EmployeeLEaveProfiles.EmpProfileId = @EmpLeaveProfileId

		SELECT 1
	END
	Else If @DayCalculationType = 2 --AND @ExceptionId != @DaysInLieuId  And @ExceptionId != @RamadanDaysInLieuId
	begin
		UPDATE	L_EmployeeLeaveProfiles
		SET		AdjustDays		=	@AdjustmentDays,
				BalanceDays		= IsNull(EntitlementDays,0) + IsNull(CarryForwardDays,0) + IsNull(@AdjustmentDays,0) + IsNull(DaysLieu,0) - IsNull(DaysUsed,0),
				UpdatedBy		=	@UpdatedBy
		WHERE	L_EmployeeLEaveProfiles.EmpProfileId = @EmpLeaveProfileId
	
		SELECT 1
	end

	--UPDATE	L_EmployeeLeaveProfiles
	--SET		AdjustDays		=	@AdjustmentDays,
	--		--BalanceDays		=	EntitlementDays + CarryForwardDays + @AdjustmentDays + DaysLieu - DaysUsed
	--		BalanceDays		=	BalanceDays + @AdjustmentDays
	--WHERE	EmpProfileId	=	@EmpLeaveProfileId
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateEmployeeLeaveProfileForBalance')
	DROP PROC prL_UpdateEmployeeLeaveProfileForBalance
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_UpdateEmployeeLeaveProfileForBalance
	@CarryForward	Bit,
	@EmployeeId		BigInt,
	@ExceptionId	BigInt,
	@LeaveYear		Int
AS
DECLARE @DaysInLieuId BigInt = 0, @RamadanDaysInLieuId BigInt = 0

SELECT	@DaysInLieuId = IsNull(ParamValue,0) FROM D_SystemParams WITH (NOLOCK) Where ParamName = 'DaysInLieuId' 

SELECT	@RamadanDaysInLieuId =  IsNull(D_ExceptionCodes.ExceptionCodeId, 0)
FROM	D_ExceptionCodes WITH (NOLOCK)
WHERE	ExcpetionCodeName = (SELECT ParamValue FROM D_SystemParams WITH (NOLOCK) Where ParamName = 'RamadanDaysInLieuCode')

if @CarryForward = 0 AND @ExceptionId != @DaysInLieuId  And @ExceptionId != @RamadanDaysInLieuId
begin
	update L_EmployeeLeaveProfiles
	set BalanceDays = IsNull(EntitlementDays,0) + IsNull(CarryForwardDays,0) + IsNull(AdjustDays,0) + IsNull(DaysLieu,0) - IsNull(DaysUsed,0)
	where Employeeid=@EmployeeId AND ExceptionId = @ExceptionId And LeaveYear = @LeaveYear
	
	SELECT 1
end
Else if @CarryForward =1 AND @ExceptionId != @DaysInLieuId And @ExceptionId != @RamadanDaysInLieuId
begin
	update L_EmployeeLeaveProfiles
	set BalanceDays = IsNull(EarnedDays,0) + IsNull(CarryForwardDays,0) + IsNull(AdjustDays,0) + IsNull(DaysLieu,0) - IsNull(DaysUsed,0) + IsNull(EarnedDays_Adj,0)
	where Employeeid=@EmployeeId AND ExceptionId = @ExceptionId And LeaveYear = @LeaveYear

	SELECT 1
end
Else If @CarryForward = 0 AND (@ExceptionId = @DaysInLieuId OR @ExceptionId = @RamadanDaysInLieuId)
begin
	update L_EmployeeLeaveProfiles
	set BalanceDays = IsNull(EarnedDays,0) + IsNull(CarryForwardDays,0) + IsNull(AdjustDays,0) + IsNull(DaysLieu,0) - IsNull(DaysUsed,0)
	where Employeeid=@EmployeeId AND ExceptionId = @ExceptionId And LeaveYear = @LeaveYear
	
	SELECT 1
end
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateEmployeeLeaveProfilesByEmpProfileId')
	DROP PROC prL_UpdateEmployeeLeaveProfilesByEmpProfileId
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATe PROC [dbo].[prL_UpdateEmployeeLeaveProfilesByEmpProfileId]
	@EmpProfileId bigint,
	@EmployeeId bigint = NULL,
	@LeaveProfileId int = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@LeaveYear int = NULL,
	@ExceptionId bigint = NULL,
	@EntitlementDays decimal(18, 2) = NULL,
	@CarryForwardDays decimal(18, 2) = NULL,
	@EarnedDays decimal(18, 2) = NULL,
	@DaysUsed decimal(18, 2) = NULL,
	@AdjustDays decimal(18, 2) = NULL,
	@DaysLieu decimal(18, 2) = NULL,
	@UsedDays decimal(18, 2) = NULL,
	@BalanceDays decimal(18, 2) = NULL,
	@EarnedDays_Cal decimal(18, 2) = NULL,
	@EarnedDays_Adj decimal(18, 2) = NULL,
	@EarnedMonth int = NULL,
	@AdjustmentRemakrs text = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@CreatedDate datetime = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdatedDate datetime = NULL
AS

UPDATE	L_EmployeeLeaveProfiles
SET	EmployeeId = @EmployeeId,
	LeaveProfileId = @LeaveProfileId,
	StartDate = @StartDate,
	EndDate = @EndDate,
	LeaveYear = @LeaveYear,
	ExceptionId = @ExceptionId,
	EntitlementDays = @EntitlementDays,
	CarryForwardDays = @CarryForwardDays,
	EarnedDays = @EarnedDays,
	DaysUsed = @DaysUsed,
	AdjustDays = @AdjustDays,
	DaysLieu = @DaysLieu,
	UsedDays = @UsedDays,
	BalanceDays = @BalanceDays,
	EarnedDays_Cal = @EarnedDays_Cal,
	EarnedDays_Adj = @EarnedDays_Adj,
	EarnedMonth = @EarnedMonth,
	AdjustmentRemakrs = @AdjustmentRemakrs,
	CreatedBy = @CreatedBy,
	CreatedDate = @CreatedDate,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = @UpdatedDate
WHERE 	EmpProfileId = @EmpProfileId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateEmployeeWorkflowRoute')
	DROP PROC prL_UpdateEmployeeWorkflowRoute
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_UpdateEmployeeWorkflowRoute
----------------------------------------------------------------------------
CREATE PROC prL_UpdateEmployeeWorkflowRoute
(
	@EmployeeWorkflowId		BigInt,
	@EmployeeId				BigInt,
	@ModuleId				int,
	@RouteId				BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN

	UPDATE	C_EmployeeWorkflow
	SET		EmployeeId			=	@EmployeeId, 
			ModuleId			=	@ModuleId, 
			RouteId				=	@RouteId, 
			StartDate			=	@StartDate, 
			EndDate				=	@EndDate, 
			UpdatedBy			=	@UpdatedBy, 
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeWorkflowId	=	@EmployeeWorkflowId

	SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeave')
	DROP PROC prL_UpdateLeave
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_UpdateLeave
----------------------------------------------------------------------------
CREATE PROC prL_UpdateLeave
(
	@LeaveId			BigInt,
	@OuId				BigInt,
	@EmployeeId			BigInt,
	@ExceptionCodeId	BigInt,
	@LeaveStart			DateTime,
	@LeaveEnd			DateTime,
	@LeaveType			Int,
	@NoOfDays			Decimal(18,2),
	@ReasonId			Int,
	@IsEmergency		Bit,
	@ApprovalStatusId	Int,
	@ReferenceNo		nVarchar(50),
	@Remarks			text,
	@AppliedBy			nVarchar(50),
	@AppliedDate		DateTime,
	@ApprovedBy			nVarchar(50),
	@ApprovedDate		DateTime,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	UPDATE	L_Leaves
	SET		OUId				=	@OuId, 
			EmployeeId			=	@EmployeeId,	
			ExceptionCodeId		=	@ExceptionCodeId, 
			LeaveStart			=	@LeaveStart, 
			LeaveEnd			=	@LeaveEnd, 
			LeaveType			=	@LeaveType, 
			NoOfDays			=	@NoOfDays, 
			ReasonId			=	@ReasonId, 
			IsEmergency			=	@IsEmergency, 
			ApprovalStatusId	=	@ApprovalStatusId,
			ReferenceNo			=	@ReferenceNo, 
			Remarks				=	@Remarks, 
			AppliedBy			=	@AppliedBy, 
			AppliedDate			=	@AppliedDate, 
			ApprovedBy			=	@ApprovedBy, 
			ApprovedDate		=	@ApprovedDate, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	LeaveId				=	@LeaveId
	SELECT  1
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeaveApplicationStatus')
	DROP PROC prL_UpdateLeaveApplicationStatus
GO

CREATE PROC prL_UpdateLeaveApplicationStatus
	@LeaveId			BigInt,
	@ApprovalStatusId	Int,
	@ApprovedBy			nVarchar(50),
	@ApprovedDate		DateTime,
	@ModuleTypeId		Int
AS
BEGIN
	DECLARE @IsApproved Int = 0

	If (@ApprovedDate IS NULL) SET @ApprovedDate = GETDATE()
	If (@ModuleTypeId = 201)
	BEGIN
		
		-- Check Whether Approval Status Id Is Approved Or Rejected.
		-- If Approved Or Rejected, Check only for that status
		If (@ApprovalStatusId = 1 OR @ApprovalStatusId = 2)
		BEGIN
			SELECT	@IsApproved = COUNT(*) 
			FROM	L_Leaves WITH (NOLOCK)
			WHERE	L_Leaves.LeaveId	=	@LeaveId
			And		L_Leaves.ApprovalStatusId IN (1, 2)
		END
		-- If Status is Cancellation Approved Or Rejected, CHeck for ONly Those status
		Else If (@ApprovalStatusId = 5 OR @ApprovalStatusId = 7)
		BEGIN
			SELECT	@IsApproved = COUNT(*) 
			FROM	L_Leaves WITH (NOLOCK)
			WHERE	L_Leaves.LeaveId	=	@LeaveId
			And		L_Leaves.ApprovalStatusId IN (5, 7)
		END
		
		If (@IsApproved = 0)
		BEGIN
			UPDATE	L_Leaves
			SET		ApprovalStatusId	=	@ApprovalStatusId,
					ApprovedBy			=	@ApprovedBy,
					ApprovedDate		=	@ApprovedDate,
					UpdatedBy			=	@ApprovedBy,
					UpdatedDate			=	GETDATE()
			WHERE	LeaveId				=	@LeaveId
			
			SELECT 1
		END
		ELSE SELECT 99
	END
	Else If (@ModuleTypeId = 202)
	BEGIN
		SELECT	@IsApproved = COUNT(*) 
		FROM	L_RequestDaysInLieu WITH (NOLOCK)
		WHERE	L_RequestDaysInLieu.DaysInLieuId	=	@LeaveId
		And		L_RequestDaysInLieu.ApprovalStatusId IN (1, 2, 5, 7)
		
		If (@IsApproved = 0)
		BEGIN
			UPDATE	L_RequestDaysInLieu
			SET		ApprovalStatusId	=	@ApprovalStatusId,
					--ApprovedBy			=	@ApprovedBy,
					ApprovedDate		=	@ApprovedDate
					--UpdatedBy			=	@ApprovedBy,
					--UpdatedDate			=	GETDATE()
			WHERE	DaysInLieuId			=	@LeaveId

			SELECT 1
		END
		ELSE SELECT 99
	END
	Else If (@ModuleTypeId = 203)
	BEGIN

		SELECT	@IsApproved = COUNT(*) 
		FROM	L_TimeOff WITH (NOLOCK)
		WHERE	L_TimeOff.TimeOffId	=	@LeaveId
		And		L_TimeOff.ApprovalStatusId IN (1, 2, 5, 7)
		
		If (@IsApproved = 0)
		BEGIN
			UPDATE	L_TimeOff
			SET		ApprovalStatusId	=	@ApprovalStatusId,
					--ApprovedBy			=	@ApprovedBy,
					ApprovedDate		=	@ApprovedDate
					--UpdatedBy			=	@ApprovedBy,
					--UpdatedDate			=	GETDATE()
			WHERE	TimeOffId			=	@LeaveId

			SELECT 1
		END
		ELSE SELECT 99
	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeaveBalance')
	DROP PROC prL_UpdateLeaveBalance
GO

----------------------------------------------------------------------------
-- Insert a single record into L_RequestDaysInLieu
----------------------------------------------------------------------------
CREATE PROC prL_UpdateLeaveBalance
(
	@ExceptionId		BigInt,
	@EmployeeId			BigInt,
	@LeaveYear			Int,
	@DaysToDeduct		Decimal(18,2),
	@DeductionType		Int, -- 0 => Deduct From Balance, 1 => Add To Balance, 3 => Add Earned And Balance, 4 => Deduct Earned, Balance
	@UpdatedBy			nVarchar(50)
)
AS

BEGIN
	
	If (@DeductionType = 0)
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		DaysUsed		=	DaysUsed + @DaysToDeduct,
				BalanceDays		=	BalanceDays - @DaysToDeduct
		WHERE	EmployeeId		=	@EmployeeId
		AND		ExceptionId		=	@ExceptionId
		AND		LeaveYear		=	@LeaveYear	
	END
	Else If (@DeductionType = 1)
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		DaysUsed		=	DaysUsed - @DaysToDeduct,
				BalanceDays		=	BalanceDays + @DaysToDeduct
		WHERE	EmployeeId		=	@EmployeeId
		AND		ExceptionId		=	@ExceptionId
		AND		LeaveYear		=	@LeaveYear
	END
	Else If (@DeductionType = 3)
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		EarnedDays		=	EarnedDays  + @DaysToDeduct,
				BalanceDays		=	BalanceDays + @DaysToDeduct
				--DaysLieu		=	DaysLieu + @DaysToDeduct
		WHERE	EmployeeId		=	@EmployeeId
		AND		ExceptionId		=	@ExceptionId
		AND		LeaveYear		=	@LeaveYear
	END
	Else If (@DeductionType = 4) -- From Cancellation Approved on Approved Requested Days In Lieu
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		EarnedDays		=	EarnedDays  - @DaysToDeduct,
				BalanceDays		=	BalanceDays - @DaysToDeduct
				--DaysLieu		=	DaysLieu + @DaysToDeduct
		WHERE	EmployeeId		=	@EmployeeId
		AND		ExceptionId		=	@ExceptionId
		AND		LeaveYear		=	@LeaveYear
	END

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeaveProfile')
	DROP PROC prL_UpdateLeaveProfile
GO

----------------------------------------------------------------------------
-- Update a single record into prL_UpdateLeaveProfile
----------------------------------------------------------------------------
CREATE PROC prL_UpdateLeaveProfile
(
	@LeaveProfileId			BigInt			=	NULL,
	@LeaveProfileHeaderId	Int,
	@ExceptionCodeId		BigInt			=	NULL,
	@EntitlementDays		Decimal(18,2),
	@CarryForward			Bit,
	@MaximumDaysPerYear		Decimal(18,2),
	@Accural				Bit,
	@CarryForwardDateType	Int,
	@CarryForwardDate		DateTime,
	@DayCalculation			Int,
	@DaysInAdvance			Decimal(18,2),
	@MinimumDaysRequest		Decimal(18,2),
	@MaximumDaysRequest		Decimal(18,2),
	@RequestPerYear			Int,
	@NegativeBalance		Bit,
	@MaximumDaysNegative	Decimal(18,2),
	@HalfDays				Bit,
	@ActiveStatus			Bit,
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	--SELECT	@ValidateDuplicate =  COUNT(*) 
	--FROM	L_LeaveProfiles WITH (NOLOCK)
	--WHERE	ExceptionCodeId	= @ExceptionCodeId
	--AND		LeaveProfileId	= @LeaveProfileId
	--AND		LeaveProfileHeaderId = @LeaveProfileHeaderId

	--If (@ValidateDuplicate = 0)
	--BEGIN
	--	UPDATE	L_LeaveProfiles
	--	SET		LeaveProfileHeaderId	=	@LeaveProfileHeaderId,
	--			ExceptionCodeId			=	@ExceptionCodeId, 
	--			EntitlementDays			=	@EntitlementDays, 
	--			CarryForward			=	@CarryForward, 
	--			MaximumDaysPerYear		=	@MaximumDaysPerYear, 
	--			Accural					=	@Accural,
	--			CarryforwardDateType	=	@CarryforwardDateType, 
	--			CarryforwardDate		=	@CarryforwardDate, 
	--			DayCalculation			=	@DayCalculation, 
	--			DaysInAdvance			=	@DaysInAdvance, 
	--			MinimumDaysRequest		=	@MinimumDaysRequest, 
	--			MaximumDaysRequest		=	@MaximumDaysRequest, 
	--			RequestPerYear			=	@RequestPerYear, 
	--			NegativeBalance			=	@NegativeBalance, 
	--			MaximumDaysNegative		=	@MaximumDaysNegative,
	--			HalfDays				=	@HalfDays, 
	--			ActiveStatus			=	@ActiveStatus, 
	--			UpdatedBy				=	@UpdatedBy,
	--			UpdatedDate				=	GETDATE()
	--	WHERE	LeaveProfileId			=	@LeaveProfileId

	--	SELECT  1
	--END
	--ELSE
	--BEGIN
	--	SET @ValidateDuplicate = -1
	--	SELECT @ValidateDuplicate
	--END

	UPDATE	L_LeaveProfiles
		SET		LeaveProfileHeaderId	=	@LeaveProfileHeaderId,
				ExceptionCodeId			=	@ExceptionCodeId, 
				EntitlementDays			=	@EntitlementDays, 
				CarryForward			=	@CarryForward, 
				MaximumDaysPerYear		=	@MaximumDaysPerYear, 
				Accural					=	@Accural,
				CarryforwardDateType	=	@CarryforwardDateType, 
				CarryforwardDate		=	@CarryforwardDate, 
				DayCalculation			=	@DayCalculation, 
				DaysInAdvance			=	@DaysInAdvance, 
				MinimumDaysRequest		=	@MinimumDaysRequest, 
				MaximumDaysRequest		=	@MaximumDaysRequest, 
				RequestPerYear			=	@RequestPerYear, 
				NegativeBalance			=	@NegativeBalance, 
				MaximumDaysNegative		=	@MaximumDaysNegative,
				HalfDays				=	@HalfDays, 
				ActiveStatus			=	@ActiveStatus, 
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()
		WHERE	LeaveProfileId			=	@LeaveProfileId

		SELECT  1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeaveProfileHeader')
	DROP PROC prL_UpdateLeaveProfileHeader
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_UpdateLeaveProfileHeader
----------------------------------------------------------------------------
CREATE PROC prL_UpdateLeaveProfileHeader
(
	@LeaveProfileHeaderId	Int,
	@LeaveProfileName		nVarchar(50),
	@Remarks				nVarchar(1000),
	@ActiveStatus			Bit,
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate	=  COUNT(*) 
	FROM	L_LeaveProfileHeader WITH (NOLOCK)
	WHERE	ProfileName			  = @LeaveProfileName
	AND		LeaveProfileHeaderId != @LeaveProfileHeaderId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	L_LeaveProfileHeader
		SET		ProfileName			=	@LeaveProfileName, 
				Remarks				=	@Remarks, 
				ActiveStatus		=	@ActiveStatus, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	LeaveProfileHeaderId = @LeaveProfileHeaderId

		SELECT  1 
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateLeaveThresholdByThresholdId')
	DROP PROC prL_UpdateLeaveThresholdByThresholdId
GO

----------------------------------------------------------------------------
-- Update a single record in L_LeaveThreshold
----------------------------------------------------------------------------
CREATE PROC prL_UpdateLeaveThresholdByThresholdId
	@ThresholdId bigint,
	@ThresholdValue decimal(18, 5) = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdatedDate datetime = NULL
AS

UPDATE	L_LeaveThreshold
SET		ThresholdValue = @ThresholdValue,
		UpdatedBy = @UpdatedBy,
		UpdatedDate = @UpdatedDate
WHERE 	ThresholdId = @ThresholdId

SELECT 1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateRequestDaysInLieu')
	DROP PROC prL_UpdateRequestDaysInLieu
GO

----------------------------------------------------------------------------
-- Insert a single record into L_RequestDaysInLieu
----------------------------------------------------------------------------
CREATE PROC prL_UpdateRequestDaysInLieu
(
	@DaysInLieuId		BigInt,
	@EmployeeId			BigInt,
	@RequestedDate		DateTime,
	@Remarks			nVarchar(100),
	@ApprovalStatusId	Int,
	@ApproverId			BigInt,
	@AppliedDate		DateTime,
	@ApprovedDate		DateTime,
	@CreatedBy			nVarchar(50)
)
AS

BEGIN

	UPDATE	L_RequestDaysInLieu
	SET		EmployeeId			=	@EmployeeId, 
			Remarks				=	@Remarks, 
			ApprovalStatusId	=	@ApprovalStatusId, 
			ApproverId			=	@ApproverId, 
			AppliedDate			=	@AppliedDate, 
			ApprovedDate		=	@ApprovedDate, 
			CreatedBy			=	@CreatedBy,
			CreatedDate			=	GETDATE()
	WHERE	DaysInLieuId		=	@DaysInLieuId

	SELECT 1	
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateTimeOff')
	DROP PROC prL_UpdateTimeOff
GO

----------------------------------------------------------------------------
-- Insert a single record into L_TimeOff
----------------------------------------------------------------------------
CREATE PROC prL_UpdateTimeOff
(
	@TimeOffId			BigInt,
	@EmployeeId			BigInt,
	@StartTime			DateTime,
	@Duration			Decimal(18,2),
	@BreakHours			Decimal(18,2),
	@Remarks			nVarchar(100),
	@ApprovalStatusId	Int,
	@ApproverId			BigInt,
	@AppliedDate		DateTime,
	@ApprovedDate		DateTime,
	@ShiftId			BigInt,
	@CreatedBy			nVarchar(50)
)
AS

BEGIN
	UPDATE	L_TimeOff
	SET		EmployeeId			=	@EmployeeId, 
			StartTime			=	@StartTime, 
			Duration			=	@Duration, 
			BreakHours			=	@BreakHours, 
			Remarks				=	@Remarks, 
			ApprovalStatusId	=	@ApprovalStatusId, 
			ApproverId			=	@ApproverId, 
			AppliedDate			=	@AppliedDate, 
			ApprovedDate		=	@ApprovedDate, 
			ShiftId				=	@ShiftId,
			CreatedBy			=	@CreatedBy,
			CreatedDate			=	GETDATE()
	WHERE	TimeoffId			=	@TimeOffId

	SELECT 1	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_UpdateTimeOffStatus')
	DROP PROC prL_UpdateTimeOffStatus
GO

CREATE PROC prL_UpdateTimeOffStatus
	@TimeOffId			BigInt,
	@ApprovalStatusId	Int,
	@ApproverId			BigInt,
	@ApprovedDate		DateTime
AS
BEGIN
	UPDATE	L_TimeOff
	SET		ApprovalStatusId	=	@ApprovalStatusId,
			ApproverId			=	@ApproverId,
			ApprovedDate		=	@ApprovedDate
	WHERE	TimeOffId			=	@TimeOffId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_ValidateHajLeave')
	DROP PROC prL_ValidateHajLeave
GO

CREATE PROC prL_ValidateHajLeave
(
	@EmployeeId			BigInt,
	@ExceptionCodeId	BigInt,
	@LeaveId			BigInt,
	@LeaveStartDate		DateTime,
	@LeaveEndDate		DateTime			
)	
AS
BEGIN

	-- This Procedures is to return the sample output object for each procedure which is stored in the
	-- L_Validations Table. And the above Parameters are required with default values if not in use.

	SELECT	Convert(Bit, 1) IsSuccess,
			'Haj Leave Validation Success' ReturnResult,
			'' ReturnResultCode,
			'Leave Application Validation' ReturnResultTitle 
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddAuxiliaryWork')
	DROP PROC prM_AddAuxiliaryWork
GO

----------------------------------------------------------------------------
-- Insert a single record into M_AuxiliaryWork
----------------------------------------------------------------------------
CREATE PROC prM_AddAuxiliaryWork
	@OUId bigint = NULL,
	@ShiftBandId bigint = NULL,
	@SkillId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@Requirement int =null,
	@WorkloadGenereated bit = NULL,
	@SignOffStatus bit = NULL,
	@CreatedBy nvarchar(100) = NULL

AS

INSERT M_AuxiliaryWork(OUId, ShiftBandId, SkillId, StartDate, EndDate,Requirement, WorkloadGenereated, SignOffStatus, CreatedDate, CreatedBy)
VALUES (@OUId, @ShiftBandId, @SkillId, @StartDate, @EndDate,@Requirement, @WorkloadGenereated, @SignOffStatus, GETDATE(), @CreatedBy)

select  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddCraneSchedule')
	DROP PROCEDURE prM_AddCraneSchedule

GO

CREATE PROC prM_AddCraneSchedule
	@OUId bigint = NULL,
	@CraneId bigint = NULL,
	@VesselScheduleId bigint = NULL,
	@LocationId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@Imported bit = NULL,
	@WorkloadGenerated bit = NULL,
	@SignOffStatus bit = NULL,
	@CreatedBy nvarchar(100) = NULL

AS

INSERT M_CraneSchedule(OUId, CraneId, VesselScheduleId, LocationId, StartDate, EndDate, Imported, WorkloadGenerated, SignOffStatus, CreatedDate, CreatedBy)
VALUES (@OUId, @CraneId, @VesselScheduleId, @LocationId, @StartDate, @EndDate, @Imported, @WorkloadGenerated, @SignOffStatus, GETDATE(), @CreatedBy) 

select  CAST(@@Identity AS INTEGER) 

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddEquipmentSchedule')
	DROP PROC prM_AddEquipmentSchedule
GO

----------------------------------------------------------------------------
-- Insert a single record into M_EquipmentSchedule
----------------------------------------------------------------------------
CREATE PROC prM_AddEquipmentSchedule
	@OUId bigint = NULL,
	@EquipmentTypeId bigint = NULL,
	@EquipmentId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@CraneScheduleId bigint = NULL,
	@WorkloadGenereated bit = NULL,
	@SignOffStatus bit = NULL,
	@CreatedBy nvarchar(100) = NULL

AS

INSERT M_EquipmentSchedule(OUId, EquipmentTypeId, EquipmentId, StartDate, EndDate, CraneScheduleId, WorkloadGenereated, SignOffStatus, CreatedDate, CreatedBy)
VALUES (@OUId, @EquipmentTypeId, @EquipmentId, @StartDate, @EndDate, @CraneScheduleId, @WorkloadGenereated, @SignOffStatus, GETDATE(), @CreatedBy)

select  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddResourceSet')
	DROP PROC prM_AddResourceSet
GO

----------------------------------------------------------------------------
-- Insert a single record into M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC prM_AddResourceSet
	@OUId bigint = NULL,
	@SetName nvarchar(1000) = NULL,
	@SetDesc nvarchar(2000) = NULL,
	@ActiveStatus bit = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT M_ResourceSet(OUId, SetName, SetDesc, ActiveStatus, CreatedBy, CreatedDate)
VALUES (@OUId, @SetName, @SetDesc, @ActiveStatus, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddShiftSignOffStatus')
	DROP PROC prM_AddShiftSignOffStatus
GO

----------------------------------------------------------------------------
-- Insert a single record into M_ShiftSignOffStatus
----------------------------------------------------------------------------
CREATE PROC prM_AddShiftSignOffStatus
	@OUId bigint = NULL,
	@ShiftDate date = NULL,
	@ShiftBandId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@Status int = NULL,
	@SignedOffBy nvarchar(100) = NULL,
	@SignedOffDate datetime = NULL
AS

UPDATE J_Activity SET ProgresstionState = 2 WHERE StartTime >= @StartTime AND StartTime < @EndTime

UPDATE J_Workload SET SignOffStatus = 1 WHERE StartTime >= @StartTime AND StartTime < @EndTime

UPDATE M_EquipmentSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime

UPDATE M_CraneSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime

UPDATE M_VesselSchedule SET Status = 2 WHERE StartDate >= @StartTime AND StartDate < @EndTime

EXEC prJ_AddPlanningRequirements @OUId, @ShiftBandId, @ShiftDate, @StartTime, @EndTime, @SignedOffBy

EXEC prJ_AddPlanningEquipmentRequirements @OUId, @ShiftBandId, @ShiftDate, @StartTime, @EndTime, @SignedOffBy

INSERT M_ShiftSignOffStatus(OUId, ShiftDate, ShiftBandId, StartTime, EndTime, Status, SignedOffBy, SignedOffDate)
VALUES (@OUId, @ShiftDate, @ShiftBandId, @StartTime, @EndTime, @Status, @SignedOffBy, @SignedOffDate)

select  CAST(@@Identity AS INTEGER) 

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AddVesselList')
	DROP PROCEDURE prM_AddVesselList
GO

CREATE PROC prM_AddVesselList
	@VesselName nvarchar(1000) = NULL,
	@LastVisitStartDate datetime = NULL,
	@LastVisitEndDate datetime = NULL,
	@CraneReq int = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT M_VesselList(VesselName, LastVisitStartDate, LastVisitEndDate, CraneReq, CreatedBy, CreatedDate)
VALUES (@VesselName, @LastVisitStartDate, @LastVisitEndDate, @CraneReq, @CreatedBy, GETDATE())

select  CAST(@@Identity AS INTEGER) 

GO


/****** Object:  StoredProcedure [dbo].[prM_AddVesselSchedule]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_AddVesselSchedule]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prM_AddVesselSchedule
GO
CREATE PROC [dbo].[prM_AddVesselSchedule]
	@OUId bigint = NULL,
	@VesselName nvarchar(2000) = NULL,
	@VisitId nvarchar(200) = NULL,
	@BerthId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@ETA datetime = NULL,
	@ETD datetime = NULL,
	@NoOfCraneReq int = NULL,
	@Priority int = NULL,
	@Status int = NULL,
	@CraneScheduled bit = NULL,
	@IsImported bit = NULL,
	@VesselType	nVarchar(100) = NULL,
	@Remarks	nVarchar(500) = NULL,
	@ResourceSetId BigInt = NULL,
	@CreatedBy nvarchar(100) = NULL
AS
declare @VesselScheduleId bigint
declare @Count int

INSERT M_VesselSchedule(OUId, VesselName, VisitId, BerthId, StartDate, EndDate, ETA, ETD, NoOfCraneReq, Priority, Status, CraneScheduled, IsImported, ResourcesetId, VesselType, Remarks, CreatedBy, CreatedDate)
VALUES (@OUId, @VesselName, @VisitId, @BerthId, @StartDate, @EndDate, @ETA, @ETD, @NoOfCraneReq, COALESCE(@Priority, (1)), COALESCE(@Status, (1)), COALESCE(@CraneScheduled, (0)), COALESCE(@IsImported, (0)), @ResourceSetId, @VesselType, @Remarks, @CreatedBy, GETDATE())

select  @VesselScheduleId = CAST(@@Identity AS INTEGER) 


select @Count = count(*) from M_VesselList WITH (NOLOCK)
where VesselName=@VesselName

IF @Count > 0 
BEGIN
	UPDATE M_VesselList
	SET LastVisitStartDate =@StartDate, LastVisitEndDate = @EndDate,CraneReq=@NoOfCraneReq, UpdatedBy=@CreatedBy,UpdatedDate=GETDATE()
	WHERE VesselName=@VesselName
END 
ELSE
BEGIN
	INSERT INTO M_VesselList(VesselName,LastVisitStartDate,LastVisitEndDate,CraneReq,CreatedBy,CreatedDate)
	VALUES(@VesselName,@StartDate,@EndDate,@NoOfCraneReq,@CreatedBy,GETDATE())
END


SELECT @VesselScheduleId

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_AllCraneRequirementSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_AllCraneRequirementSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_AllCraneRequirementSel]  
(
	
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Crane_Requirement.CraneReqId,
			M_Crane_Requirement.OUId,
			M_Crane_Requirement.SkillId, 
			M_Crane_Requirement.Requirement ,
			M_Crane_Requirement.CreatedBy, 
			M_Crane_Requirement.CreatedDate,
			M_Crane_Requirement.UpdatedBy,
			M_Crane_Requirement.UpdatedDate,
			D_Skill.Skill as SkillName
	FROM	M_Crane_Requirement	  WITH (NOLOCK)
	INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Crane_Requirement.OUId = C_OrganizationNode.OUId
	left outer join D_Skill WITH (NOLOCK) on D_Skill.SkillId= M_Crane_Requirement.SkillId 			 
	WHERE	M_Crane_Requirement.OUId = @OUID
	 
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_AuxiliaryScheduleDel')
	DROP PROC prM_AuxiliaryScheduleDel
GO

----------------------------------------------------------------------------
-- Delete a single record from prM_AuxiliaryScheduleDel
----------------------------------------------------------------------------
CREATE PROC prM_AuxiliaryScheduleDel
	@AuxiliaryScheduleId bigint
AS

DELETE	M_AuxiliaryWork
WHERE 	ScheduleId = @AuxiliaryScheduleId

SELECT 1

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthCranesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthCranesDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthCranesDel]
(
	@BerthId		BigInt ,
	@CraneId		BigInt
)
AS
BEGIN
	DELETE FROM 	M_BerthCranes 
	WHERE	BerthId	=	@BerthId and CraneId =@CraneId

	SELECT 1
END 

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthCranesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthCranesIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthCranesIns]    
(		
	@BerthId				Bigint, 
	@CraneId				bigint , 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_BerthCranes WITH (NOLOCK)
	WHERE	BerthId=@BerthId and CraneId=@CraneId 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_BerthCranes
		( BerthId,CraneId,CreatedBy, CreatedDate)
		VALUES(@BerthId,@CraneId,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthCranesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthCranesSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_BerthCranesSel]   
(
	@BerthId		bigint 
)
AS
BEGIN
	SELECT	M_BerthCranes.BerthCraneId,
			M_BerthCranes.BerthId,
			M_BerthCranes.CraneId,  
			M_BerthCranes.CreatedBy, 
			M_BerthCranes.CreatedDate,
			M_BerthCranes.UpdatedBy,
			M_BerthCranes.UpdatedDate,
			M_Cranes.CraneNumber as CraneNumber
	FROM	M_BerthCranes	  WITH (NOLOCK)
	left outer join M_Cranes WITH (NOLOCK) on M_Cranes.CraneId= M_BerthCranes.CraneId 			 
	WHERE	(M_BerthCranes.BerthId = @BerthId )
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthCranesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthCranesUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthCranesUpd]    
(
	@BerthCraneId		BigInt,
	@BerthId					Bigint, 
	@CraneId		bigint,	 	 
	@Requirement		INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_BerthCranes WITH (NOLOCK)
	WHERE	  BerthId=@BerthId and CraneId=@CraneId
	AND		BerthCraneId	!=	@BerthCraneId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_BerthCranes
		SET		BerthId			=	@BerthId, 
				CraneId		=	@CraneId,	 
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	BerthCraneId			=	@BerthCraneId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthDel]    
(	
	@BerthId	           BigInt 
)
AS
BEGIN
	 

	Update M_Berth  set ActiveStatus =0 where BerthId =@BerthId 
	SELECT 1
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthIns]    
(		
	@OUId				Bigint, 
	@Berth				nvarchar(50),
	@BerthDesc			nvarchar(1000),	 
	@ActiveStatus		INT,	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Berth WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Berth))) = LTrim(RTrim(Upper(@Berth)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_Berth
		( OUId,Berth,BerthDesc,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@OUId,@Berth,@BerthDesc,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_BerthSel]    
(
	@BerthId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Berth.BerthId,
			M_Berth.OUId,
			M_Berth.Berth,
			M_Berth.BerthDesc,		 
			M_Berth.ActiveStatus,						 
			M_Berth.CreatedBy, 
			M_Berth.CreatedDate,
			M_Berth.UpdatedBy,
			M_Berth.UpdatedDate		 
	FROM	M_Berth	  WITH (NOLOCK)			 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Berth.OUId = C_OrganizationNode.OUId
	WHERE	(M_Berth.BerthId = @BerthId OR @BerthId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_BerthUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_BerthUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_BerthUpd]    
(
	@BerthId		BigInt,
	@OUId				Bigint, 
	@Berth		nVarchar(50),
	@BerthDesc			nVarchar(500),	 	 
	@ActiveStatus		INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Berth WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Berth))) = LTrim(RTrim(Upper(@Berth)))
	AND		BerthId	!=	@BerthId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_Berth
		SET		Berth			=	@Berth, 
				BerthDesc			=	@BerthDesc, 
				OUId			=	@OUId,			 
				ActiveStatus			=	@ActiveStatus, 			 
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	BerthId				=	@BerthId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneScheduleByDateRangeByBerthForOverlap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneScheduleByDateRangeByBerthForOverlap]
GO
 
 
create PROC [dbo].[prM_CraneScheduleByDateRangeByBerthForOverlap]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@CraneId int
AS

SELECT	*
FROM	M_CraneSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND CraneId = @CraneId
AND
(EndDate <= CONVERT(DATETIME, @EndDate)
AND StartDate >= CONVERT(DATETIME, @StartDate))

go



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneScheduleByDateRangeByCraneForOverlap_EndTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneScheduleByDateRangeByCraneForOverlap_EndTime]
GO
 
create PROC [dbo].[prM_CraneScheduleByDateRangeByCraneForOverlap_EndTime]
	@OUId bigint,
	@EndTime DateTime,
	@CraneId Bigint
AS

SELECT	*
FROM	M_CraneSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND CraneId = @CraneId
AND
(EndDate >= CONVERT(DATETIME, @EndTime)
AND StartDate < CONVERT(DATETIME, @EndTime))

go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneScheduleByDateRangeByCraneIdForOverlap_StartTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneScheduleByDateRangeByCraneIdForOverlap_StartTime]
GO
 
create PROC [dbo].[prM_CraneScheduleByDateRangeByCraneIdForOverlap_StartTime]
	@OUId bigint,
	@StartDate DateTime,
	@CraneId int
AS

SELECT	*
FROM	M_CraneSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND CraneId = @CraneId
AND
(EndDate > CONVERT(DATETIME, @StartDate)
AND StartDate <= CONVERT(DATETIME, @StartDate))

go



IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_CraneScheduleDel')
	DROP PROC prM_CraneScheduleDel
GO

----------------------------------------------------------------------------
-- Delete a single record from prM_CraneScheduleDel
----------------------------------------------------------------------------
CREATE PROC prM_CraneScheduleDel
	@CraneScheduleId bigint
AS
BEGIN
	CREATE TABLE ##DelCraneActivities (ActivityId BigInt);
	
	INSERT INTO ##DelCraneActivities 
	SELECT	J_Activity.ActivityId
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
	WHERE	J_ActivityAttributes.ScheduleId IN 
	(	
		SELECT EquipmentScheduleId FROM M_EquipmentSchedule WITH (NOLOCK) WHERE CraneScheduleId IN 
		(
			SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE CraneScheduleId = @CraneScheduleId
		)
	)
	UNION ALL
	SELECT	J_Activity.ActivityId
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 1 -- Crane Schedule
	WHERE	J_ActivityAttributes.ScheduleId IN 
	(
		SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE CraneScheduleId = @CraneScheduleId
	)
	ORDER BY ActivityId
	--SELECT Activities.ActivityId From Activities

	-- Delete From J_WorkLoad
	DELETE FROM J_Workload WHERE CraneScheduleId = @CraneScheduleId

	-- Delete From J_ActivityAttributes Where Work Type = 1 -- Crane Schedule By Vessel Schedule Id
	DELETE FROM J_ActivityAttributes 
	WHERE	ActivityId IN 
			(	
				SELECT	J_Activity.ActivityId
				FROM	J_Activity WITH (NOLOCK)
						INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 1 -- Equipment Schedule
				WHERE	J_ActivityAttributes.ScheduleId IN 
				(
					SELECT CraneScheduleId FROM M_CraneSchedule WITH (NOLOCK) WHERE CraneScheduleId = @CraneScheduleId
				)
			)						  

	-- Delete From J_ActivityAttributes Where Work Type = 2 -- Equipment Schedule By Vessel Schedule Id
	DELETE FROM J_ActivityAttributes 
	WHERE	ActivityId IN 
			(	
				SELECT	J_Activity.ActivityId
				FROM	J_Activity WITH (NOLOCK)
						INNER JOIN J_ActivityAttributes WITH (NOLOCK) ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
				WHERE	J_ActivityAttributes.ScheduleId IN 
				(	
					SELECT EquipmentScheduleId FROM M_EquipmentSchedule WITH (NOLOCK) WHERE CraneScheduleId = @CraneScheduleId
				)
			)

	-- Delete Activity Records of those between Selected Shift Start And End Date By WorkType = 1 & 2 [Crane & Equipment Schedule]
	DELETE	FROM J_Activity 
	WHERE	ActivityId IN (SELECT ActivityId FROM ##DelCraneActivities)

	-- Delete From M_EquipmentSchedule
	DELETE	FROM M_EquipmentSchedule 
	WHERE	CraneScheduleId = @CraneScheduleId

	-- Delete From M_CraneSchedule
	DELETE FROM M_CraneSchedule WHERE CraneScheduleId = @CraneScheduleId

	DROP TABLE ##DelCraneActivities

	SELECT 1
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CranesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CranesDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_CranesDel]    
(	
	@CraneId	           BigInt 
)
AS
BEGIN
	 

	Update M_Cranes  set ActiveStatus =0 where CraneId =@CraneId 
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CranesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CranesIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_CranesIns]    
(		
	@OUId				Bigint, 
	@CraneNumber		nVarchar(50),
	@CraneDesc			nVarchar(500),	 
	@LocationId			bigint,	 
	@ActiveStatus		INT,	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Cranes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(CraneNumber))) = LTrim(RTrim(Upper(@CraneNumber)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_Cranes
		(CraneNumber,CraneDesc, OUId,LocationId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@CraneNumber, @CraneDesc,@OUId,@LocationId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CranesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CranesSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_CranesSel]    
(
	@CraneId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Cranes.CraneId,
			M_Cranes.OUId,
			M_Cranes.CraneNumber,
			M_Cranes.CraneDesc,
			M_Cranes.LocationId,
			M_Locations.LocationName,
			M_Locations.LocationDesc,
			M_Cranes.ActiveStatus,		 
			M_Cranes.CreatedBy, 
			M_Cranes.CreatedDate,
			M_Cranes.UpdatedBy,
			M_Cranes.UpdatedDate		 
	FROM	M_Cranes	  WITH (NOLOCK)			 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Cranes.OUId = C_OrganizationNode.OUId
			INNER JOIN M_Locations WITH (NOLOCK) ON M_Cranes.LocationId = M_Locations.LocationId
	WHERE	(M_Cranes.CraneId = @CraneId OR @CraneId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CranesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CranesUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_CranesUpd]    
(
	@CraneId		BigInt,
	@OUId				Bigint, 
	@CraneNumber		nVarchar(50),
	@CraneDesc			nVarchar(500),	 
	@LocationId			bigint,	 
	@ActiveStatus		INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Cranes WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(CraneNumber))) = LTrim(RTrim(Upper(@CraneNumber)))
	AND		CraneId	!=	@CraneId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_Cranes
		SET		CraneNumber			=	@CraneNumber, 
				CraneDesc			=	@CraneDesc, 
				OUId			=	@OUId,
				LocationId				=	@LocationId,
				ActiveStatus			=	@ActiveStatus, 			 
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	CraneId				=	@CraneId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_Crane_RequirementDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_Crane_RequirementDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_Crane_RequirementDel]
(
	@CraneReqId		BigInt 
)
AS
BEGIN
	DELETE FROM 	M_Crane_Requirement 
	WHERE	CraneReqId	=	@CraneReqId

	SELECT 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_Crane_RequirementIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_Crane_RequirementIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_Crane_RequirementIns]    
(		
	@OUId				Bigint, 
	@SkillId			bigint,	 
	@Requirement		INT,	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Crane_Requirement WITH (NOLOCK)
	WHERE	SkillId=@SkillId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_Crane_Requirement
		( OUId,SkillId,Requirement,CreatedBy, CreatedDate)
		VALUES(@OUId,@SkillId,@Requirement,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_Crane_RequirementSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_Crane_RequirementSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_Crane_RequirementSel]  
(
	@CraneReqId		bigint ,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Crane_Requirement.CraneReqId,
			M_Crane_Requirement.OUId,
			M_Crane_Requirement.SkillId, 
			M_Crane_Requirement.Requirement ,
			M_Crane_Requirement.CreatedBy, 
			M_Crane_Requirement.CreatedDate,
			M_Crane_Requirement.UpdatedBy,
			M_Crane_Requirement.UpdatedDate,
			D_Skill.Skill as SkillName
	FROM	M_Crane_Requirement	  WITH (NOLOCK)
	INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Crane_Requirement.OUId = C_OrganizationNode.OUId
	LEFT OUTER JOIN D_Skill WITH (NOLOCK) on D_Skill.SkillId= M_Crane_Requirement.SkillId 			 
	WHERE	(M_Crane_Requirement.CraneReqId = @CraneReqId OR @CraneReqId = 0)
	AND 	M_Crane_Requirement.OUId = @OUID
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_Crane_RequirementUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_Crane_RequirementUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_Crane_RequirementUpd]    
(
	@CraneReqId		BigInt,
	@OUId					Bigint, 
	@SkillId		bigint,	 	 
	@Requirement		INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Crane_Requirement WITH (NOLOCK)
	WHERE	  SkillId=@SkillId
	AND		CraneReqId	!=	@CraneReqId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_Crane_Requirement
		SET		OUId			=	@OUId, 
				SkillId		=	@SkillId, 				 
				Requirement			=	@Requirement, 				  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	CraneReqId			=	@CraneReqId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_DelEquipmentScheduleByDateRange')
	DROP PROC prM_DelEquipmentScheduleByDateRange
GO

----------------------------------------------------------------------------
-- Delete Scheduled Equipments Between Given Date Range And OU
----------------------------------------------------------------------------
CREATE PROC prM_DelEquipmentScheduleByDateRange
	@OUId					BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	@EquipmentMatrixId		BigInt
AS
BEGIN
	-- Create Equipment Schedule Temporary Table And Insert Equipment Schedule Id From Date Range By OU
	CREATE TABLE ##EquipmentSchedule	(EquipmentScheduleId BigInt)

	INSERT INTO	##EquipmentSchedule
	SELECT	EquipmentScheduleId
	FROM	M_EquipmentSchedule
	WHERE	Convert(DateTime,M_EquipmentSchedule.EndDate) > Convert(DateTime,@StartDate)
	AND		Convert(DateTime,M_EquipmentSchedule.StartDate) < Convert(DateTime,@EndDate)
	AND		M_EquipmentSchedule.EquipmentTypeId IN (SELECT EquipmentTypeId FROM E_EquipmentMatrix_EquipmentType WHERE MatrixId = @EquipmentMatrixId)
	AND		OUId	=	@OUId

	CREATE TABLE ##DelEquipmentActivities (ActivityId BigInt);
	
	INSERT INTO ##DelEquipmentActivities
	SELECT	J_Activity.ActivityId
	FROM	J_Activity  
			INNER JOIN J_ActivityAttributes ON J_Activity.ActivityId = J_ActivityAttributes.ActivityId  AND WorkType = 2 -- Equipment Schedule
			INNER JOIN ##EquipmentSchedule ON J_ActivityAttributes.ScheduleId = ##EquipmentSchedule.EquipmentScheduleId
	WHERE	J_ActivityAttributes.ScheduleId IN (SELECT	EquipmentScheduleId  FROM	##EquipmentSchedule)
	ORDER BY ActivityId
	
	-- Delete From J_WorkLoad
	DELETE	FROM J_Workload  WHERE	EquipmentScheduleId IN (SELECT	EquipmentScheduleId  FROM	##EquipmentSchedule )

	-- Delete From J_ActivityAttributes Where the Activity Id Available in Temporary Table
	DELETE FROM J_ActivityAttributes WHERE	ActivityId IN ( SELECT	ActivityId FROM	##DelEquipmentActivities )						  

	-- Delete Activity Records of those between Selected Shift Start And End Date By WorkType = 2 [Equipment Schedule]
	DELETE	FROM J_Activity  WHERE	ActivityId IN (SELECT ActivityId FROM ##DelEquipmentActivities)

	-- Delete From M_EquipmentSchedule
	DELETE	FROM M_EquipmentSchedule  WHERE	EquipmentScheduleId IN (SELECT EquipmentScheduleId FROM ##EquipmentSchedule)


	DROP TABLE ##DelEquipmentActivities
	DROP TABLE ##EquipmentSchedule

	SELECT 1
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_DeleteAuxiliaryWorkAndWorkLoadByDateRange')
	DROP PROC prM_DeleteAuxiliaryWorkAndWorkLoadByDateRange
GO

----------------------------------------------------------------------------
-- Select a single record from M_AuxiliaryWork
----------------------------------------------------------------------------
CREATE PROC prM_DeleteAuxiliaryWorkAndWorkLoadByDateRange
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@WorkLoadType Int
AS

DELETE FROM J_Workload
WHERE	J_Workload.WorkType = @WorkLoadType
AND		J_Workload.OUId	=	@OUId	
AND 	(J_Workload.EndTime >= CONVERT(DATETIME, @StartDate)
AND 	J_Workload.StartTime < CONVERT(DATETIME, @EndDate))

DELETE FROM M_AuxiliaryWork
WHERE 	M_AuxiliaryWork.OUId=@OUId
AND 	(M_AuxiliaryWork.EndDate >= CONVERT(DATETIME, @StartDate)
AND 	M_AuxiliaryWork.StartDate < CONVERT(DATETIME, @EndDate))

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_DeleteShiftSignOffStatusByStatusId')
	DROP PROC prM_DeleteShiftSignOffStatusByStatusId
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ShiftSignOffStatus
----------------------------------------------------------------------------
CREATE PROC prM_DeleteShiftSignOffStatusByStatusId
	@StatusId bigint
AS

DELETE	M_ShiftSignOffStatus
WHERE 	StatusId = @StatusId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_DeleteWorkLoadByOUIDDateRange')
	DROP PROCEDURE prM_DeleteWorkLoadByOUIDDateRange
GO

CREATE PROC prM_DeleteWorkLoadByOUIDDateRange
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
AS

DELETE FROM J_Workload
WHERE 	J_Workload.OUId = @OUId
AND		(J_Workload.EndTime >= CONVERT(DATETIME, @StartDate)
AND		J_Workload.StartTime < CONVERT(DATETIME, @EndDate))

DELETE FROM J_ActivityAttributes
WHERE J_ActivityAttributes.ActivityId IN (SELECT ActivityId 
									      FROM	J_Activity 
										  WHERE J_Activity.OUId = @OUId 
										  AND J_Activity.EndTime >= CONVERT(DATETIME, @StartDate)
										  AND J_Activity.StartTime < CONVERT(DATETIME, @EndDate))

DELETE FROM J_Activity
WHERE	J_Activity.OUId = @OUId
AND		(J_Activity.EndTime >= CONVERT(DATETIME, @StartDate)
AND		J_Activity.StartTime < CONVERT(DATETIME, @EndDate))

SELECT 1
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EqipmentScheduleByDateRangeByIdForOverlap_EndTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EqipmentScheduleByDateRangeByIdForOverlap_EndTime]
GO
 
create PROC [dbo].[prM_EqipmentScheduleByDateRangeByIdForOverlap_EndTime]
	@OUId bigint,
	@EndTime DateTime,
	@EquipmentId Bigint
AS


SELECT	*
FROM	M_EquipmentSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND EquipmentId = @EquipmentId
AND
(EndDate >= CONVERT(DATETIME, @EndTime)
AND StartDate < CONVERT(DATETIME, @EndTime))

go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentMaintenanceDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentMaintenanceDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentMaintenanceDel]    
(	
	@MaintenanceId	           BigInt 
)
AS
BEGIN
	 
	 DELETE FROM M_EquipmentMaintenance WHERE MaintenanceId=@MaintenanceId
	 
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentMaintenanceIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentMaintenanceIns]
GO
Create PROCEDURE [dbo].[prM_EquipmentMaintenanceIns]    
(		
	@EquipmentId		BIGINT,
	@StartDate			DATETIME,	 	 
	@EndDate			DATETIME,
	@Reason			    NVARCHAR(MAX),
	@Notes				NVARCHAR(MAX),	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentMaintenance WITH (NOLOCK)
	where EquipmentId=@EquipmentId
--	WHERE	LTrim(RTrim(Upper(EquipmentType))) = LTrim(RTrim(Upper(@EquipmentType)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentMaintenance
		(EquipmentId,StartDate, EndDate,Reason,Notes,CreatedBy, CreatedDate)
		VALUES(@EquipmentId, @StartDate,@EndDate,@Reason,@Notes,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentMaintenanceSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentMaintenanceSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentMaintenanceSel]    
(
	@MaintenanceId		bigint 
)
AS
BEGIN
	SELECT	M_EquipmentMaintenance.MaintenanceId,
			M_EquipmentMaintenance.EquipmentId,
			M_EquipmentMaintenance.StartDate, 
			M_EquipmentMaintenance.EndDate,
			M_EquipmentMaintenance.Reason ,	
			M_EquipmentMaintenance.Notes ,		 
			M_EquipmentMaintenance.CreatedBy, 
			M_EquipmentMaintenance.CreatedDate,
			M_EquipmentMaintenance.UpdatedBy,
			M_EquipmentMaintenance.UpdatedDate,
			M_Equipments.EquipmentName 
	FROM	M_EquipmentMaintenance	  WITH (NOLOCK) 
	INNER JOIN M_Equipments WITH (NOLOCK) ON M_Equipments.EquipmentId =M_EquipmentMaintenance.EquipmentId 			 
	WHERE	(M_EquipmentMaintenance.MaintenanceId = @MaintenanceId OR @MaintenanceId = 0)
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentMaintenanceUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentMaintenanceUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentMaintenanceUpd]    
(
	@MaintenanceId		BigInt,
	@EquipmentId		BIGINT,
	@StartDate			DATETIME,	 	 
	@EndDate			DATETIME,
	@Reason			    NVARCHAR(MAX),
	@Notes				NVARCHAR(MAX),
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentMaintenance WITH (NOLOCK)
	WHERE	 MaintenanceId	!=	@MaintenanceId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_EquipmentMaintenance
		SET		EquipmentId			=	@EquipmentId, 
				StartDate			=	@StartDate, 				 
				EndDate				=	@EndDate, 
				Reason				=	@Reason,  
				Notes				=	@Notes,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	MaintenanceId		=	@MaintenanceId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap]
GO
 
 
create PROC [dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@EquipmentId bigint
AS

SELECT	*
FROM	M_EquipmentSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND EquipmentId = @EquipmentId
AND
(EndDate <= CONVERT(DATETIME, @EndDate)
AND StartDate >= CONVERT(DATETIME, @StartDate))

go

 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap_StartTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap_StartTime]
GO
 
Create PROC [dbo].[prM_EquipmentScheduleByDateRangeByIdForOverlap_StartTime]
	@OUId bigint,
	@StartDate DateTime,
	@EquipmentId bigint
AS

SELECT	*
FROM	M_EquipmentSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND EquipmentId = @EquipmentId
AND
(EndDate > CONVERT(DATETIME, @StartDate)
AND StartDate <= CONVERT(DATETIME, @StartDate))


go

-- Select * from M_EquipmentSchedule
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentScheduleDel')
	DROP PROC prM_EquipmentScheduleDel
GO

----------------------------------------------------------------------------
-- Delete a single record from prM_EquipmentScheduleDel
----------------------------------------------------------------------------
CREATE PROC prM_EquipmentScheduleDel
	@EquipmentScheduleId bigint
AS

DELETE	M_EquipmentSchedule
WHERE 	EquipmentScheduleId = @EquipmentScheduleId

SELECT 1

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentsIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentsIns]    
(		
	@OUId					Bigint, 
	@EquipmentName			nVarchar(100),
	@EquipmentDesc			nVarchar(1000),
	@EquipmentTypeId		BIGINT,
	@LocationId				BIGINT,
	@ActiveStatus			INT,	 
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Equipments WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EquipmentName))) = LTrim(RTrim(Upper(@EquipmentName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_Equipments
		(EquipmentName,EquipmentDesc,EquipmentTypeId,LocationId, OUId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@EquipmentName, @EquipmentDesc,@EquipmentTypeId,@LocationId,@OUId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentsSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentsSel]    
(
	@EquipmentId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Equipments.EquipmentId,
			M_Equipments.EquipmentTypeId,
			M_Equipments.EquipmentName,
			M_Equipments.EquipmentDesc,
			M_Equipments.LocationId,
			M_Equipments.ActiveStatus,
			M_Equipments.OUId ,			 
			M_Equipments.CreatedBy, 
			M_Equipments.CreatedDate,
			M_Equipments.UpdatedBy,
			M_Equipments.UpdatedDate,
			M_EquipmentType.EquipmentType,
			M_Locations.LocationName 
	FROM	M_Equipments	  WITH (NOLOCK) 
			inner join M_EquipmentType WITH (NOLOCK)  on M_EquipmentType.EquipmentTypeId =M_Equipments.EquipmentTypeId
			inner join M_Locations WITH (NOLOCK)  on M_Locations.LocationId =M_Equipments.LocationId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Equipments.OUId = C_OrganizationNode.OUId
	WHERE	(M_Equipments.EquipmentId = @EquipmentId OR @EquipmentId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentsUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentsUpd]    
(
	@EquipmentId		BigInt,
	@EquipmentName		nVarchar(100),
	@EquipmentDesc		nVarchar(1000),
	@EquipmentTypeId	BIGINT,
	@LocationId			BIGINT,
	@ActiveStatus		INT,
	@OUId			    Bigint,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Equipments WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EquipmentName))) = LTrim(RTrim(Upper(@EquipmentName)))
	AND		EquipmentId	!=	@EquipmentId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_Equipments
		SET		EquipmentName			=	@EquipmentName, 
				EquipmentDesc			=	@EquipmentDesc, 
				EquipmentTypeId			=	@EquipmentTypeId,
				LocationId				=	@LocationId,
				ActiveStatus			=	@ActiveStatus, 
				OUId					=	@OUId,  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	EquipmentId				=	@EquipmentId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentTypeDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentTypeDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prM_EquipmentTypeDel]    
(	
	@EquipmentTypeId	           BigInt 
)
AS
BEGIN
	 

	Update M_EquipmentType  set ActiveStatus =0 where EquipmentTypeId =@EquipmentTypeId 
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentTypeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentTypeIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentTypeIns]    
(		
	@OUId					Bigint, 
	@EquipmentType		nVarchar(100),
	@EqipmentTypeDesc		nVarchar(1000),	 	 
	@ActiveStatus		INT,	 
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentType WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EquipmentType))) = LTrim(RTrim(Upper(@EquipmentType)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentType
		(EquipmentType,EqipmentTypeDesc, OUId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@EquipmentType, @EqipmentTypeDesc,@OUId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentTypeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentTypeSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentTypeSel]    
(
	@EquipmentTypeId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_EquipmentType.EquipmentTypeId,
			M_EquipmentType.EquipmentType,
			M_EquipmentType.EqipmentTypeDesc, 
			M_EquipmentType.ActiveStatus,
			M_EquipmentType.OUId ,			 
			M_EquipmentType.CreatedBy, 
			M_EquipmentType.CreatedDate,
			M_EquipmentType.UpdatedBy,
			M_EquipmentType.UpdatedDate
	FROM	M_EquipmentType	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_EquipmentType.OUId = C_OrganizationNode.OUId
	WHERE	(M_EquipmentType.EquipmentTypeId = @EquipmentTypeId OR @EquipmentTypeId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentTypeUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentTypeUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentTypeUpd]    
(
	@EquipmentTypeId		BigInt,
	@EquipmentType		nVarchar(100),
	@EqipmentTypeDesc		nVarchar(1000),	 	 
	@ActiveStatus		INT,
	@OUId			    Bigint,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentType WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(EquipmentType))) = LTrim(RTrim(Upper(@EquipmentType)))
	AND		EquipmentTypeId	!=	@EquipmentTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_EquipmentType
		SET		EquipmentType			=	@EquipmentType, 
				EqipmentTypeDesc		=	@EqipmentTypeDesc, 				 
				ActiveStatus			=	@ActiveStatus, 
				OUId					=	@OUId,  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	EquipmentTypeId			=	@EquipmentTypeId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentType_RequirementDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentType_RequirementDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentType_RequirementDel]
(
	@EquipmentTypeReqId		BigInt 
)
AS
BEGIN
	DELETE FROM 	M_EquipmentType_Requirement 
	WHERE	EquipmentTypeReqId	=	@EquipmentTypeReqId

	SELECT 1
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentType_RequirementIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentType_RequirementIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prM_EquipmentType_RequirementIns]    
(		
	@EquipmentTypeId					Bigint, 
	@SkillId		bigint,	 	 
	@Requirement		INT,	 
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentType_Requirement WITH (NOLOCK)
	WHERE	EquipmentTypeId = @EquipmentTypeId and SkillId=@SkillId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentType_Requirement
		(EquipmentTypeId,SkillId,Requirement,CreatedBy, CreatedDate)
		VALUES(@EquipmentTypeId, @SkillId,@Requirement,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentType_RequirementSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentType_RequirementSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prM_EquipmentType_RequirementSel]   
(
	@EquipmentTypeReqId		bigint 
)
AS
BEGIN
	SELECT	M_EquipmentType_Requirement.EquipmentTypeReqId,
			M_EquipmentType_Requirement.EquipmentTypeId,
			M_EquipmentType_Requirement.SkillId, 
			M_EquipmentType_Requirement.Requirement ,
			M_EquipmentType_Requirement.CreatedBy, 
			M_EquipmentType_Requirement.CreatedDate,
			M_EquipmentType_Requirement.UpdatedBy,
			M_EquipmentType_Requirement.UpdatedDate,
			D_Skill.Skill as SkillName
	FROM	M_EquipmentType_Requirement	  WITH (NOLOCK)
	left outer join D_Skill on D_Skill.SkillId= M_EquipmentType_Requirement.SkillId 			 
	WHERE	(M_EquipmentType_Requirement.EquipmentTypeId = @EquipmentTypeReqId OR @EquipmentTypeReqId = 0)
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentType_RequirementUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentType_RequirementUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_EquipmentType_RequirementUpd]    
(
	@EquipmentTypeReqId		BigInt,
	@EquipmentTypeId					Bigint, 
	@SkillId		bigint,	 	 
	@Requirement		INT,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentType_Requirement WITH (NOLOCK)
	WHERE	EquipmentTypeId = @EquipmentTypeId and SkillId=@SkillId
	AND		EquipmentTypeReqId	!=	@EquipmentTypeReqId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_EquipmentType_Requirement
		SET		EquipmentTypeId			=	@EquipmentTypeId, 
				SkillId		=	@SkillId, 				 
				Requirement			=	@Requirement, 				  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	EquipmentTypeReqId			=	@EquipmentTypeReqId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GerAuxiliaryWorkByDateRange')
	DROP PROC prM_GerAuxiliaryWorkByDateRange
GO

----------------------------------------------------------------------------
-- Select a single record from M_AuxiliaryWork
----------------------------------------------------------------------------
CREATE PROC prM_GerAuxiliaryWorkByDateRange
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
AS

SELECT	ScheduleId,
		OUId,
		ShiftBandId,
		M_AuxiliaryWork.SkillId,
		D_Skill.Skill SkillCode,
		D_Skill.SkillDesc SkillDescription,
		StartDate,
		EndDate,
		WorkloadGenereated,Requirement,
		SignOffStatus,
		M_AuxiliaryWork.CreatedDate,
		M_AuxiliaryWork.CreatedBy,
		M_AuxiliaryWork.UpdatedBy,
		M_AuxiliaryWork.UpdatedDate
FROM	M_AuxiliaryWork WITH (NOLOCK) 
		INNER JOIN D_Skill WITH (NOLOCK) ON M_AuxiliaryWork.SkillId = D_Skill.SkillId
WHERE 	M_AuxiliaryWork.OUId=@OUId
AND 	(EndDate >= CONVERT(DATETIME, @StartDate)
AND 	StartDate < CONVERT(DATETIME, @EndDate))

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GerAuxiliaryWorkByScheduleId')
	DROP PROC prM_GerAuxiliaryWorkByScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from M_AuxiliaryWork
----------------------------------------------------------------------------
CREATE PROC prM_GerAuxiliaryWorkByScheduleId
	@ScheduleId bigint
AS

SELECT	ScheduleId,
	OUId,
	ShiftBandId,
	SkillId,
	StartDate,
	EndDate,
	Requirement,
	WorkloadGenereated,
	SignOffStatus,
	CreatedDate,
	CreatedBy,
	UpdatedBy,
	UpdatedDate
FROM	M_AuxiliaryWork WITH (NOLOCK)
WHERE 	ScheduleId = @ScheduleId

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetAvailableCranesByDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetAvailableCranesByDuration]
GO
 
 
Create PROC [dbo].[prM_GetAvailableCranesByDuration]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
	
AS

SELECT	M_cranes.CraneId,M_cranes.CraneNumber 
FROM	M_cranes WITH (NOLOCK) 
where	M_cranes.ActiveStatus=1 
AND		OUId	= @OUId 
AND		M_cranes.craneid  NOT IN (SELECT EquipmentId from M_EquipmentMaintenance WITH (NOLOCK)
								  WHERE @StartDate BETWEEN StartDate AND EndDate
								  OR @EndDate  BETWEEN StartDate AND EndDate
								  OR StartDate BETWEEN @StartDate AND @EndDate)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetAvailableEquipmentsByDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetAvailableEquipmentsByDuration]
GO
 
 
 
create PROC [dbo].[prM_GetAvailableEquipmentsByDuration]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime	
AS

SELECT	M_Equipments.EquipmentId, M_Equipments.EquipmentTypeId, 
		M_Equipments.EquipmentName from M_Equipments WITH (NOLOCK)
WHERE	M_Equipments.ActiveStatus=1 
AND		OUId=@OUId 
AND		M_Equipments.EquipmentId  NOT IN (	SELECT	EquipmentId  FROM	M_EquipmentMaintenance WITH (NOLOCK)
											WHERE	@StartDate BETWEEN StartDate and EndDate
											OR		@EndDate  BETWEEN StartDate and EndDate
											OR		StartDate BETWEEN @StartDate and @EndDate
										 )
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetAvailableResourceByDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetAvailableResourceByDuration]
GO
 
 
Create PROC [dbo].[prM_GetAvailableResourceByDuration]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
	
AS

SELECT	S_Shifts.ShiftId, D_Roles.RoleId PrimaryRoleId, D_Roles.PrimarySkillId, S_Shifts.EmployeeId
FROM	S_Shifts WITH (NOLOCK)
		INNER JOIN D_Roles WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId 
		INNER JOIN D_Skill WITH (NOLOCK) ON D_Roles.PrimarySkillId = D_Skill.SkillId
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId 
				   AND C_EmployeeRoles.IsPrimaryRole = 1 AND C_EmployeeRoles.EmployeeId = S_SHIFTS.EmployeeId
				   AND (S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId IS NULL)
WHERE	(ActualEndTime > CONVERT(DATETIME, @StartDate)
AND		ActualStartTime < CONVERT(DATETIME, @EndDate))
AND		S_Shifts.OUId = @OUId

go



IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetCraneScheduleByCraneScheduleId')
	DROP PROCEDURE prM_GetCraneScheduleByCraneScheduleId
GO

CREATE PROC prM_GetCraneScheduleByCraneScheduleId
	@CraneScheduleId bigint
AS

SELECT	CraneScheduleId,
		craneSchd.OUId,
		craneSchd.CraneId,
		M_Cranes.CraneNumber,
		M_Cranes.CraneDesc CraneDescription,
		craneSchd.VesselScheduleId,
		vesselSchd.VesselName,
		vesselSchd.VisitId VesselVisitId,
		M_Berth.BerthId,
		M_Berth.Berth BerthName,
		craneSchd.LocationId,
		M_Locations.LocationName,
		craneSchd.StartDate,
		craneSchd.EndDate,
		Imported,
		WorkloadGenerated,
		SignOffStatus,
		craneSchd.CreatedDate,
		craneSchd.CreatedBy,
		craneSchd.UpdatedBy,
		craneSchd.UpdatedDate
FROM	M_CraneSchedule craneSchd WITH (NOLOCK)
		INNER JOIN M_VesselSchedule vesselSchd WITH (NOLOCK) ON craneSchd.VesselScheduleId = vesselSchd.VesselScheduleId
		INNER JOIN M_Locations WITH (NOLOCK) ON craneSchd.LocationId = M_Locations.LocationId
		INNER JOIN M_Cranes WITH (NOLOCK) ON craneSchd.CraneId = M_Cranes.CraneId
		INNER JOIN M_Berth WITH (NOLOCK) ON vesselSchd.BerthId = M_Berth.BerthId
WHERE 	CraneScheduleId = @CraneScheduleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetCraneScheduleByOUIDDateRange')
	DROP PROCEDURE prM_GetCraneScheduleByOUIDDateRange
GO

CREATE PROC prM_GetCraneScheduleByOUIDDateRange
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
AS

SELECT	CraneScheduleId,
		M_CraneSchedule.OUId,
		M_CraneSchedule.CraneId,
		M_Cranes.CraneNumber,
		M_CraneSchedule.VesselScheduleId,
		M_CraneSchedule.LocationId,
		M_Locations.LocationName,
		M_CraneSchedule.StartDate,
		M_CraneSchedule.EndDate,
		M_VesselSchedule.BerthId,
		M_Berth.Berth BerthName,
		Imported,
		WorkloadGenerated,
		SignOffStatus,
		M_CraneSchedule.CreatedDate,
		M_CraneSchedule.CreatedBy,
		M_CraneSchedule.UpdatedBy,
		M_CraneSchedule.UpdatedDate,
		M_VesselSchedule.VesselName,
		M_VesselSchedule.VisitId VesselVisitId
FROM	M_CraneSchedule WITH (NOLOCK)	
		INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
		INNER JOIN M_Locations WITH (NOLOCK) ON M_CraneSchedule.LocationId = M_Locations.LocationId
		INNER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
		INNER JOIN M_Berth WITH (NOLOCK) ON M_VesselSchedule.BerthId = M_Berth.BerthId
WHERE 	M_CraneSchedule.OUId = @OUId
AND		(M_CraneSchedule.EndDate > CONVERT(DATETIME, @StartDate)
AND		M_CraneSchedule.StartDate < CONVERT(DATETIME, @EndDate))


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetCraneScheduleByVesselScheduleId')
	DROP PROCEDURE prM_GetCraneScheduleByVesselScheduleId
GO

CREATE PROC prM_GetCraneScheduleByVesselScheduleId
	@VesselScheduleId bigint
AS

SELECT	CraneScheduleId,
		M_CraneSchedule.OUId,
		M_CraneSchedule.CraneId,	
		M_Cranes.CraneNumber,
		VesselScheduleId,
		M_CraneSchedule.LocationId,
		M_Locations.LocationName,
		M_CraneSchedule.StartDate,
		EndDate,
		Imported,
		WorkloadGenerated,
		SignOffStatus,
		M_CraneSchedule.CreatedDate,
		M_CraneSchedule.CreatedBy,
		M_CraneSchedule.UpdatedBy,
		M_CraneSchedule.UpdatedDate
FROM	M_CraneSchedule WITH (NOLOCK)	
		INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
		INNER JOIN M_Locations WITH (NOLOCK) ON M_CraneSchedule.LocationId = M_Locations.LocationId
WHERE 	VesselScheduleId = @VesselScheduleId

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetCranesForScheduleByVesselDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetCranesForScheduleByVesselDuration]
GO
 
 
Create PROC [dbo].[prM_GetCranesForScheduleByVesselDuration]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@BerthId bigint
	
AS

select M_cranes.CraneId,M_cranes.CraneNumber, M_Cranes.LocationId, M_Locations.LocationName from M_cranes WITH (NOLOCK)
inner join M_BerthCranes WITH (NOLOCK) on M_BerthCranes.CraneId = M_cranes.CraneId
INNER JOIN M_Locations WITH (NOLOCK) ON M_Locations.LocationId = M_Cranes.LocationId
where M_BerthCranes.BerthId=@BerthId and M_cranes.ActiveStatus=1 and M_Cranes.OUId=@OUId and  M_cranes.craneid 
not in (select craneid from M_craneschedule WITH (NOLOCK)
where  @StartDate >= StartDate and @StartDate < EndDate
	or @EndDate  > StartDate and @EndDate < EndDate
	or StartDate >= @StartDate and StartDate < @EndDate
	union  
	select equipmentid from M_EquipmentMaintenance WITH (NOLOCK)
	where @StartDate >= StartDate and @StartDate < EndDate
	or @EndDate  >= StartDate and @EndDate   <= EndDate
	or StartDate >= @StartDate and StartDate <= @EndDate)
--where  @StartDate between StartDate and EndDate
--	or @EndDate  between StartDate and EndDate
--	or StartDate between @StartDate and @EndDate
--	union  
--	select equipmentid from M_EquipmentMaintenance WITH (NOLOCK)
--	where @StartDate between StartDate and EndDate
--	or @EndDate  between StartDate and EndDate
--	or StartDate between @StartDate and @EndDate)

--select * from M_craneschedule 
-- select * from M_EquipmentMaintenance
-- select * from M_BerthCranes
-- select * from M_cranes

go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEquipmentScheduleByDateRange')
	DROP PROC prM_GetEquipmentScheduleByDateRange
GO

----------------------------------------------------------------------------
-- Select a single record from M_EquipmentSchedule
----------------------------------------------------------------------------
CREATE PROC prM_GetEquipmentScheduleByDateRange
	@OUId			bigint,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@EquipmentTypes	nVarchar(max),
	@Equipments		nVarchar(max)
AS
DECLARE @__EquipmentTypesId BIGINT = 0, @__EquipmentsId BIGINT = 0
BEGIN
	
	SELECT TOP 1 @__EquipmentTypesId = sID FROM fnStringToTable(@EquipmentTypes)

	SELECT TOP 1 @__EquipmentsId = sID FROM fnStringToTable(@Equipments)

	SELECT	EquipmentScheduleId,
			M_EquipmentSchedule.OUId,
			M_EquipmentSchedule.EquipmentTypeId,
			M_EquipmentType.EquipmentType EquipmentTypeName,
			M_EquipmentSchedule.EquipmentId,
			M_Equipments.LocationId,
			M_Locations.LocationName,
			M_Locations.LocationDesc LocationName,
			M_EQUIPMENTS.EquipmentName,
			M_Equipments.EquipmentDesc EquipmentDescription,
			M_EquipmentSchedule.StartDate,
			M_EquipmentSchedule.EndDate,
			M_EquipmentSchedule.CraneScheduleId,
			WorkloadGenereated,
			M_VesselSchedule.BerthId,
			M_Berth.Berth BerthName,
			M_EquipmentSchedule.SignOffStatus,
			M_EquipmentSchedule.CreatedDate,
			M_EquipmentSchedule.CreatedBy,
			M_EquipmentSchedule.UpdatedBy,
			M_EquipmentSchedule.UpdatedDate,
			M_VesselSchedule.VesselName,
			M_VesselSchedule.VisitId VesselVisitId,
			M_Cranes.CraneNumber
	FROM	M_EquipmentSchedule WITH (NOLOCK) 
			INNER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_EQUIPMENTS.EquipmentId
				AND (M_EquipmentSchedule.EquipmentId IN (SELECT * FROM fnStringToTable(@Equipments)) OR @__EquipmentsId = 0) -- Equipment Filter
			INNER JOIN M_EquipmentType WITH (NOLOCK) ON M_Equipments.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
				AND (M_EquipmentSchedule.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes)) OR @__EquipmentTypesId = 0) -- Equipment Type Filter
			INNER JOIN M_Locations WITH (NOLOCK) ON M_Equipments.LocationId = M_Locations.LocationId
			LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = M_EquipmentSchedule.CraneScheduleId
			LEFT OUTER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneSchedule.CraneId
			LEFT OUTER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
			LEFT OUTER JOIN M_Berth WITH (NOLOCK) ON M_VesselSchedule.BerthId = M_Berth.BerthId
	WHERE 	M_EquipmentSchedule.OUId=@OUId
	AND 	(M_EquipmentSchedule.EndDate > CONVERT(DATETIME, @StartDate)
	AND 	M_EquipmentSchedule.StartDate < CONVERT(DATETIME, @EndDate))
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEquipmentScheduleByDateRangeAndCraneScheduleId')
	DROP PROC prM_GetEquipmentScheduleByDateRangeAndCraneScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from M_EquipmentSchedule
----------------------------------------------------------------------------
CREATE PROC prM_GetEquipmentScheduleByDateRangeAndCraneScheduleId
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@CraneScheduleId bigint
AS

SELECT	EquipmentScheduleId,
		M_EquipmentSchedule.OUId,
		M_Equipments.LocationId,
		M_Locations.LocationName,
		M_EquipmentSchedule.EquipmentTypeId,
		M_EquipmentSchedule.EquipmentId,
		M_Equipments.EquipmentName,
		StartDate,
		EndDate,
		CraneScheduleId,
		WorkloadGenereated,
		SignOffStatus,
		M_EquipmentSchedule.CreatedDate,
		M_EquipmentSchedule.CreatedBy,
		M_EquipmentSchedule.UpdatedBy,	
		M_EquipmentSchedule.UpdatedDate
FROM	M_EquipmentSchedule WITH (NOLOCK) 
		INNER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
		INNER JOIN M_Locations WITH (NOLOCK) ON M_Equipments.LocationId = M_Locations.LocationId
WHERE 	M_EquipmentSchedule.OUId=@OUId
AND 	(EndDate >= CONVERT(DATETIME, @StartDate)
AND 	StartDate < CONVERT(DATETIME, @EndDate))
and CraneScheduleId=@CraneScheduleId

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEquipmentScheduleByEquipmentScheduleId')
	DROP PROC prM_GetEquipmentScheduleByEquipmentScheduleId
GO

----------------------------------------------------------------------------
-- Select a single record from M_EquipmentSchedule
----------------------------------------------------------------------------
CREATE PROC prM_GetEquipmentScheduleByEquipmentScheduleId
	@EquipmentScheduleId bigint
AS

SELECT	EquipmentScheduleId,
		M_EquipmentSchedule.OUId,
		M_EquipmentSchedule.EquipmentTypeId,
		M_EquipmentSchedule.EquipmentId,
		M_EquipmentSchedule.StartDate,
		M_EquipmentSchedule.EndDate,
		M_EquipmentSchedule.CraneScheduleId,
		M_EquipmentSchedule.WorkloadGenereated,
		M_EquipmentSchedule.SignOffStatus,
		M_EquipmentSchedule.CreatedDate,
		M_EquipmentSchedule.CreatedBy,
		M_EquipmentSchedule.UpdatedBy,
		M_EquipmentSchedule.UpdatedDate,
		M_CraneSchedule.CraneId,
		M_Cranes.CraneNumber,
		M_Equipments.EquipmentName,
		M_equipments.EquipmentDesc
FROM	M_EquipmentSchedule WITH (NOLOCK) 
		INNER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
		LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON M_EquipmentSchedule.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		LEFT OUTER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
WHERE 	EquipmentScheduleId = @EquipmentScheduleId

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetEquipmentsForScheduleByCraneScheuleDuration]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetEquipmentsForScheduleByCraneScheuleDuration]
GO
 
 
 
create PROC [dbo].[prM_GetEquipmentsForScheduleByCraneScheuleDuration]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@EquipmentTypeId bigint
	
AS

--SELECT	M_Equipments.EquipmentId,M_Equipments.EquipmentName, M_Equipments.LocationId, M_Locations.LocationName, M_Equipments.EquipmentTypeId
--FROM	M_Equipments WITH (NOLOCK) INNER JOIN M_Locations WITH (NOLOCK) ON M_Equipments.LocationId = M_Locations.LocationId
--WHERE	(M_Equipments.EquipmentTypeId= @EquipmentTypeId or @EquipmentTypeId = 0) and M_Equipments.ActiveStatus=1 and M_Equipments.OUId = @OUId 
--AND		M_Equipments.EquipmentId  not in (select EquipmentId from M_EquipmentSchedule WITH (NOLOCK)
--where  @StartDate between StartDate and EndDate
--	or @EndDate  between StartDate and EndDate
--	or StartDate between @StartDate and @EndDate
--	union  
--	select equipmentid from M_EquipmentMaintenance WITH (NOLOCK)
--	where @StartDate between StartDate and EndDate
--	or @EndDate  between StartDate and EndDate
--	or StartDate between @StartDate and @EndDate)


SELECT	M_Equipments.EquipmentId,
		M_Equipments.EquipmentName, 
		M_Equipments.LocationId, 
		M_Locations.LocationName, 
		M_Equipments.EquipmentTypeId,
		M_EquipmentType.EquipmentType EquipmentTypeName
FROM	M_Equipments WITH (NOLOCK) 
		INNER JOIN M_Locations WITH (NOLOCK) ON M_Equipments.LocationId = M_Locations.LocationId
		INNER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_Equipments.EquipmentTypeId
WHERE	(M_Equipments.EquipmentTypeId= @EquipmentTypeId or @EquipmentTypeId = 0) and M_Equipments.ActiveStatus=1 and M_Equipments.OUId = @OUId 
AND		M_Equipments.EquipmentId  not in (select EquipmentId from M_EquipmentSchedule WITH (NOLOCK)
where  @StartDate >= StartDate and @StartDate < EndDate
	or @EndDate  > StartDate and @EndDate <= EndDate
	or StartDate >= @StartDate and StartDate < @EndDate
	union  
	select equipmentid from M_EquipmentMaintenance WITH (NOLOCK)
	where @StartDate >= StartDate and @StartDate < EndDate
	or @EndDate  > StartDate and @EndDate   <= EndDate
	or StartDate >= @StartDate and StartDate < @EndDate)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetLastSignedOffShift')
	DROP PROC prM_GetLastSignedOffShift
GO

----------------------------------------------------------------------------
-- Retrieve Last Signed Off Shift Before current selected Date And OU
----------------------------------------------------------------------------
CREATE PROC prM_GetLastSignedOffShift
	@SelectedDate	DateTime,
	@OUId			BigInt
AS
	SELECT	TOP 1 
			StatusId,
			M_ShiftSignOffStatus.OUId,
			C_OrganizationNode.OUName,
			ShiftDate,
			M_ShiftSignOffStatus.ShiftBandId,
			D_ShiftBand.ShiftBandName,
			M_ShiftSignOffStatus.StartTime,
			M_ShiftSignOffStatus.EndTime,
			Status,
			SignedOffBy,
			SignedOffDate,
			DeployedDate,
			DeployedBy,
			DeploymentPublishedDate,
			DeploymentPublishedBy
	FROM	M_ShiftSignOffStatus WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON M_ShiftSignOffStatus.OUId = C_OrganizationNode.OUId 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON M_ShiftSignOffStatus.ShiftBandId = D_ShiftBand.ShiftBandId
	--WHERE	Convert(Date,M_ShiftSignOffStatus.ShiftDate) <= Convert(Date,@SelectedDate)
	WHERE	M_ShiftSignOffStatus.OUId = @OUId
	ORDER BY M_ShiftSignOffStatus.EndTime DESC
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetShiftSignOffStatusByDate')
	DROP PROC prM_GetShiftSignOffStatusByDate
GO

----------------------------------------------------------------------------
-- Retrieve Shift Sign Off Status By Selected Date, OU And Shift Band
----------------------------------------------------------------------------
CREATE PROC prM_GetShiftSignOffStatusByDate
	@OUId bigint = NULL,
	@ShiftDate date = NULL,
	@ShiftBandId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL
AS
	SELECT	StatusId,
			M_ShiftSignOffStatus.OUId,
			C_OrganizationNode.OUName,
			ShiftDate,
			M_ShiftSignOffStatus.ShiftBandId,
			D_ShiftBand.ShiftBandName,
			M_ShiftSignOffStatus.StartTime,
			M_ShiftSignOffStatus.EndTime,
			Status,
			SignedOffBy,
			SignedOffDate,
			DeployedDate,
			DeployedBy,
			DeploymentPublishedDate,
			DeploymentPublishedBy
	FROM	M_ShiftSignOffStatus WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON M_ShiftSignOffStatus.OUId = C_OrganizationNode.OUId 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON M_ShiftSignOffStatus.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	M_ShiftSignOffStatus.ShiftBandId	=	@ShiftBandId
	AND		M_ShiftSignOffStatus.OUId			=	@OUId	
	AND		M_ShiftSignOffStatus.ShiftDate		=	@ShiftDate
	AND		M_ShiftSignOffStatus.StartTime		=	@StartTime
	AND		M_ShiftSignOffStatus.EndTime		=	@EndTime
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetShiftSignOffStatusByDateTime')
	DROP PROC prM_GetShiftSignOffStatusByDateTime
GO

----------------------------------------------------------------------------
-- Retrieve Shift Sign Off Status By Selected Date And Time
----------------------------------------------------------------------------
CREATE PROC prM_GetShiftSignOffStatusByDateTime
	@DateTimeToValidate DateTime,
	@OUId				BigInt
AS
	SELECT	StatusId,
			M_ShiftSignOffStatus.OUId,
			C_OrganizationNode.OUName,
			ShiftDate,
			M_ShiftSignOffStatus.ShiftBandId,
			D_ShiftBand.ShiftBandName,
			M_ShiftSignOffStatus.StartTime,
			M_ShiftSignOffStatus.EndTime,
			Status,
			SignedOffBy,
			SignedOffDate,
			DeployedDate,
			DeployedBy,
			DeploymentPublishedDate,
			DeploymentPublishedBy
	FROM	M_ShiftSignOffStatus WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON M_ShiftSignOffStatus.OUId = C_OrganizationNode.OUId 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON M_ShiftSignOffStatus.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	Convert(DateTime,M_ShiftSignOffStatus.EndTime,120) >= Convert(DateTime,@DateTimeToValidate,120)
	AND		Convert(DateTime,M_ShiftSignOffStatus.StartTime,120) < Convert(DateTime,@DateTimeToValidate,120)
	ORDER BY M_ShiftSignOffStatus.StartTime DESC
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetSkillBySkillMatrixTemplateId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetSkillBySkillMatrixTemplateId]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prM_GetSkillBySkillMatrixTemplateId]    
(
	@MatrixSkillId	BigInt
)
AS
BEGIN
	SELECT	M_Skill_Matrix_Det.SkillId,
			D_Skill.Skill SkillCode
	FROM	M_Skill_Matrix_Det WITH (NOLOCK)
			INNER JOIN M_Skill_Matrix_Template WITH (NOLOCK) ON M_Skill_Matrix_Det.MatrixSkillId = M_Skill_Matrix_Template.MatrixSkillId
			INNER JOIN D_SKILL WITH (NOLOCK) ON D_SKILL.SkillId = M_Skill_Matrix_Det.SkillId
	WHERE	M_Skill_Matrix_Template.MatrixSkillId = @MatrixSkillId

END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetSkillMatrixScheduleBySkillMatrixId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetSkillMatrixScheduleBySkillMatrixId]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prM_GetSkillMatrixScheduleBySkillMatrixId]    
(
	@SkillMatrixId		BigInt
)
AS
BEGIN
	SELECT	SkillMatrixScheduleId,
			SkillMatrixId,
			ScheduledValue,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	M_SkillMatrix_Schedule WITH (NOLOCK)
	WHERE	M_SkillMatrix_Schedule.SkillMatrixId = @SkillMatrixId

END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetSkillMatrixTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetSkillMatrixTemplate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prM_GetSkillMatrixTemplate]    
(
	@MatrixSkillId		BigInt,
	@OuId				BigInt

)
AS
BEGIN
	SELECT	M_Skill_Matrix_Template.MatrixSkillId,
			M_Skill_Matrix_Template.OUId,
			M_Skill_Matrix_Template.SkillTemplateName,
			M_Skill_Matrix_Template.ActiveStatus,
			M_Skill_Matrix_Template.CreatedBy,
			M_Skill_Matrix_Template.CreatedDate,
			M_Skill_Matrix_Template.UpdatedBy,
			M_Skill_Matrix_Template.UpdatedDate
	FROM	M_Skill_Matrix_Template WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON M_Skill_Matrix_Template.OUId = C_OrganizationNode.OUId
	WHERE	(M_Skill_Matrix_Template.MatrixSkillId = @MatrixSkillId OR @MatrixSkillId = 0)
	AND		C_OrganizationNode.OUId = @OuId

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetVesselListByVesselName')
	DROP PROCEDURE prM_GetVesselListByVesselName
GO

CREATE PROC prM_GetVesselListByVesselName
	@VesselName nvarchar(500)
AS

SELECT	VesselId,
	VesselName,
	LastVisitStartDate,
	LastVisitEndDate,
	CraneReq,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_VesselList WITH (NOLOCK)
WHERE 	VesselName = @VesselName

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetWorkloadByDateRangeForActivity')
	DROP PROC prM_GetWorkloadByDateRangeForActivity
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE  PROC [dbo].[prM_GetWorkloadByDateRangeForActivity]
	@OUId bigint,
	@StartTime DateTime,
	@EndTime DateTime,
	@SkillId bigint,
	@WorkType int
AS
-- crane
if @WorkType = 1 
begin
	select WorkloadId,SkillId,StartTime,EndTime,M_CraneSchedule.CraneId 'EquipmentId', J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.CraneScheduleId 'ScheduleId',J_Workload.EquipmentScheduleId	
	from J_Workload WITH (NOLOCK)
	inner join M_CraneSchedule WITH (NOLOCK) on J_Workload.CraneScheduleId =M_CraneSchedule.CraneScheduleId
	where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType and
	 ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
	 order by StartTime

	 SELECT J_Activity.WorkloadId, Min(J_Activity.StartTime) ActivityStartTime, Max(J_Activity.EndTime) ActivityEndTime
	 FROM	J_Activity WITH (NOLOCK) INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
	 WHERE	J_Workload.OUId = @OUId and J_Workload.SkillId=@SkillId and J_Workload.WorkType=@WorkType and
	 ( J_Workload.StartTime <= @StartTime  and J_Workload.EndTime >= @EndTime
	 or J_Workload.StartTime <= @StartTime  and J_Workload.EndTime < @EndTime and J_Workload.EndTime > @StartTime
	 or J_Workload.StartTime > @StartTime  and J_Workload.EndTime <= @EndTime
	 or J_Workload.StartTime >= @StartTime and J_Workload.StartTime <@EndTime)
	 AND J_Activity.SkillId != 19
	 GROUP BY J_Activity.WorkloadId
end
else if @WorkType = 2
begin

	select WorkloadId, SkillId,StartTime,EndTime,M_EquipmentSchedule.EquipmentId 'EquipmentId' , J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.EquipmentScheduleId 'ScheduleId'	
	from J_Workload WITH (NOLOCK)
	inner join M_EquipmentSchedule WITH (NOLOCK) on J_Workload.EquipmentScheduleId =M_EquipmentSchedule.EquipmentScheduleId
	where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType and
	 ( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime) 
	 order by StartTime

	  SELECT J_Activity.WorkloadId, Min(J_Activity.StartTime) ActivityStartTime, Max(J_Activity.EndTime) ActivityEndTime
	 FROM	J_Activity WITH (NOLOCK) INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
	 WHERE	J_Workload.OUId = @OUId and J_Workload.SkillId=@SkillId and J_Workload.WorkType=@WorkType and
	 ( J_Workload.StartTime <= @StartTime  and J_Workload.EndTime >= @EndTime
	 or J_Workload.StartTime <= @StartTime  and J_Workload.EndTime < @EndTime and J_Workload.EndTime > @StartTime
	 or J_Workload.StartTime > @StartTime  and J_Workload.EndTime <= @EndTime
	 or J_Workload.StartTime >= @StartTime and J_Workload.StartTime <@EndTime)
	 AND J_Activity.SkillId != 19
	 GROUP BY J_Activity.WorkloadId
end
else if @WorkType = 3
begin
	select WorkloadId, SkillId,StartTime,EndTime,0 'EquipmentId' , J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.ScheduleId	
	from J_Workload WITH (NOLOCK)
		where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType and
	( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
	order by StartTime

	 SELECT J_Activity.WorkloadId, Min(J_Activity.StartTime) ActivityStartTime, Max(J_Activity.EndTime) ActivityEndTime
	 FROM	J_Activity WITH (NOLOCK) INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
	 WHERE	J_Workload.OUId = @OUId and J_Workload.SkillId=@SkillId and J_Workload.WorkType=@WorkType and
	 ( J_Workload.StartTime <= @StartTime  and J_Workload.EndTime >= @EndTime
	 or J_Workload.StartTime <= @StartTime  and J_Workload.EndTime < @EndTime and J_Workload.EndTime > @StartTime
	 or J_Workload.StartTime > @StartTime  and J_Workload.EndTime <= @EndTime
	 or J_Workload.StartTime >= @StartTime and J_Workload.StartTime <@EndTime)
	 AND J_Activity.SkillId != 19
	 GROUP BY J_Activity.WorkloadId
end
else if @WorkType = 4
begin
	select WorkloadId, SkillId,StartTime,EndTime,0 'EquipmentId' , J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',M_VesselSchedule.VesselScheduleId 'ScheduleId'	
	from J_Workload WITH (NOLOCK)
	inner join M_VesselSchedule WITH (NOLOCK) on J_Workload.ScheduleId =M_VesselSchedule.VesselScheduleId
	where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType and
	( StartTime <= @StartTime  and EndTime >= @EndTime
	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
	 or StartTime > @StartTime  and EndTime <= @EndTime
	 or StartTime >= @StartTime and StartTime <@EndTime)
	order by StartTime

	 SELECT J_Activity.WorkloadId, Min(J_Activity.StartTime) ActivityStartTime, Max(J_Activity.EndTime) ActivityEndTime
	 FROM	J_Activity WITH (NOLOCK) INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
	 WHERE	J_Workload.OUId = @OUId and J_Workload.SkillId=@SkillId and J_Workload.WorkType=@WorkType and
	 ( J_Workload.StartTime <= @StartTime  and J_Workload.EndTime >= @EndTime
	 or J_Workload.StartTime <= @StartTime  and J_Workload.EndTime < @EndTime and J_Workload.EndTime > @StartTime
	 or J_Workload.StartTime > @StartTime  and J_Workload.EndTime <= @EndTime
	 or J_Workload.StartTime >= @StartTime and J_Workload.StartTime <@EndTime)
	 AND J_Activity.SkillId != 19
	 GROUP BY J_Activity.WorkloadId
end



GO
	IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetWorkloadByScheduledList')
	DROP PROC prM_GetWorkloadByScheduledList
GO

----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE  PROC [dbo].[prM_GetWorkloadByScheduledList]
	@ScheduledIdList	nVarchar(max),
	@WorkType			int
AS
-- crane
if @WorkType = 1 
begin
	select WorkloadId,SkillId,StartTime,EndTime,M_CraneSchedule.CraneId 'EquipmentId', J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.CraneScheduleId 'ScheduleId',J_Workload.EquipmentScheduleId	
	from J_Workload WITH (NOLOCK)
	inner join M_CraneSchedule WITH (NOLOCK) on J_Workload.CraneScheduleId =M_CraneSchedule.CraneScheduleId
	where J_Workload.CraneScheduleId IN (SELECT * FROM fnStringToTable(@ScheduledIdList))
	order by StartTime
end
else if @WorkType = 2
begin

	select WorkloadId, SkillId,StartTime,EndTime,M_EquipmentSchedule.EquipmentId 'EquipmentId' , J_Workload.OUId
	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.EquipmentScheduleId 'ScheduleId'	
	from J_Workload WITH (NOLOCK)
	inner join M_EquipmentSchedule WITH (NOLOCK) on J_Workload.EquipmentScheduleId =M_EquipmentSchedule.EquipmentScheduleId
	where J_Workload.EquipmentScheduleId IN (SELECT * FROM fnStringToTable(@ScheduledIdList))
	order by StartTime
end
--else if @WorkType = 3
--begin
--	select SkillId,StartTime,EndTime,0 'EquipmentId' , J_Workload.OUId
--	,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',J_Workload.ScheduleId	from J_Workload
--		where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType and
--	( StartTime <= @StartTime  and EndTime >= @EndTime
--	 or StartTime <= @StartTime  and EndTime < @EndTime and EndTime > @StartTime
--	 or StartTime > @StartTime  and EndTime <= @EndTime
--	 or StartTime >= @StartTime and StartTime <@EndTime)
--	order by StartTime
--end
else if @WorkType = 4
begin
	SELECT	WorkloadId, SkillId,StartTime,EndTime,0 'EquipmentId' , J_Workload.OUId ,DATEDIFF ( minute , StartTime , EndTime ) 'Duration',
			M_VesselSchedule.VesselScheduleId 'ScheduleId'	
	FROM	J_Workload WITH (NOLOCK)
			INNER JOIN M_VesselSchedule WITH (NOLOCK) on J_Workload.ScheduleId =M_VesselSchedule.VesselScheduleId
	WHERE	J_Workload.VesselScheduleId  IN (SELECT * FROM fnStringToTable(@ScheduledIdList))
	ORDER BY StartTime
end



GO
	IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LocationsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LocationsDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 Create PROCEDURE [dbo].[prM_LocationsDel]    
(	
	@LocationId	           BigInt 
)
AS
BEGIN
	 

	Update M_Locations  set ActiveStatus =0 where LocationId =@LocationId 
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LocationsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LocationsIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_LocationsIns]    
(		
	@OUId					Bigint, 
	@LocationName			nVarchar(500),
	@LocationDesc			nVarchar(1000),
	@ActiveStatus			INT,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Locations WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(LocationName))) = LTrim(RTrim(Upper(@LocationName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_Locations
		(LocationName,LocationDesc, OUId,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@LocationName, @LocationDesc,@OUId,@ActiveStatus,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LocationsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LocationsSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_LocationsSel]    
(
	@LocationId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_Locations.LocationId,
			M_Locations.LocationName,
			M_Locations.LocationDesc,
			M_Locations.ActiveStatus,
			M_Locations.OUId ,			 
			M_Locations.CreatedBy, 
			M_Locations.CreatedDate,
			M_Locations.UpdatedBy,
			M_Locations.UpdatedDate
	FROM	M_Locations	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Locations.OUId = C_OrganizationNode.OUId
	WHERE	(M_Locations.LocationId = @LocationId OR @LocationId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LocationsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LocationsUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_LocationsUpd]    
(
	@LocationId			BigInt,
	@LocationName		nVarchar(500),
	@LocationDesc		nVarchar(1000),
	@ActiveStatus		INT,
	@OUId			    Bigint,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_Locations WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(LocationName))) = LTrim(RTrim(Upper(@LocationName)))
	AND		LocationId	!=	@LocationId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_Locations
		SET		LocationName			=	@LocationName, 
				LocationDesc			=	@LocationDesc, 
				ActiveStatus			=	@ActiveStatus, 
				OUId					=	@OUId,  
				UpdatedBy				=	@UpdatedBy,
				UpdatedDate				=	GETDATE()				
		WHERE	LocationId				=	@LocationId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_RevokeShiftSignOff')
	DROP PROC prM_RevokeShiftSignOff
GO

----------------------------------------------------------------------------
-- Update Required Shift Sign Off
----------------------------------------------------------------------------
CREATE PROC prM_RevokeShiftSignOff
(
	@OUId			BigInt,
	@ShiftBandId	BigInt,
	@ShiftDate		DateTime,
	@StartTime		DateTime,
	@EndTime		DateTime,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	DELETE FROM J_ActivityAttributes  
	WHERE ActivityId IN (SELECT Activityid FROM J_Activity 
						 WHERE	StartTime	>=	@StartTime 
						 AND		StartTime	<	@EndTime 
						 AND		ShiftBandId =	@ShiftBandId 
						 AND		OUId		=	@OUId);

	DELETE FROM J_Activity
	WHERE	StartTime	>=	@StartTime 
	AND		StartTime	<	@EndTime 
	AND		ShiftBandId =	@ShiftBandId 
	AND		OUId		=	@OUId;


	UPDATE	J_Workload SET SignOffStatus = 0 
	WHERE	StartTime	>=	@StartTime 
	AND		StartTime	<	@EndTime 
	AND		ShiftBandId =	@ShiftBandId 
	AND		OUId		=	@OUId;

	UPDATE	M_EquipmentSchedule SET SignOffStatus = 0
	WHERE	StartDate	>=	@StartTime 
	AND		StartDate	<	@EndTime 
	AND		OUId		=	@OUId;

	UPDATE	M_CraneSchedule SET SignOffStatus = 0
	WHERE	StartDate	>=	@StartTime 
	AND		StartDate	<	@EndTime 
	AND		OUId		=	@OUId;

	UPDATE	M_VesselSchedule SET Status = 1
	WHERE	StartDate	>=	@StartTime 
	AND		StartDate	<	@EndTime 
	AND		OUId		=	@OUId;

	DELETE	FROM  M_AuxiliaryWork --SET SignOffStatus = 0
	WHERE	EndDate		>	@StartTime
	AND		StartDate	<	@EndTime 
	--AND		ShiftBandId =	@ShiftBandId 
	AND		OUId		=	@OUId;

	DELETE	FROM  J_Workload --SET SignOffStatus = 0
	WHERE	EndTime		>	@StartTime
	AND		StartTime	<	@EndTime
	AND		WorkType	=	3	-- Delete Auxiliary Work
	AND		OUId		=	@OUId;

	DELETE FROM  M_ShiftSignOffStatus
	WHERE	StartTime	>=	@StartTime 
	AND		StartTime	<	@EndTime 
	AND		ShiftBandId =	@ShiftBandId 
	AND		OUId		=	@OUId;

	SELECT 1;
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_SkillMatrixSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_SkillMatrixSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prM_SkillMatrixSel]    
(
	@SkillMatrixId		BigInt,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	M_SkillMatrix.SkillMatrixId,
			M_SkillMatrix.OUId,
			M_SkillMatrix.MatrixSkillId,
			M_SkillMatrix.SkillMatrixName,		 
			M_SkillMatrix.CreatedBy, 
			M_SkillMatrix.CreatedDate,
			M_SkillMatrix.UpdatedBy,
			M_SkillMatrix.UpdatedDate
	FROM	M_SkillMatrix WITH (NOLOCK) 			 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_SkillMatrix.OUId = C_OrganizationNode.OUId
	WHERE	(M_SkillMatrix.SkillMatrixId = @SkillMatrixId OR @SkillMatrixId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_SkillMatrixSkillsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_SkillMatrixSkillsSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prM_SkillMatrixSkillsSel]    
(
	@SkillMatrixId		BigInt
)
AS
BEGIN
	SELECT	M_SkillMatrix_Skills.SkillMatrixDetailsId,
			M_SkillMatrix.SkillMatrixId,
			M_SkillMatrix_Skills.SkillId,
			M_SkillMatrix_Skills.SkillMatrixScheduleId,
			M_SkillMatrix_Schedule.ScheduledValue,
			D_Skill.Skill SkillName,
			M_SkillMatrix_Skills.SkillValue,		 
			M_SkillMatrix_Skills.CreatedBy, 
			M_SkillMatrix_Skills.CreatedDate,
			M_SkillMatrix_Skills.UpdatedBy,
			M_SkillMatrix_Skills.UpdatedDate
	FROM	M_SkillMatrix_Skills WITH (NOLOCK) 			 
			INNER JOIN M_SkillMatrix with (NOLOCK) ON M_SkillMatrix_Skills.SkillMatrixId = M_SkillMatrix.SkillMatrixId
			INNER JOIN M_SkillMatrix_Schedule WITH (NOLOCK) ON M_SkillMatrix_Schedule.SkillMatrixScheduleId = M_SkillMatrix_Skills.SkillMatrixScheduleId
			AND M_SkillMatrix_Schedule.SkillMatrixId = M_SkillMatrix.SkillMatrixId
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_SkillMatrix_Skills.SkillId
	WHERE	(M_SkillMatrix.SkillMatrixId = @SkillMatrixId OR @SkillMatrixId = 0)
	ORDER BY D_Skill.Skill
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_UpdateAuxiliaryWorkByScheduleId')
	DROP PROC prM_UpdateAuxiliaryWorkByScheduleId
GO

----------------------------------------------------------------------------
-- Update a single record in M_AuxiliaryWork
----------------------------------------------------------------------------
CREATE PROC prM_UpdateAuxiliaryWorkByScheduleId
	@ScheduleId bigint,
	@OUId bigint = NULL,
	@ShiftBandId bigint = NULL,
	@SkillId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@Requirement int =null,
	@WorkloadGenereated bit = NULL,
	@SignOffStatus bit = NULL,
	@UpdatedBy nvarchar(100) = NULL
AS

UPDATE	M_AuxiliaryWork
SET	OUId = @OUId,
	ShiftBandId = @ShiftBandId,
	SkillId = @SkillId,
	StartDate = @StartDate,
	EndDate = @EndDate,
	Requirement= @Requirement,
	WorkloadGenereated = @WorkloadGenereated,
	SignOffStatus = @SignOffStatus,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	ScheduleId = @ScheduleId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_UpdateCraneScheduleByCraneScheduleId')
	DROP PROCEDURE prM_UpdateCraneScheduleByCraneScheduleId
GO

CREATE PROC prM_UpdateCraneScheduleByCraneScheduleId
	@CraneScheduleId bigint,
	@OUId bigint = NULL,
	@CraneId bigint = NULL,
	@VesselScheduleId bigint = NULL,
	@LocationId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@Imported bit = NULL,
	@WorkloadGenerated bit = NULL,
	@SignOffStatus bit = NULL,
	@UpdatedBy nvarchar(100) = NULL
	
AS

UPDATE	M_CraneSchedule
SET	OUId = @OUId,
	CraneId = @CraneId,
	VesselScheduleId = @VesselScheduleId,
	LocationId = @LocationId,
	StartDate = @StartDate,
	EndDate = @EndDate,
	Imported = @Imported,
	WorkloadGenerated = @WorkloadGenerated,
	SignOffStatus = @SignOffStatus,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	CraneScheduleId = @CraneScheduleId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_UpdateEquipmentScheduleByEquipmentScheduleId')
	DROP PROC prM_UpdateEquipmentScheduleByEquipmentScheduleId
GO

----------------------------------------------------------------------------
-- Update a single record in M_EquipmentSchedule
----------------------------------------------------------------------------
CREATE PROC prM_UpdateEquipmentScheduleByEquipmentScheduleId
	@EquipmentScheduleId bigint,
	@OUId bigint = NULL,
	@EquipmentTypeId bigint = NULL,
	@EquipmentId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@CraneScheduleId bigint = NULL,
	@WorkloadGenereated bit = NULL,
	@SignOffStatus bit = NULL,
	@UpdatedBy nvarchar(100) = NULL
	
AS

UPDATE	M_EquipmentSchedule
SET		OUId = @OUId,
		EquipmentTypeId = @EquipmentTypeId,
		EquipmentId = @EquipmentId,
		StartDate = @StartDate,
		EndDate = @EndDate,
		CraneScheduleId = @CraneScheduleId,
		WorkloadGenereated = @WorkloadGenereated,
		SignOffStatus = @SignOffStatus,
		UpdatedBy = @UpdatedBy,
		UpdatedDate = GETDATE()
WHERE 	EquipmentScheduleId = @EquipmentScheduleId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_UpdateShiftSignOffStatus')
	DROP PROC prM_UpdateShiftSignOffStatus
GO

----------------------------------------------------------------------------
-- Update Shift Sign Off Status prM_UpdateShiftSignOffStatus
----------------------------------------------------------------------------
CREATE PROC prM_UpdateShiftSignOffStatus
	@StatusId					BigInt,
	@SignOffStatus				Int,
	@DeployedBy					nVarchar(100) = NULL,
	@DeployedDate				DateTime = NULL,
	@DeploymentPublishedBy		nVarchar(100) ,
	@DeploymentPublishedDate	DateTime
AS

--UPDATE J_Activity SET ProgresstionState = 2 WHERE StartTime >= @StartTime AND StartTime < @EndTime

--UPDATE J_Workload SET SignOffStatus = 1 WHERE StartTime >= @StartTime AND StartTime < @EndTime

--UPDATE M_EquipmentSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime

--UPDATE M_CraneSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime

--UPDATE M_VesselSchedule SET Status = 2 WHERE StartDate >= @StartTime AND StartDate < @EndTime

	UPDATE	M_ShiftSignOffStatus
	SET		[Status]					=	@SignOffStatus,
			DeployedBy					=	@DeployedBy,
			DeployedDate				=	@DeployedDate,
			DeploymentPublishedBy		=	@DeploymentPublishedBy,
			DeploymentPublishedDate		=	@DeploymentPublishedDate
	WHERE	StatusId					=	@StatusId

	SELECT 1

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_UpdateVesselListByName')
	DROP PROCEDURE prM_UpdateVesselListByName

GO

CREATE PROC prM_UpdateVesselListByName
	
	@VesselName nvarchar(1000) = NULL,
	@LastVisitStartDate datetime = NULL,
	@LastVisitEndDate datetime = NULL,
	@CraneReq int = NULL,
	@UpdatedBy nvarchar(100) = NULL
AS

UPDATE	M_VesselList
SET	VesselName = @VesselName,
	LastVisitStartDate = @LastVisitStartDate,
	LastVisitEndDate = @LastVisitEndDate,
	CraneReq = @CraneReq,
	
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	VesselName = @VesselName

select  CAST(@@Identity AS INTEGER) 

GO

/****** Object:  StoredProcedure [dbo].[prM_UpdateVesselScheduleByVesselScheduleId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_UpdateVesselScheduleByVesselScheduleId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prM_UpdateVesselScheduleByVesselScheduleId
GO

create PROC [dbo].[prM_UpdateVesselScheduleByVesselScheduleId]
	@VesselScheduleId bigint,
	@OUId bigint = NULL,
	@VesselName nvarchar(2000) = NULL,
	@VisitId nvarchar(200) = NULL,
	@BerthId bigint = NULL,
	@StartDate datetime = NULL,
	@EndDate datetime = NULL,
	@ETA datetime = NULL,
	@ETD datetime = NULL,
	@NoOfCraneReq int = NULL,
	@Priority int = NULL,
	@Status int = NULL,
	@CraneScheduled bit = NULL,
	@IsImported bit = NULL,
	@ResourceSetId BigInt = NULL,
	@VesselType	nVarchar(100) = NULL,
	@Remarks	nVarchar(500) = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@UpdateType int
AS

	If (@UpdateType = 3 OR @UpdateType = 0)
		UPDATE	M_VesselSchedule
		SET		OUId = @OUId,
				VesselName = @VesselName,
				VisitId = @VisitId,
				BerthId = @BerthId,
				StartDate = @StartDate,
				EndDate = @EndDate,
				ETA = @ETA,
				ETD = @ETD,
				NoOfCraneReq = @NoOfCraneReq,
				Priority = COALESCE(@Priority, (1)),
				Status = COALESCE(@Status, (1)),
				CraneScheduled = COALESCE(@CraneScheduled, (0)),
				IsImported = COALESCE(@IsImported, (0)),
				ResourceSetId = @ResourceSetId,
				VesselType	=	@VesselType,
				Remarks		=	@Remarks,
				UpdatedBy = @UpdatedBy,
				UpdatedDate = GETDATE()
		WHERE 	VesselScheduleId = @VesselScheduleId
	Else if (@UpdateType = 1)
		UPDATE	M_VesselSchedule 
		SET		StartDate			=	@StartDate
		WHERE	VesselScheduleId	=	@VesselScheduleId
	Else If (@UpdateType = 2)
		UPDATE	M_VesselSchedule 
		SET		StartDate			=	@StartDate
		WHERE	VesselScheduleId	=	@VesselScheduleId

	SELECT @VesselScheduleId
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleByDateRange]
GO
 
create PROC [dbo].[prM_VesselScheduleByDateRange]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime
AS

SELECT	VesselScheduleId,
		M_VesselSchedule.OUId,
		VesselName,
		VisitId,
		M_VesselSchedule.BerthId,
		M_Berth.Berth,
		StartDate,
		EndDate,
		ETA,
		ETD,
		NoOfCraneReq,
		Priority,
		Status,
		CraneScheduled,
		IsImported,
		M_VesselSchedule.ResourceSetId,
		M_VesselSchedule.CreatedBy,
		M_VesselSchedule.CreatedDate,
		M_VesselSchedule.UpdatedBy,
		M_VesselSchedule.UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
		INNER JOIN M_Berth WITH (NOLOCK) ON M_VesselSchedule.BerthId = M_Berth.BerthId
WHERE 	M_VesselSchedule.OUId=@OUId
AND 	(EndDate > CONVERT(DATETIME, @StartDate)
AND 	StartDate < CONVERT(DATETIME, @EndDate))

GO
/****** Object:  StoredProcedure [dbo].[prM_VesselScheduleByDateRangeAndBerthId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByDateRangeAndBerthId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prM_VesselScheduleByDateRangeAndBerthId
GO

create PROC [dbo].[prM_VesselScheduleByDateRangeAndBerthId]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@BerthId bigint
AS

SELECT	VesselScheduleId,
	OUId,
	VesselName,
	VisitId,
	BerthId,
	StartDate,
	EndDate,
	ETA,
	ETD,
	NoOfCraneReq,
	Priority,
	Status,
	CraneScheduled,
	IsImported,
	M_VesselSchedule.ResourceSetId,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
WHERE OUId=@OUId and BerthId=@BerthId
AND
(EndDate >= CONVERT(DATETIME, @StartDate)
AND StartDate < CONVERT(DATETIME, @EndDate))

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap]
GO
 
create PROC [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@BerthId int
AS

SELECT	VesselScheduleId,
	OUId,
	VesselName,
	VisitId,
	BerthId,
	StartDate,
	EndDate,
	ETA,
	ETD,
	NoOfCraneReq,
	Priority,
	Status,
	CraneScheduled,
	IsImported,
	ResourceSetId,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND BerthId = @BerthId
AND
(EndDate <= CONVERT(DATETIME, @EndDate)
AND StartDate >= CONVERT(DATETIME, @StartDate))



GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_EndTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_EndTime]
GO
 
create PROC [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_EndTime]
	@OUId bigint,
	@EndTime DateTime,
	@BerthId int
AS

SELECT	VesselScheduleId,
	OUId,
	VesselName,
	VisitId,
	BerthId,
	StartDate,
	EndDate,
	ETA,
	ETD,
	NoOfCraneReq,
	Priority,
	Status,
	CraneScheduled,
	IsImported,
	M_VesselSchedule.ResourceSetId,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND BerthId = @BerthId
AND
(EndDate >= CONVERT(DATETIME, @EndTime)
AND StartDate < CONVERT(DATETIME, @EndTime))

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_StartTime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_StartTime]
GO
 
create PROC [dbo].[prM_VesselScheduleByDateRangeByBerthForOverlap_StartTime]
	@OUId bigint,
	@StartDate DateTime,
	@BerthId int
AS


SELECT	VesselScheduleId,
	OUId,
	VesselName,
	VisitId,
	BerthId,
	StartDate,
	EndDate,
	ETA,
	ETD,
	NoOfCraneReq,
	Priority,
	Status,
	CraneScheduled,
	IsImported,
	M_VesselSchedule.ResourceSetId,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
WHERE OUId=@OUId AND BerthId = @BerthId
AND
(EndDate > CONVERT(DATETIME, @StartDate)
AND StartDate <= CONVERT(DATETIME, @StartDate))


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_VesselScheduleByVesselScheduleId')
	DROP PROCEDURE prM_VesselScheduleByVesselScheduleId
GO
 
 
CREATE PROC prM_VesselScheduleByVesselScheduleId
	@VesselScheduleId bigint,
	@OUId	BigInt
AS
BEGIN

	-- Retrieve Vessel Schedule
	SELECT	VesselScheduleId,
			M_VesselSchedule.OUId,
			VesselName,
			VisitId,
			M_VesselSchedule.BerthId,
			M_Berth.Berth,
			StartDate,
			Convert(nVarchar,StartDate,120) StartDateString,
			EndDate,
			Convert(nVarchar,EndDate,120) EndDateString,
			ETA,
			Convert(nVarchar,ETA,120) ETAString,
			ETD,
			Convert(nVarchar,ETD,120) ETDString,
			NoOfCraneReq,
			Priority,
			Status,
			CraneScheduled,
			IsImported,
			M_ResourceSet.ResourceSetId,
			M_ResourceSet.SetName ResourceSetName,
			M_VesselSchedule.CreatedBy,
			M_VesselSchedule.CreatedDate,
			M_VesselSchedule.UpdatedBy,
			M_VesselSchedule.UpdatedDate,
			M_VesselSchedule.VesselType,
			M_VesselSchedule.Remarks
	FROM	M_VesselSchedule WITH (NOLOCK) 
			INNER JOIN M_Berth WITH (NOLOCK) ON M_VesselSchedule.BerthId = M_Berth.BerthId
			LEFT OUTER JOIN M_ResourceSet WITH (NOLOCK) ON M_ResourceSet.ResourceSetId = M_VesselSchedule.ResourceSetId
	WHERE 	(VesselScheduleId = @VesselScheduleId OR @VesselScheduleId = 0)
	AND		(M_VesselSchedule.OUId = @OUId OR @OUId = 0)

	-- Retrieve Resource Set Assigned To Selected Vessel Schedule
	SELECT J_WorkLoad.SkillId, D_Skill.SKill SkillName, Count(*) Requirement
	FROM J_Workload WITH (NOLOCK) INNER JOIN D_Skill WITH (NOLOCK) ON J_Workload.SkillId = D_Skill.SkillId 
	WHERE VesselScheduleId = @VesselScheduleId
	Group By J_WorkLoad.SkillId, D_Skill.Skill 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleByVisitId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleByVisitId]
GO
 
create PROC [dbo].[prM_VesselScheduleByVisitId]
	@VisitId nvarchar(100)
	
AS

SELECT	VesselScheduleId,
		M_VesselSchedule.OUId,
		VesselName,
		VisitId,
		M_VesselSchedule.BerthId,
		StartDate,
		Convert(nVarchar,StartDate,120) StartDateString,
		EndDate,
		Convert(nVarchar,EndDate,120) EndDateString,
		ETA,
		Convert(nVarchar,ETA,120) ETAString,
		ETD,
		Convert(nVarchar,ETD,120) ETDString,
		NoOfCraneReq,
		Priority,
		Status,
		CraneScheduled,
		IsImported,
		ResourceSetId,
		M_VesselSchedule.CreatedBy,
		M_VesselSchedule.CreatedDate,
		M_VesselSchedule.UpdatedBy,
		M_VesselSchedule.UpdatedDate
FROM	M_VesselSchedule WITH (NOLOCK)
WHERE 	VisitId = @VisitId


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prProcess_THPProcessByDay')
	DROP PROC prProcess_THPProcessByDay
GO
----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeDetails
----------------------------------------------------------------------------
CREATE PROC [dbo].[prProcess_THPProcessByDay]
	@ShiftBandId bigint = NULL,	
	@ShiftDate datetime = NULL,
	@CreatedBy nvarchar(50)
	
AS
declare @ShiftId bigint
declare @ActualStartTime datetime
declare @ActuelEndTime Datetime
declare @THPPeriodId bigint
declare @EmployeeId bigint
declare @LeaveId bigint
declare @ShiftHour Decimal(18,2) 
declare	@ActivityHour Decimal(18,2) 

DECLARE curShifts CURSOR FOR 
SELECT shiftid,actualstarttime,ActualEndtime,EmployeeId from S_Shifts WITH (NOLOCK)
where ShiftBandId=@ShiftBandId and CONVERT(date,actualstarttime) = CONVERT(date,@ShiftDate)


OPEN curShifts  
FETCH NEXT FROM curShifts INTO @ShiftId,@ActualStartTime,@ActuelEndTime,@EmployeeId

WHILE @@FETCH_STATUS = 0  
BEGIN  

	--TODO: Delete From THP By Employee id And Shift Date Instead of Shift Id

	DELETE FROM S_THPEmployeeDetails 
	Where	EmployeeId						=	@EmployeeId
	And		Convert(Date,ShiftDate)	=	Convert(Date,@ShiftDate)

	--where ShiftId=@ShiftId

	
	 select @ShiftHour = DATEDIFF ( hour , ActualStartTime , ActualEndTime )  from S_Shifts WITH (NOLOCK)
	where ShiftId = @ShiftId

	select @ActivityHour = Sum(DATEDIFF ( hour , StartTime , EndTime )) from J_Activity WITH (NOLOCK)
	where ShiftId = @ShiftId

	SET @LeaveId  = 0

	select @LeaveId= IsNull(LeaveId,0) from S_EmployeeLeaves WITH (NOLOCK)
	where ShiftId=@ShiftId

	select  @THPPeriodId= THPPeriodId from S_THPEmployeePeriods WITH (NOLOCK)
	where EmployeeId=@EmployeeId 
	and convert(date,PeriodStart)<= convert(date,@ShiftDate)
	and convert(date,PeriodEnd)>= convert(date,@ShiftDate)

	INSERT S_THPEmployeeDetails(THPPeriodId, EmployeeId, ShiftDate, ShiftId, LeaveId, ShiftCounter, ActivityCounter, LeaveCounter, NormalHour, OTHour, THPProcessDate, THPNotes, CreatedBy, CreatedDate)
	VALUES (@THPPeriodId, @EmployeeId, @ShiftDate, @ShiftId, @LeaveId, @ShiftHour, @ActivityHour, 0, 0, 0, null, null, @CreatedBy, getdate())

	FETCH NEXT FROM curShifts INTO @ShiftId,@ActualStartTime,@ActuelEndTime,@EmployeeId

END

CLOSE curShifts  
DEALLOCATE curShifts

SELECT 1

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pRpt_LeaveReport')
	DROP PROC pRpt_LeaveReport
GO

CREATE  PROCEDURE [dbo].[pRpt_LeaveReport](
	@StartDate			datetime,
	@EndDate			datetime,
	--@OUID               BigInt,
	@FilteredOUList		nVarchar(max),
	@LeaveType	       nVarchar(max),
	@ApplicationStatus  nVarchar(max),
	@EmployeeNumber     nvarchar(50),
	@LeaveDateParameterType int,
	@RosterGroup     nvarchar(50)

	)

AS
BEGIN  

if(len(@EmployeeNumber) = 0) set @EmployeeNumber='0'
if(len(@LeaveType) = 0) SET @LeaveType = '0'
if(len(@RosterGroup) = 0) SET @RosterGroup = '0'
if(len(@ApplicationStatus) = 0) SET @ApplicationStatus = '0'
if @LeaveDateParameterType = 2 
begin
		SELECT C_Employee.EmployeeNumber ,C_Employee.DisplayName EmpName,C_OrganizationNode.OUName Department,AppliedDate TransDate,ExceptionCodeDesc LeaveCode,ReasonId ReasonCode,LeaveStart FromDate,LeaveEnd ToDate,
			   NoOfDays,W_ApprovalStatus.ApprovalStatus ApprovalStatusName
		FROM  L_Leaves	 WITH (NOLOCK) 
	inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
	inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
	inner join W_ApprovalStatus WITH (NOLOCK) on W_ApprovalStatus.ApprovalStatusId = L_Leaves.ApprovalStatusId
		WHERE W_ApprovalStatus.ApprovalStatusId IN (SELECT * FROM fnStringToTable(@ApplicationStatus))
	and(L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
	and  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	--and D_ExceptionCodes.ExceptionCodeId=@LeaveType
	and (D_ExceptionCodes.ExceptionCodeId in (SELECT * FROM fnStringToTable(@LeaveType)) OR @LeaveType = '0')
	and (C_Employee.rostergroupid in (SELECT * FROM fnStringToTable(@RosterGroup)) OR @RosterGroup = '0')
	and C_Employee.IsTerminated=0
	and (C_Employee.EmployeeNumber=@EmployeeNumber or @EmployeeNumber='0')
	order by C_OrganizationNode.OUName,EmployeeNumber,ExceptionCodeDesc
end
else
begin
	SELECT C_Employee.EmployeeNumber ,C_Employee.DisplayName EmpName,C_OrganizationNode.OUName Department,AppliedDate TransDate,ExceptionCodeDesc LeaveCode,ReasonId ReasonCode,LeaveStart FromDate,LeaveEnd ToDate,
			   NoOfDays,W_ApprovalStatus.ApprovalStatus ApprovalStatusName
		FROM  L_Leaves	WITH (NOLOCK) 
	inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
	inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
	inner join W_ApprovalStatus WITH (NOLOCK) on W_ApprovalStatus.ApprovalStatusId = L_Leaves.ApprovalStatusId
		WHERE W_ApprovalStatus.ApprovalStatusId IN (SELECT * FROM fnStringToTable(@ApplicationStatus))
	and(Convert(Date,L_Leaves.AppliedDate) >=Convert(Date,@StartDate) and Convert(Date,L_Leaves.AppliedDate) <=Convert(Date,@EndDate))
	and  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	and (D_ExceptionCodes.ExceptionCodeId in (SELECT * FROM fnStringToTable(@LeaveType)) OR @LeaveType = '0')
	and (C_Employee.rostergroupid in (SELECT * FROM fnStringToTable(@RosterGroup)) OR @RosterGroup = '0')
	and C_Employee.IsTerminated=0
	and (C_Employee.EmployeeNumber=@EmployeeNumber or @EmployeeNumber='0')
	order by C_OrganizationNode.OUName,EmployeeNumber,ExceptionCodeDesc
end
END
GO

	IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pRpt_SickLeaveSummary')
	DROP PROC pRpt_SickLeaveSummary
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE  PROCEDURE [dbo].[pRpt_SickLeaveSummary](
	@StartDate			datetime,
	@EndDate			datetime,
	@FilteredOUList		nVarchar(max),
	@LeaveType	        nVarchar(max),
	@RosterGroupList  nVarchar(max)

	)

AS
BEGIN  

if(len(@LeaveType) = 0) set @LeaveType='2,13,14'

if(len(@RosterGroupList) = 0) set @RosterGroupList='0'



	SELECT C_Employee.EmployeeNumber ,C_Employee.DisplayName EmployeeName,C_OrganizationNode.OUName OUName	,
case  
when FORMAT (LeaveStart,'MM') =1 then convert(int,sum(NoOfDays))  else 0 end JanCount,
case  when FORMAT (LeaveStart,'MM') =2 then convert(int,sum(NoOfDays))  else 0 end FebCount,
case  when FORMAT (LeaveStart,'MM') =3 then convert(int,sum(NoOfDays))  else 0 end MarCount,
case  when FORMAT (LeaveStart,'MM') =4 then convert(int,sum(NoOfDays))  else 0 end AprCount,
case  when FORMAT (LeaveStart,'MM') =5 then convert(int,sum(NoOfDays))  else 0 end MayCount,
case  when FORMAT (LeaveStart,'MM') =6 then convert(int,sum(NoOfDays))  else 0 end JuneCount,
case  when FORMAT (LeaveStart,'MM') =7 then convert(int,sum(NoOfDays))  else 0 end JulyCount,
case  when FORMAT (LeaveStart,'MM') =8 then convert(int,sum(NoOfDays))  else 0 end AugCount,
case  when FORMAT (LeaveStart,'MM') =9 then convert(int,sum(NoOfDays))  else 0 end SepCount,
case  when FORMAT (LeaveStart,'MM') =10 then convert(int,sum(NoOfDays))  else 0 end OctCount,
case  when FORMAT (LeaveStart,'MM') =11 then convert(int,sum(NoOfDays))  else 0 end NovCount,
case  when FORMAT (LeaveStart,'MM') =12 then convert(int,sum(NoOfDays))  else 0 end DecCount
	FROM  L_Leaves	WITH (NOLOCK) 
inner join C_Employee WITH (NOLOCK)  on C_Employee.EmployeeId = L_Leaves.EmployeeId
inner join C_OrganizationNode WITH (NOLOCK)  ON C_Employee.OUId = C_OrganizationNode.OUId
where
 C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
 and  (L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
 and L_Leaves.ExceptionCodeId in  (SELECT * FROM fnStringToTable(@LeaveType)) 
 and ApprovalStatusId=1
group by FORMAT (LeaveStart,'MM'),
C_Employee.EmployeeNumber ,C_Employee.DisplayName ,C_OrganizationNode.OUName 
order by C_OrganizationNode.OUName,EmployeeNumber



	

	SELECT C_Employee.EmployeeNumber ,C_Employee.DisplayName EmployeeName,C_OrganizationNode.OUName OUName	
,convert(int,sum(NoOfDays)) TotCount
,case when  sum(NoOfDays)  <=14 then convert(int,sum(NoOfDays) )
	when  sum(NoOfDays)  > 14 then 14  end Count0
,case when sum(NoOfDays)  >14 and sum(NoOfDays)  <=28 then convert(int,sum(NoOfDays)) -14
		when sum(NoOfDays)  >28 then 14  else  0 end Count25
, case when sum(NoOfDays)  >28 and sum(NoOfDays)  <=42 then  convert(int,sum(NoOfDays)) -28
		when sum(NoOfDays)  > 42 then 14 else 0 end Count50
, case when sum(NoOfDays)  >42 and  sum(NoOfDays)  <= 70 then convert(int,sum(NoOfDays)) -42
		when sum(NoOfDays)  >70 then 28 else 0 end Count75
, case when sum(NoOfDays)  > 70 then convert(int,sum(NoOfDays)) -70 else 0 end Count100
	FROM  L_Leaves	WITH (NOLOCK) 
inner join C_Employee WITH (NOLOCK)  on C_Employee.EmployeeId = L_Leaves.EmployeeId
inner join C_OrganizationNode WITH (NOLOCK)  ON C_Employee.OUId = C_OrganizationNode.OUId
where
 C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
 and  (L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
 and L_Leaves.ExceptionCodeId in  (SELECT * FROM fnStringToTable(@LeaveType)) 
  and ApprovalStatusId=1
group by FORMAT (LeaveStart,'yyyy'),
C_Employee.EmployeeNumber ,C_Employee.DisplayName ,C_OrganizationNode.OUName 
order by C_OrganizationNode.OUName,EmployeeNumber


END



GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_AddOvertimeDayNightSettings')
	DROP PROC prP_AddOvertimeDayNightSettings
GO

----------------------------------------------------------------------------
-- Insert a single record into prP_AddOvertimeDayNightSettings
----------------------------------------------------------------------------
CREATE PROC prP_AddOvertimeDayNightSettings
	@OverTimeId			BigInt			=	NULL,
	@DayNightType		Int				=	NULL,
	@StartTime			DateTime		=	NULL,
	@EndTime			DateTime		=	NULL,
	@CreatedBy			nvarchar(100)	= NULL
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	P_OvertimeDayNightSettings WITH (NOLOCK)
	WHERE	DayNightType = @DayNightType
	AND		OvertimeId	 = @OverTimeId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT P_OvertimeDayNightSettings(OvertimeId, DayNightType, StartTime, EndTime, CreatedBy, CreatedDate)
		VALUES (@OverTimeId, @DayNightType, @StartTime, @EndTime, @CreatedBy, GETDATE() )

		SELECT  CAST(@@Identity AS bigint) 
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_AddOvertimeSettings')
	DROP PROC prP_AddOvertimeSettings
GO

----------------------------------------------------------------------------
-- Insert a single record into prP_AddOvertimeSettings
----------------------------------------------------------------------------
CREATE PROC prP_AddOvertimeSettings
	@OUId				BigInt			= NULL,
	@OvertimeName		nVarchar(500)	= NULL,
	@OvertimeDesc		nVarchar(1000)	= NULL,
	@PeriodUnit			int				= NULL,
	@PeriodLength		int				= NULL,
	@ApprovalRequired	Bit				= 0,
	@DayNightOvertime	Bit				= 0,
	@CreatedBy			nvarchar(100)	= NULL,
	@MaxOvrTimeSettings Decimal(18,2)   = 0
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	P_OvertimeSettings
	WHERE	LTrim(RTrim(Upper(OTName))) = LTrim(RTrim(Upper(@OvertimeName)))
	AND		OUId = @OUId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT P_OvertimeSettings(OUId, OTName, OTDesc, PeriodUnit, PeriodLength, ApprovalRequired, DayNightOvertime, CreatedBy, CreatedDate,MaxOvertimeHours)
		VALUES (@OUId, @OvertimeName, @OvertimeDesc, COALESCE(@PeriodUnit, (1)), @PeriodLength, @ApprovalRequired, @DayNightOvertime, @CreatedBy, GETDATE(),@MaxOvrTimeSettings)

		SELECT  CAST(@@Identity AS bigint) 
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_AddShiftCosts')
	DROP PROC prP_AddShiftCosts
GO

----------------------------------------------------------------------------
-- Insert a single record into P_ShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_AddShiftCosts
	@ShiftId bigint = NULL,
	@PayCodeId bigint = NULL,
	@StartTime datetime = NULL,
	@EndTime datetime = NULL,
	@ActualHour int = NULL,
	@ApprovedHours Decimal(18,5),
	@ShiftCost decimal(18, 5) = NULL,
	@AdjustmentCost decimal(18, 5) = NULL,
	@TotalCost decimal(18, 5) = NULL,
	@ApprovalStatus	Int,
	@CreatedBy nvarchar(100) = NULL
	
AS


INSERT P_ShiftCosts(ShiftId, PayCodeId, StartTime, EndTime, ActualHour, ApprovedHours, ApprovalStatus, ShiftCost, AdjustmentCost, TotalCost, CreatedBy, CreatedDate)
VALUES (@ShiftId, @PayCodeId, @StartTime, @EndTime, @ActualHour, @ApprovedHours, @ApprovalStatus, @ShiftCost, @AdjustmentCost, @TotalCost, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_DeleteEmployeeLeaveForPublicHolidayProcess')
	DROP PROC prP_DeleteEmployeeLeaveForPublicHolidayProcess
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prP_DeleteEmployeeLeaveForPublicHolidayProcess]    
(
	@LeaveId	        bigint
)
AS
BEGIN

declare @ShiftId Bigint

	select @ShiftId = Shiftid  from S_EmployeeLeaves
	where LeaveId=@LeaveId

	delete from S_EmployeeLeaves
	where LeaveId=@LeaveId

	DELETE FROM S_THPEmployeeDetails 
	WHERE	ShiftId = @ShiftId

	delete from S_Shifts
	where shiftid=@ShiftId

	select @ShiftId

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_DeleteOvertimeDayNightSettingsId')
	DROP PROC prP_DeleteOvertimeDayNightSettingsId
GO

----------------------------------------------------------------------------
-- Select a single record from prP_DeleteOvertimeDayNightSettingsId
----------------------------------------------------------------------------
CREATE PROC prP_DeleteOvertimeDayNightSettingsId
	@OTSettingsId		BigInt
AS

DELETE FROM P_OvertimeDayNightSettings
WHERE OTSettingsId = @OTSettingsId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_DeleteShiftCostsByShiftCostId')
	DROP PROC prP_DeleteShiftCostsByShiftCostId
GO

----------------------------------------------------------------------------
-- Delete a single record from P_ShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_DeleteShiftCostsByShiftCostId
	@ShiftCostId bigint
AS

DELETE	P_ShiftCosts
WHERE 	ShiftCostId = @ShiftCostId

SELECT 1
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_DeleteShiftCostsByShiftId')
	DROP PROC prP_DeleteShiftCostsByShiftId
GO

----------------------------------------------------------------------------
-- Delete a single record from P_ShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_DeleteShiftCostsByShiftId
	@ShiftId bigint
AS

DELETE	P_ShiftCosts
WHERE 	ShiftId = @ShiftId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetActingIncentveRate')
	DROP PROC prP_GetActingIncentveRate
GO

Create PROC [dbo].[prP_GetActingIncentveRate]
	
AS
select D_MasterCodes.CodeValue 'Positions',P_ActingIncentiveRates.IncentiveRate IncentiveRates from P_ActingIncentiveRates
inner join D_MasterCodes  on P_ActingIncentiveRates.PositionId= D_MasterCodes.CodeId

Go






IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetEmployeeActingIncentiveRateByEmployeeId')
	DROP PROC prP_GetEmployeeActingIncentiveRateByEmployeeId
GO

Create PROC [dbo].[prP_GetEmployeeActingIncentiveRateByEmployeeId]
	@EmployeeId Bigint,
	@ShiftId BigInt
AS
declare @ActCount int

select @ActCount = count(*)  from J_Activity
where shiftid =@ShiftId
and SkillId in (
select SkillId from C_EmployeeSkills
where IsActingSkill=1
and EmployeeId=@EmployeeId
)

select @ActCount

Go









/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_GetEmployeeListForPublicHolidayProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_GetEmployeeListForPublicHolidayProcess]
GO

CREATE PROCEDURE [dbo].[prP_GetEmployeeListForPublicHolidayProcess]    
(
	@IsTerminated int
)
AS
BEGIN
	select C_Employee.EmployeeId,EmployeeNumber,C_OrganizationNode.OUName,C_Employee.EmploymentBasisId,D_EmploymentBasis.EmploymentBasisCode,D_MasterCodes.CodeId ReligionId,D_MasterCodes.CodeValue ReligionName from C_Employee
	inner join C_EmployeeOU on C_Employee.EmployeeId= C_EmployeeOU.EmployeeId
	inner join C_OrganizationNode on C_EmployeeOU.OUId = C_OrganizationNode.OUId
	inner join D_EmploymentBasis on D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
	inner join D_MasterCodes on D_MasterCodes.CodeId = C_Employee.ReligionId and  CodeType='Religion'
	where C_Employee.IsTerminated=@IsTerminated
	order by EmployeeNumber,OUName

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetIsShiftComboShiftOrNot')
	DROP PROC prP_GetIsShiftComboShiftOrNot
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prP_GetIsShiftComboShiftOrNot]    
(
	@ShiftId	        bigint
)
AS
BEGIN


	select count(*) C from S_Shifts
	where CombinationShiftId=ShiftBandId
	and ShiftId=@ShiftId

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetListOfLeaveOnPublicHolidayByHolidayDate')
	DROP PROC prP_GetListOfLeaveOnPublicHolidayByHolidayDate
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prP_GetListOfLeaveOnPublicHolidayByHolidayDate]    
(
	@PublicHoliday	        DateTime
)
AS
BEGIN
select LeaveId,EmployeeId,ExceptionCodeId  from S_EmployeeLeaves
where ExceptionCodeId in (1,9)
AND 	Convert(Date,FromDate) = Convert(Date,@PublicHoliday)
order by fromDate

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetListOfShiftsOnPublicHolidayByHolidayDate')
	DROP PROC prP_GetListOfShiftsOnPublicHolidayByHolidayDate
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prP_GetListOfShiftsOnPublicHolidayByHolidayDate]    
(
	@PublicHoliday	        DateTime	
)
AS
BEGIN
select ShiftId,EmployeeId from S_Shifts
where Convert(Date,ShiftStartTime) = Convert(Date,@PublicHoliday)
order by ShiftStartTime

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetOvertimeDayNightSettingsByOvertimeId')
	DROP PROC prP_GetOvertimeDayNightSettingsByOvertimeId
GO

----------------------------------------------------------------------------
-- Select a single record from prP_GetOvertimeDayNightSettingsByOvertimeId
----------------------------------------------------------------------------
CREATE PROC prP_GetOvertimeDayNightSettingsByOvertimeId
	@OvertimeId		BigInt
AS

SELECT	P_OvertimeDayNightSettings.OTSettingsId,
		P_OvertimeDayNightSettings.OvertimeId,
		P_OvertimeDayNightSettings.DayNightType,
		P_OvertimeDayNightSettings.StartTime,
		P_OvertimeDayNightSettings.EndTime,
		P_OvertimeDayNightSettings.CreatedBy,
		P_OvertimeDayNightSettings.CreatedDate,
		P_OvertimeDayNightSettings.UpdatedBy,
		P_OvertimeDayNightSettings.UpdatedDate
FROM	P_OvertimeDayNightSettings
WHERE	(P_OvertimeDayNightSettings.OvertimeId = @OvertimeId OR @OvertimeId = 0)
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetOvertimeSettingsByOUId')
	DROP PROC prP_GetOvertimeSettingsByOUId
GO

----------------------------------------------------------------------------
-- Select a single record from prP_GetOvertimeSettingsByOUId
----------------------------------------------------------------------------
CREATE PROC prP_GetOvertimeSettingsByOUId
	@OUId			Bigint,
	@OvertimeId		BigInt
AS

SELECT	OvertimeId,
		OTName OvertimeName,
		OTDesc OvertimeDescription,
		PeriodUnit,
		PeriodLength,
		ApprovalRequired,
		DayNightOvertime,
		P_OvertimeSettings.CreatedBy,
		P_OvertimeSettings.CreatedDate,
		P_OvertimeSettings.UpdatedBy,
		P_OvertimeSettings.UpdatedDate,
		P_OvertimeSettings.OUId OuId,
		C_OrganizationNode.OUName OUName
FROM	P_OvertimeSettings WITH (NOLOCK) 
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON P_OvertimeSettings.OUId = C_OrganizationNode.OUId
WHERE 	(P_OvertimeSettings.OUId = @OUId OR @OUId = 0)
AND		(OvertimeId = @OvertimeId OR @OvertimeId = 0)

GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_GetPublicHolidayToProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_GetPublicHolidayToProcess]
GO

CREATE PROCEDURE [dbo].[prP_GetPublicHolidayToProcess]    
	@ProcessType	Int = 1
AS
BEGIN
	If (@ProcessType = 1)
	BEGIN
		select PublicHolidayId,HolidayDate,IsLeaveProcess,IsShiftProcess, HolidayName from D_PublicHolidays
		where IsLeaveProcess = 0 
		order by HolidayDate
	END
	Else If (@ProcessType = 2)
	BEGIN
		select PublicHolidayId,HolidayDate,IsLeaveProcess,IsShiftProcess, HolidayName from D_PublicHolidays
		where IsShiftProcess = 0 
		order by HolidayDate		
	END
END

GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_GetShiftIdBetweenDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_GetShiftIdBetweenDates]
GO

CREATE PROCEDURE [dbo].[prP_GetShiftIdBetweenDates]
(
	@StartDate		Date,
	@EndDate		Date
)    
AS
BEGIN
	SELECT	ShiftId 
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.InTime IS NOT NULL 
	AND		S_Shifts.OutTime IS NOT NULL
	--AND		S_Shifts.ShiftID = 1014051
	--AND		S_Shifts.OUID != 41
	--AND EMPLOYEEID IN (954,851,834,2073, 2167, 1863, 1996, 2037, 2110, 2041, 1218, 2115, 1826, 2049, 2050, 2123)
	AND EmployeeId IN (636) --(1813,985,2022)
	--AND		DateDiff(MI,ActualStartTime,ActualEndTime) < 300
	--AND		OUId not in (24)
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_ShiftCostsByShiftCostId')
	DROP PROC prP_ShiftCostsByShiftCostId
GO

----------------------------------------------------------------------------
-- Select a single record from P_ShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_ShiftCostsByShiftCostId
	@ShiftCostId bigint
AS

SELECT	ShiftCostId,
		ShiftId,
		PayCodeId,
		StartTime,
		EndTime,
		ActualHour,
		ApprovedHours,
		ApprovalStatus,
		ShiftCost,
		AdjustmentCost,
		TotalCost,
		CreatedBy,
		CreatedDate,
		UpdatedBy,
		UpdatedDate
FROM	P_ShiftCosts
WHERE 	ShiftCostId = @ShiftCostId

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_ShiftCostsByShiftId')
	DROP PROC prP_ShiftCostsByShiftId
GO

----------------------------------------------------------------------------
-- Select a single record from P_ShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_ShiftCostsByShiftId
	@ShiftId bigint
AS

SELECT	ShiftCostId,
		P_ShiftCosts.ShiftId,
		D_PayCodes.PayCode,
		P_ShiftCosts.PayCodeId,
		D_ShiftBand.ShiftBandCode,
		S_Shifts.ActualStartTime,
		S_Shifts.ActualEndTime,
		P_ShiftCosts.StartTime,
		P_ShiftCosts.EndTime,
		ActualHour,
		P_ShiftCosts.ShiftCost,
		AdjustmentCost,
		TotalCost,
		P_ShiftCosts.ApprovedHours,
		P_ShiftCosts.ApprovalStatus,
		P_ShiftCosts.CreatedBy,
		P_ShiftCosts.CreatedDate,
		P_ShiftCosts.UpdatedBy,
		P_ShiftCosts.UpdatedDate,
		D_PaygroupCodes.PaycodeType PayCodeTypeId,
		D_PayCodes.IsEditable
FROM	P_ShiftCosts WITH (NOLOCK) 
		INNER JOIN S_Shifts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId
		INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		INNER JOIN D_PayCodes WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId
		INNER JOIN D_PaygroupCodes WITH (NOLOCK) ON D_PaygroupCodes.PayCodeId = D_PayCodes.PayCodeId
WHERE 	P_ShiftCosts.ShiftId = @ShiftId

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_ShiftCostSummarySel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_ShiftCostSummarySel]
GO
/****** Object:  StoredProcedure [dbo].[prP_ShiftCostSummarySel]    Script Date: 8/8/2018 5:22:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prP_ShiftCostSummarySel] 
(
	@OUId					BigInt,
	--@Date					datetime,
	@StartDateTime			DateTime,
	@EndDateTime			DateTime,
	@ShiftBandId			nVarchar(max),
	@EmployeeNumber			nvarchar(50),
	@Reconstatusid			int,
	@TAExceptionId			int,
	@LoginUserEmployeeId	BigInt,
	@EmploymentBasisId		BigInt
)
AS
DECLARE @__shiftBandIds BIGINT = 0
BEGIN	 
	SELECT TOP 1 @__shiftBandIds = sID FROM fnStringToTable(@shiftbandid);
	--WorkFlowRoute (RouteId)
	--AS
	--(
	--	SELECT	Distinct RouteId 
	--	FROM	W_WorkflowRouteDetails WITH (NOLOCK)
	--	WHERE	EmployeeId = @LoginUserEmployeeId 
	--), 
	WITH ShiftCosts (ShiftId)
	AS
	(
			SELECT	DISTINCT S_Shifts.ShiftId
			FROM	S_Shifts WITH (NOLOCK)	
					INNER JOIN C_OrganizationNode WITH (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
					INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId = S_Shifts.EmployeeId
					--INNER JOIN WorkFlowRoute ON C_EmployeeWorkflow.RouteId = WorkFlowRoute.RouteId  AND C_EmployeeWorkflow.ModuleId = 204	
					LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
					LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
					LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
					LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
					LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
			WHERE 	C_OrganizationNode.OUId = @OUID 
			AND		CONVERT(DateTime,S_Shifts.ActualStartTime) >= CONVERT(DateTime,@StartDateTime)
			AND		Convert(DateTime,S_Shifts.ActualStartTime) <= Convert(DateTime,@EndDateTime)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
			AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
			AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
			AND		(S_Shifts.ReconFailureReasonId = @TAExceptionId OR @TAExceptionId = 0)
			AND		(C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
	)
	--SELECT	D_PayCodes.PayCode, Convert(Int,SUM(ApprovedHours)) TotalHours, Sum(TotalCost) TotalCost 
	--SELECT	D_PayCodes.PayCode, Convert(decimal(18,2),Round(SUM(ApprovedHours)/60,2)) TotalHours, Convert(decimal(18,2),Sum(TotalCost),2) TotalCost 
	SELECT	D_PayCodes.PayCode, SUM(ApprovedHours) TotalHours, Round(Sum(TotalCost),2) TotalCost 
	FROM	P_ShiftCosts WITH (NOLOCK)
			INNER JOIN D_PayCodes WITH (NOLOCK) ON P_ShiftCosts.PayCodeId = D_PayCodes.PayCodeId			
			INNER JOIN ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = ShiftCosts.ShiftId
	GROUP BY D_PayCodes.PayCode
END
GO

/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_UpdateDILBalanceForPublicHolidayForComboShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_UpdateDILBalanceForPublicHolidayForComboShift]
GO

CREATE PROCEDURE [dbo].[prP_UpdateDILBalanceForPublicHolidayForComboShift]    
(
	@EmployeeId	 BigInt ,
	@LeaveYear int,
	@ExceptionCodeId BigInt,
	@HolidayDate Date,
	@DaysToAdd	Float
)
AS
BEGIN

	
	update L_EmployeeLeaveProfiles
	set BalanceDays=BalanceDays + @DaysToAdd,EarnedDays=EarnedDays + @DaysToAdd
	where EmployeeId=@EmployeeId
	and LeaveYear=@LeaveYear
	and ExceptionId=@ExceptionCodeId

	SELECT 1


END

GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_UpdateLeaveBalanceForPublicHolidayForNonComboShift]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_UpdateLeaveBalanceForPublicHolidayForNonComboShift]
GO

CREATE PROCEDURE [dbo].[prP_UpdateLeaveBalanceForPublicHolidayForNonComboShift]    
(
	@EmployeeId	 BigInt ,
	@LeaveYear int,
	@ExceptionCodeId BigInt,
	@HolidayDate Date
)
AS
BEGIN

	
	update L_EmployeeLeaveProfiles
	set BalanceDays=BalanceDays+1,DaysUsed=DaysUsed-1
	where EmployeeId=@EmployeeId
	and LeaveYear=@LeaveYear
	and ExceptionId=@ExceptionCodeId



	update L_Leaves
	set NoOfDays=NoOfDays-1
	where LeaveId in
	(select LeaveId from L_Leaves WITH (NOLOCK)
	where EmployeeId=@EmployeeId and ExceptionCodeId=@ExceptionCodeId
	and Convert(Date,LeaveStart) <= Convert(Date,@HolidayDate) and  Convert(Date,LeaveEnd) >= Convert(Date,@HolidayDate)
	and ApprovalStatusId=1)
	END

	SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_UpdateOvertimeDayNightSettings')
	DROP PROC prP_UpdateOvertimeDayNightSettings
GO

----------------------------------------------------------------------------
-- Insert a single record into prP_UpdateOvertimeDayNightSettings
----------------------------------------------------------------------------
CREATE PROC prP_UpdateOvertimeDayNightSettings
	@OTSettingsId		BigInt			=	NULL,
	@OverTimeId			BigInt			=	NULL,
	@DayNightType		Int				=	NULL,
	@StartTime			DateTime		=	NULL,
	@EndTime			DateTime		=	NULL,
	@UpdatedBy			nvarchar(100)	= NULL
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	P_OvertimeDayNightSettings WITH (NOLOCK)
	WHERE	DayNightType = @DayNightType 
	AND		OTSettingsId != @OTSettingsId
	AND		OvertimeId	 = @OverTimeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE P_OvertimeDayNightSettings 
		SET		OvertimeId		=	@OverTimeId, 
				DayNightType	=	@DayNightType, 
				StartTime		=	@StartTime, 
				EndTime			=	@EndTime, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	OTSettingsId	=	@OTSettingsId

		SELECT 1
	END
	ELSE
	BEGIN
		SET @ValidateDuplicate = -1
		SELECT @ValidateDuplicate
	END

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_UpdateOvertimeSettings')
	DROP PROC prP_UpdateOvertimeSettings
GO

----------------------------------------------------------------------------
-- Update single record into prP_UpdateOvertimeSettings
----------------------------------------------------------------------------
CREATE PROC prP_UpdateOvertimeSettings
	@OvertimeId			BigInt			= NULL,
	@OUId				BigInt			= NULL,
	@OvertimeName		nVarchar(500)	= NULL,
	@OvertimeDesc		nVarchar(1000)	= NULL,
	@PeriodUnit			int				= NULL,
	@PeriodLength		int				= NULL,
	@ApprovalRequired	Bit				= 0,
	@DayNightOvertime	Bit				= 0,
	@UpdatedBy			nvarchar(100)	= NULL,
	@MaxOvrTimeHours    decimal(18, 2)  = NULL
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*) 
	FROM	P_OvertimeSettings
	WHERE	LTrim(RTrim(Upper(OTName))) = LTrim(RTrim(Upper(@OvertimeName)))
	AND		OvertimeId != @OvertimeId
	AND		OUId	   = @OUId

	if(@ValidateDuplicate = 0)
	BEGIN
		UPDATE	P_OvertimeSettings
				SET	OUId				=	@OUId, 
					OTName				=	@OvertimeName, 
					OTDesc				=	@OvertimeDesc, 
					PeriodUnit			=	@PeriodUnit, 
					PeriodLength		=	@PeriodLength, 
					ApprovalRequired	=	@ApprovalRequired, 
					DayNightOvertime	=	@DayNightOvertime,
					UpdatedBy			=	@UpdatedBy, 
					UpdatedDate			=	GETDATE(),
					MaxOvertimeHours    =   @MaxOvrTimeHours 
		WHERE		OvertimeId			=	@OvertimeId

		SELECT 1
	END
	ELSE
		SELECT -1
END
GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_UpdatePublicHolidayIsLeaveProcessById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_UpdatePublicHolidayIsLeaveProcessById]
GO

CREATE PROCEDURE [dbo].[prP_UpdatePublicHolidayIsLeaveProcessById]    
(
	@PublicHolidayId	 BigInt 
)
AS
BEGIN

	update D_PublicHolidays
	set IsLeaveProcess=1
	where PublicHolidayId=@PublicHolidayId

END

GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_UpdatePublicHolidayIsShiftProcessById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_UpdatePublicHolidayIsShiftProcessById]
GO

CREATE PROCEDURE [dbo].[prP_UpdatePublicHolidayIsShiftProcessById]    
(
	@PublicHolidayId	 BigInt 
)
AS
BEGIN

	update D_PublicHolidays
	set IsShiftProcess=1
	where PublicHolidayId=@PublicHolidayId

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_UpdateShiftCosts')
	DROP PROC prP_UpdateShiftCosts
GO

----------------------------------------------------------------------------
-- Update a single record into prP_UpdateShiftCosts
----------------------------------------------------------------------------
CREATE PROC prP_UpdateShiftCosts
	@ShiftCostId BigInt = NULL,
	@AdjustmentCost decimal(18, 5) = NULL,
	@ApprovedHours	Decimal(18,5),
	@ApprovalStatus Int,
	@UpdatedBy nvarchar(100) = NULL
	
AS

UPDATE	P_ShiftCosts 
SET		AdjustmentCost	=	@AdjustmentCost, 
		TotalCost		=	ShiftCost + @AdjustmentCost,
		ApprovedHours	=	@ApprovedHours,
		ApprovalStatus	=	@ApprovalStatus,
		UpdatedBy		=	@UpdatedBy,
		UpdatedDate		=	GETDATE()
WHERE	ShiftCostId		=	@ShiftCostId

SELECT 1

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_UpdateShiftCostsByShiftCostId')
	DROP PROC prP_UpdateShiftCostsByShiftCostId
GO

----------------------------------------------------------------------------
-- Update a single record into prP_UpdateShiftCostsByShiftCostId
----------------------------------------------------------------------------
CREATE PROC prP_UpdateShiftCostsByShiftCostId
	@ShiftCostId	BigInt,
	@PayCodeId		BigInt		= NULL,
	@StartTime		DATETIME	= NULL,
	@EndTime		DATETIME	= NULL,
	@ActualHour		INT			= NULL,
	@ApprovedHours	Decimal(18,5),
	@ApprovalStatus	Int,
	@UpdatedBy		nvarchar(100) = NULL
	
AS

	UPDATE	P_ShiftCosts
	SET		PayCodeId		=	@PayCodeId, 
			StartTime		=	@StartTime, 
			EndTime			=	@EndTime, 
			ActualHour		=	@ActualHour, 
			ApprovedHours	=	@ApprovedHours, 
			ApprovalStatus	=	@ApprovalStatus, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	ShiftCostId		=	@ShiftCostId;

	SELECT 1;

GO
/****** Object:  StoredProcedure [dbo].[prRpt_ActingIncentive]    Script Date: 27/05/2019 16:30:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_ActingIncentive]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_ActingIncentive]
GO
CREATE PROCEDURE [dbo].[prRpt_ActingIncentive](
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate	        DateTime,
	@EndDate            DateTime,
	@RoleGroup	        nVarchar(max),
	@RosterGroup		nVarchar(max)
)
AS
BEGIN
	
	/*
	SELECT C_Employee.FirstName,
		   C_Employee.EmployeeNumber,
		   C_OrganizationNode.OUName OrganizationName,
		   D_Roles.RoleGroupId,
		   S_RosterGroup.GroupName,
		   S_Shifts.ShiftStartTime,
		   S_Shifts.ShiftEndTime,
		   D_Roles.RoleId, 
		   D_Roles.RoleName PrimaryRole,
		   P_ActingIncentiveRates.IncentiveRate,
		   D_MasterCodes.CodeValue
   FROM     D_MasterCodes
			INNER Join C_Employee ON C_Employee.ActiveStatus=D_MasterCodes.ActiveStatus
			INNER Join P_ActingIncentiveRates ON P_ActingIncentiveRates.PositionId=D_MasterCodes.CodeId
	        INNER JOIN  C_OrganizationNode ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN S_Shifts ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_Roles ON D_Roles.RoleId = S_Shifts.RoleId
			INNER JOIN S_RosterGroup ON C_Employee.RosterGroupId=S_RosterGroup.RosterGroupId
   WHERE     C_OrganizationNode.OUId = @OUId 
	AND     (S_Shifts.ShiftStartTime>=@StartDate and S_Shifts.ShiftEndTime<=@EndDate)
	AND    (C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroup)) or @RosterGroup ='0')		
	AND		(D_Roles.RoleGroupId  IN (SELECT * FROM fnStringToTable(@RoleGroup)) or @RoleGroup ='0')
*/
		SELECT C_Employee.EmployeeId,C_Employee.EmployeeNumber,C_Employee.DisplayName EmployeeName ,D_Roles.RoleName  ,C_Employee.Position,D_MasterCodes.CodeId  PositionId
		FROM C_Employee	WITH (NOLOCK) 	 
		INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole=1
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
		inner join D_MasterCodes WITH (NOLOCK) on D_MasterCodes.CodeValue = C_Employee.Position and D_MasterCodes.CodeType='Position'
		WHERE C_Employee.Position is not null
		AND C_Employee.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
		AND (TerminationDate is null or TerminationDate<=@EndDate)
		and D_MasterCodes.CodeId in (36,37,38)
		order by EmployeeNumber

		select S_Shifts.EmployeeId,P_ShiftCosts.PayCodeId,Sum(ApprovedHours) ActualHour, D_PaygroupCodes.PaycodeType 
		from P_ShiftCosts WITH (NOLOCK) 
		inner join S_Shifts WITH (NOLOCK) on S_Shifts.ShiftId = P_ShiftCosts.ShiftId
		inner join D_PaygroupCodes WITH (NOLOCK) on D_PaygroupCodes.PayCodeId=P_ShiftCosts.PayCodeId  and D_PaygroupCodes.PaycodeType=8
		WHERE ( CONVERT(DATE,StartTime) >= CONVERT(DATE,@StartDate) AND CONVERT(DATE,StartTime) <= CONVERT(DATE,@EndDate))
			group by EmployeeId,P_ShiftCosts.PayCodeId,D_PaygroupCodes.PaycodeType
			order by EmployeeId

		select PositionId,IncentiveRate from P_ActingIncentiveRates WITH (NOLOCK) 
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_DailyBooking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_DailyBooking]
GO
 

Create PROCEDURE [dbo].[prRpt_DailyBooking]    
(
	@OUId				BigInt,
	@Date	Datetime,
	@RoleGroupList		nVarchar(max),
	@ShiftBandList		nVarchar(max),
	@EmpCatList nVarchar(max),
	@EquipmentTypeList nVarchar(max)
)
AS
BEGIN

--execute  prProcess_THPProcessByDay @ShiftBandList,@Date,'Temp Process'

if(len(@RoleGroupList) = 0)
	set @RoleGroupList='0'
	
	select  
	EmployeeNumber, EmployeeName,RoleName,RoleGroupId,SkillId,StartTime,DurationMins,
	ShiftBandId,ShiftStart,ShiftEnd,ProgresstionState,ActivityId,
	 HASACTIVITY,
	EquipmentId,
	EquipmentName,RoleGroupName from
	(
	select EmployeeNumber, C_Employee.DisplayName 'EmployeeName',D_Roles.RoleName,D_Roles.RoleGroupId,J_Activity.SkillId,J_Activity.StartTime,DateDiff(MINUTE,J_Activity.StartTime,J_Activity.EndTime) 'DurationMins',
	S_Shifts.ShiftBandId,S_Shifts.ActualStartTime 'ShiftStart',S_Shifts.ActualEndTime 'ShiftEnd',J_Activity.ProgresstionState,
	J_Activity.ActivityId,
	CASE
	WHEN J_Activity.WorkType =1   THEN 0 ELSE 1 END AS HASACTIVITY,
	M_Cranes.CraneId EquipmentId,
	M_Cranes.CraneNumber EquipmentName,D_rolegroup.RoleGroupName
	from C_Employee WITH (NOLOCK)
	inner join S_Shifts WITH (NOLOCK) on C_Employee.EmployeeId=S_Shifts.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId=S_Shifts.ShiftId
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 1 
	inner join M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId = J_ActivityAttributes.ScheduleId 
	inner join M_Cranes WITH (NOLOCK) on M_Cranes.CraneId = M_CraneSchedule.CraneId
	where 
	Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @Date)
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')
	
	union 

	select EmployeeNumber, C_Employee.DisplayName 'EmployeeName',D_Roles.RoleName,D_Roles.RoleGroupId,J_Activity.SkillId,J_Activity.StartTime,DateDiff(MINUTE,J_Activity.StartTime,J_Activity.EndTime) 'DurationMins',
	S_Shifts.ShiftBandId,S_Shifts.ActualStartTime 'ShiftStart',S_Shifts.ActualEndTime 'ShiftEnd',J_Activity.ProgresstionState,
	J_Activity.ActivityId,
	CASE
	WHEN J_Activity.WorkType =1   THEN 0 ELSE 1 END AS HASACTIVITY,
	M_Equipments.EquipmentId EquipmentId,
	M_Equipments.EquipmentName EquipmentName,D_rolegroup.RoleGroupName
	from C_Employee WITH (NOLOCK)
	inner join S_Shifts WITH (NOLOCK) on C_Employee.EmployeeId=S_Shifts.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId=S_Shifts.ShiftId
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 2
	inner join M_EquipmentSchedule WITH (NOLOCK) on M_EquipmentSchedule.EquipmentScheduleId = J_ActivityAttributes.ScheduleId 
	inner join M_Equipments WITH (NOLOCK) on M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
	where 
	Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @Date)
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	
	union
	select EmployeeNumber, C_Employee.DisplayName 'EmployeeName',D_Roles.RoleName,D_Roles.RoleGroupId,J_Activity.SkillId,J_Activity.StartTime,DateDiff(MINUTE,J_Activity.StartTime,J_Activity.EndTime) 'DurationMins',
	S_Shifts.ShiftBandId,S_Shifts.ActualStartTime 'ShiftStart',S_Shifts.ActualEndTime 'ShiftEnd',J_Activity.ProgresstionState,
	J_Activity.ActivityId,
	CASE
	WHEN J_Activity.WorkType =1   THEN 0 ELSE 1 END AS HASACTIVITY,
	0 EquipmentId,
	'' EquipmentName,D_rolegroup.RoleGroupName
	from C_Employee WITH (NOLOCK) 
	inner join S_Shifts WITH (NOLOCK) on C_Employee.EmployeeId=S_Shifts.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId=S_Shifts.ShiftId
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 3	
	where 
	Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @Date)
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	

	union -- GCT
	
	select EmployeeNumber, C_Employee.DisplayName 'EmployeeName',D_Roles.RoleName,D_Roles.RoleGroupId,J_Activity.SkillId,J_Activity.StartTime,DateDiff(MINUTE,J_Activity.StartTime,J_Activity.EndTime) 'DurationMins',
	S_Shifts.ShiftBandId,S_Shifts.ActualStartTime 'ShiftStart',S_Shifts.ActualEndTime 'ShiftEnd',J_Activity.ProgresstionState,
	J_Activity.ActivityId,
	CASE
	WHEN J_Activity.WorkType =1   THEN 0 ELSE 1 END AS HASACTIVITY,
	0 EquipmentId,
	'' EquipmentName,D_rolegroup.RoleGroupName
	from C_Employee WITH (NOLOCK) 
	inner join S_Shifts WITH (NOLOCK) on C_Employee.EmployeeId=S_Shifts.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId=S_Shifts.ShiftId
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 4
	--inner join M_EquipmentSchedule on M_EquipmentSchedule.EquipmentScheduleId = J_ActivityAttributes.ScheduleId 
	--inner join M_Equipments on M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
	where 
	Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @Date)
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	
	union
	select EmployeeNumber, C_Employee.DisplayName 'EmployeeName',D_Roles.RoleName,D_Roles.RoleGroupId,J_Activity.SkillId,J_Activity.StartTime,DateDiff(MINUTE,J_Activity.StartTime,J_Activity.EndTime) 'DurationMins',
	S_Shifts.ShiftBandId,S_Shifts.ActualStartTime 'ShiftStart',S_Shifts.ActualEndTime 'ShiftEnd',J_Activity.ProgresstionState,
	J_Activity.ActivityId,
	CASE
	WHEN J_Activity.WorkType =1   THEN 0 ELSE 1 END AS HASACTIVITY,
	0 EquipmentId,
	'' EquipmentName,D_rolegroup.RoleGroupName
	from C_Employee WITH (NOLOCK) 
	inner join S_Shifts WITH (NOLOCK) on C_Employee.EmployeeId=S_Shifts.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join J_Activity WITH (NOLOCK) on J_Activity.ShiftId=S_Shifts.ShiftId
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 3	
	where 
	Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @Date)
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	

	) re
	order by RoleGroupId,EmployeeNumber,StartTime
	-- Crane Schedule
	

	-- All the sckill
	select D_Skill.SkillId, skill SkillName,ColorCode Color from D_Skill WITH (NOLOCK) 
	inner join D_SkillOU WITH (NOLOCK) on D_Skill.SkillId= D_SkillOU.SkillId
	where D_SkillOU.OUId=@OUId

	-- Equoment Schedule by date range
	select J_ActivityAttributes.ActivityId,M_EquipmentSchedule.EquipmentId,M_Equipments.EquipmentName 
	from M_EquipmentSchedule WITH (NOLOCK) 
	inner join J_ActivityAttributes WITH (NOLOCK) on J_ActivityAttributes.ScheduleId=M_EquipmentSchedule.EquipmentScheduleId and J_ActivityAttributes.AttributeId=1
	inner join M_Equipments WITH (NOLOCK) on M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
	-- Filter by Date Range
END






GO


/****** Object:  StoredProcedure [dbo].[prRpt_EmployeeDetails]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_EmployeeDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_EmployeeDetails]
GO

/****** Object:  StoredProcedure [dbo].[prRpt_EmployeeDetails]    Script Date: 22/06/2018 2:23:21 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prRpt_EmployeeDetails]    
(
	@RosterGroupList	nVarchar(max),
	@RoleGroupList		nVarchar(max),
	@LastUpdatedDate	DateTime,
	--@OUId				BigInt
	@FilteredOrgUnits	nVarchar(max)	
)
AS
BEGIN

	if len(@RosterGroupList) =0
		set @RosterGroupList='0'

	if len(@RoleGroupList) =0
		set @RoleGroupList='0'

	SELECT  EmployeeNumber, 
			FirstName ,
			LastName, 
			D_Roles.RoleId PrimaryRoleId, 
			D_Roles.RoleName PrimaryRole, 
			S_ScheduleRules.ScheduleRuleId, 
			S_ScheduleRules.Name ScheduleRule,
			C_Employee.HiredDate,
			C_Employee.DateOfBirth,
			C_Employee.MobilePhone,
			C_Employee.EmailAddress,
			S_RosterGroup.GroupName RosterGroupName,
			S_RosterGroup.RosterGroupId,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			C_OrganizationNode.OUName OrganizationName,
			D_PayGroup.PayGroupCode PayGroup,C_Employee.UpdatedDate
	FROM	C_Employee  WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON C_Employee.RosterGroupId = S_RosterGroup.RosterGroupId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_ROLES.RoleId AND D_Roles.ActiveStatus = 1 
			LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON C_Employee.ScheduleRuleId = S_ScheduleRules.ScheduleRuleId
			left outer join D_PayGroup WITH (NOLOCK) on D_PayGroup.PayGroupId = C_Employee.PayGroupId
	WHERE	C_Employee.ActiveStatus = 1
	AND		C_OrganizationNode.ActiveStatus = 1
	AND		C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOrgUnits))
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupList)) or @RosterGroupList ='0')
		
	AND		(D_RoleGroup.RoleGroupId  IN (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList ='0')
	AND		(C_Employee.UpdatedDate <= Convert(Date,@LastUpdatedDate) or C_Employee.UpdatedDate is null)
	ORDER BY 			S_RosterGroup.RosterGroupId,
			D_RoleGroup.RoleGroupId,C_Employee.EmployeeNumber


END



GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_EquipmentBooking]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_EquipmentBooking]
GO
 

CREATE  PROCEDURE [dbo].[prRpt_EquipmentBooking]    
(
	@OUId				BigInt,
	@StartDate	Datetime,
	@EndDate	Datetime,
	@RoleGroupList		nVarchar(max),
	@ShiftBandList		nVarchar(max),
	@EmpCatList nVarchar(max),
	@EquipmentTypeList nVarchar(max)
)
AS
BEGIN

if(len(@RoleGroupList) = 0)
	set @RoleGroupList='0'

if(len(@EquipmentTypeList) = 0)
	set @EquipmentTypeList='-1'	
	--print @EndDate

	select M_Cranes.CraneNumber EquipmentName,'' EmployeeName,0 RoleGroupId,0 SkillId, M_CraneSchedule.StartDate StartTime,M_CraneSchedule.EndDate EndTime,
	 M_CraneSchedule.StartDate ShiftStart,M_CraneSchedule.EndDate ShiftEnd,
	M_Cranes.CraneId EquipmentId,
	3 WorkType,M_VesselSchedule.VesselName ,M_VesselSchedule.VisitId,
	DateDiff(MINUTE,M_CraneSchedule.StartDate,M_CraneSchedule.EndDate) 'DurationMins',
	0  EquipmentTypeId,
	'Crane' EquipmentType
	from M_CraneSchedule WITH (NOLOCK)
	inner join M_Cranes WITH (NOLOCK) on M_Cranes.CraneId = M_CraneSchedule.CraneId
	inner join M_VesselSchedule WITH (NOLOCK) on M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
	where 	
	@EndDate >= M_CraneSchedule.StartDate AND M_CraneSchedule.EndDate >= @StartDate
	and (@EquipmentTypeList=0 or @EquipmentTypeList='-1')
	
	union

	select M_equipments.EquipmentName EquipmentName,'' EmployeeName,0 RoleGroupId,0 SkillId, 
	M_equipmentSchedule.StartDate StartTime,M_equipmentSchedule.EndDate EndTime,
	 M_equipmentSchedule.StartDate ShiftStart,M_equipmentSchedule.EndDate ShiftEnd,
	M_equipments.EquipmentId EquipmentId,
	2 WorkType,'' VesselName ,'' VisitId,
	DateDiff(MINUTE,M_equipmentSchedule.StartDate,M_equipmentSchedule.EndDate) 'DurationMins',
	M_EquipmentType.EquipmentTypeId,
	M_EquipmentType.EquipmentType
	from M_equipmentSchedule WITH (NOLOCK)
	inner join M_equipments WITH (NOLOCK) on M_equipments.EquipmentId = M_equipmentSchedule.EquipmentId
	--inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId = M_CraneSchedule.VesselScheduleId
	and (M_equipments.EquipmentTypeId in (SELECT * FROM fnStringToTable(@EquipmentTypeList)) or @EquipmentTypeList='-1')
	inner join M_EquipmentType WITH (NOLOCK) on M_EquipmentType.EquipmentTypeId = M_equipments.EquipmentTypeId
	where 	
	@EndDate >= M_equipmentSchedule.StartDate AND M_equipmentSchedule.EndDate >= @StartDate
	order by EquipmentTypeId,EquipmentId

	-- Crane Schedule
	

	-- All the sckill
	select D_Skill.SkillId, skill SkillName,ColorCode Color from D_Skill WITH (NOLOCK)
	inner join D_SkillOU WITH (NOLOCK) on D_Skill.SkillId= D_SkillOU.SkillId
	where D_SkillOU.OUId=@OUId	
	
END



go



/****** Object:  StoredProcedure [dbo].[prRD_HRAttendanceDetails]    Script Date: 27/05/2019 16:30:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_HRAttendanceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_HRAttendanceDetails]
GO

CREATE PROCEDURE    [dbo].[prRpt_HRAttendanceDetails]

(
	@FilteredOUList		nVarchar(max),
	--@OUId				BigInt,
	@StartDate	        DateTime,
	@EndDate            DateTime,
	@EmployeeNumber     nvarchar(50),
	@ShiftBand			nVarchar(max)

)
	
AS
BEGIN
	If (Len(@ShiftBand) = 0) SET @ShiftBand = '0'

	SELECT  C_Employee.DisplayName FirstName,
			C_Employee.EmployeeNumber,
			C_Employee.RosterGroupId,
			D_Roles.RoleGroupId,
			C_OrganizationNode.OUName OrganizationName,
			S_Shifts.ShiftId,
		--	S_Shifts.ShiftStartTime ShiftStart,
			convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)) ShiftStart,
			--S_Shifts.ShiftEndTime ShiftEnd,
			convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108)) ShiftEnd,
			S_Shifts.InTime ClockIn,
			S_Shifts.OutTime ClockOut,
			S_Shifts.ShiftBandId,
		case
				when S_Shifts.InStatus  = 1 then 'OnTime'
				when S_Shifts.InStatus  = 2 then 'EarlyIn'
				when S_Shifts.InStatus  = 3 then 'LateIn'
				when S_Shifts.InStatus  = 4 then 'EarlyOut'
				when S_Shifts.InStatus  = 5 then 'LateOut'
				when S_Shifts.InStatus  = 6 then 'NoClocking'
				when S_Shifts.InStatus  = 7 then 'NoClockIn'
				when S_Shifts.InStatus  = 8 then 'NoClockOut'
				when S_Shifts.InStatus  = -1 then 'NoActionRequired'
				when S_Shifts.InStatus  = 9 then 'Manual'
			else convert(varchar(10),S_Shifts.InStatus )
			end InStatus,
			--S_Shifts.InStatus,
			case
				when S_Shifts.OutStatus  = 1 then 'OnTime'
				when S_Shifts.OutStatus  = 2 then 'EarlyIn'
				when S_Shifts.OutStatus  = 3 then 'LateIn'
				when S_Shifts.OutStatus  = 4 then 'EarlyOut'
				when S_Shifts.OutStatus  = 5 then 'LateOut'
				when S_Shifts.OutStatus  = 6 then 'NoClocking'
				when S_Shifts.OutStatus  = 7 then 'NoClockIn'
				when S_Shifts.OutStatus  = 8 then 'NoClockOut'
				when S_Shifts.OutStatus  = -1 then 'NoActionRequired'
				when S_Shifts.OutStatus  = 9 then 'Manual'
			else convert(varchar(10),S_Shifts.OutStatus )
			end OutStatus,
			--S_Shifts.OutStatus ,,
			D_Roles.RoleId PrimaryRoleId, 
			D_Roles.RoleName PrimaryRole,
			D_ShiftBand.ShiftBandId,
			D_ShiftBand.ShiftBandName ,
		   -- DATEDIFF(HOUR,ShiftEndTime,ShiftStartTime) As PlannedHours,
		   DATEDIFF(hour,		   
		   convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)),
		   convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108))
		   ) PlannedHours,
			--DATEDIFF(HOUR,ShiftStartTime,ShiftEndTime) As Hours,
			DATEDIFF(HOUR,InTime,OutTime) As Hours,
			isnull( DATEDIFF(hour,		   
		   convert(datetime, CONVERT(varchar,s_shiftexceptions.StartTime, 101) + ' ' +  CONVERT(varchar, s_shiftexceptions.StartTime, 108)),
		   convert(datetime,CONVERT(varchar,s_shiftexceptions.EndTime, 101) + ' ' +  CONVERT(varchar, s_shiftexceptions.EndTime, 108))
		   ),0) ExceptionHours,
		   D_ExceptionCodes.ExcpetionCodeName ExceptionCodeDescription
	     --    DATEDIFF(hour,		   
		 --  convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)),
		--   convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108))
		--   )			
		--	- DATEDIFF(HOUR,InTime,OutTime) As Deviation			
	 FROM   C_Employee WITH (NOLOCK)
			inner JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
	        INNER JOIN  C_OrganizationNode WITH (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId			
			inner JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
			inner JOIN D_ShiftBand WITH (NOLOCK) ON  S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			left outer join s_shiftexceptions WITH (NOLOCK) on s_shiftexceptions.shiftid=S_Shifts.ShiftId
			LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
			LEFT OUTER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	WHERE   C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND     (D_ShiftBand.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand)) or @ShiftBand='0')
	AND     (convert(date,S_Shifts.ShiftStartTime)>=convert(date,@StartDate) and convert(date,S_Shifts.ShiftEndTime)<=convert(date,@EndDate))
	AND     C_Employee.EmployeeNumber=@EmployeeNumber	
	and (S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId  or  S_Shifts.CombinationShiftId is  null)
	UNION ALL
	select	C_Employee.DisplayName FirstName,
			C_Employee.EmployeeNumber,
			C_Employee.RosterGroupId,
			D_Roles.RoleGroupId,
			C_OrganizationNode.OUName OrganizationName,
			0 'ShiftId',
			S_EmployeeLeaves.FromDate ShiftStart,
			S_EmployeeLeaves.FromDate ShiftEnd,
			NULL ClockIn,
			NULL ClockOut,
			0 ShiftBandId,
			'' InStatus,
			'' OutStatus,
			C_EmployeeRoles.RoleId PrimaryRoleId,
			D_Roles.RoleName PrimaryRole,
			0 ShiftBandId,
			'' ShiftBandName,
			S_EmployeeLeaves.LeaveHours PlannedHours,
			S_EmployeeLeaves.LeaveHours [Hours],
			0 ExceptionHours,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeDescription
	from	S_EmployeeLeaves WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId And C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHere	C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	And		C_Employee.EmployeeNumber = @EmployeeNumber
	And		Convert(Date,FromDate) >= Convert(Date,@StartDate) 
	And		Convert(Date,FromDate) <= Convert(Date,@EndDate)
	And ISNULL(S_EmployeeLeaves.ShiftId,0) = 0

	ORDER BY ShiftStart
	--C_OrganizationNode.OUName,EmployeeNumber,
END

	
GO

/****** Object:  StoredProcedure [dbo].[prRD_HRAttendanceDetails]    Script Date: 27/05/2019 16:30:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_HRReportDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_HRReportDetails]
GO

CREATE PROCEDURE [dbo].[prRpt_HRReportDetails]
(
	@FilteredOUList		nVarchar(max),
	--@OUId				BigInt,
	@StartDate	        DateTime,
	@EndDate            DateTime,
	@ShiftBand		    nVarchar(max),
	@RoleGroup	        nVarchar(max),
	@RosterGroup		nVarchar(max)
)
	
AS
BEGIN
	
if len(@RoleGroup) =0
		set @RoleGroup='0'

	if len(@RosterGroup) =0
		set @RosterGroup='0'

		if len(@ShiftBand) =0
		set @ShiftBand='0'

	SELECT  C_Employee.DisplayName FirstName,
			C_Employee.EmployeeNumber,
			C_Employee.RosterGroupId,
			D_Roles.RoleGroupId,
			C_OrganizationNode.OUName OrganizationName,
			S_Shifts.ShiftId,
		--	S_Shifts.ShiftStartTime ShiftStart,
			convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)) ShiftStart,
			--S_Shifts.ShiftEndTime ShiftEnd,
			convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108)) ShiftEnd,
			S_Shifts.InTime ClockIn,
			S_Shifts.OutTime ClockOut,
			S_Shifts.ShiftBandId,
		case
				when S_Shifts.InStatus  = 1 then 'OnTime'
				when S_Shifts.InStatus  = 2 then 'EarlyIn'
				when S_Shifts.InStatus  = 3 then 'LateIn'
				when S_Shifts.InStatus  = 4 then 'EarlyOut'
				when S_Shifts.InStatus  = 5 then 'LateOut'
				when S_Shifts.InStatus  = 6 then 'NoClocking'
				when S_Shifts.InStatus  = 7 then 'NoClockIn'
				when S_Shifts.InStatus  = 8 then 'NoClockOut'
				when S_Shifts.InStatus  = -1 then 'NoActionRequired'
				when S_Shifts.InStatus  = 9 then 'Manual'
			else convert(varchar(10),S_Shifts.InStatus )
			end InStatus,
			--S_Shifts.InStatus,
			case
				when S_Shifts.OutStatus  = 1 then 'OnTime'
				when S_Shifts.OutStatus  = 2 then 'EarlyIn'
				when S_Shifts.OutStatus  = 3 then 'LateIn'
				when S_Shifts.OutStatus  = 4 then 'EarlyOut'
				when S_Shifts.OutStatus  = 5 then 'LateOut'
				when S_Shifts.OutStatus  = 6 then 'NoClocking'
				when S_Shifts.OutStatus  = 7 then 'NoClockIn'
				when S_Shifts.OutStatus  = 8 then 'NoClockOut'
				when S_Shifts.OutStatus  = -1 then 'NoActionRequired'
				when S_Shifts.OutStatus  = 9 then 'Manual'
			else convert(varchar(10),S_Shifts.OutStatus )
			end OutStatus,
			--S_Shifts.OutStatus ,,
			D_Roles.RoleId PrimaryRoleId, 
			D_Roles.RoleName PrimaryRole,
			D_ShiftBand.ShiftBandId,
			D_ShiftBand.ShiftBandName ,
		   -- DATEDIFF(HOUR,ShiftEndTime,ShiftStartTime) As PlannedHours,
		   DATEDIFF(hour,		   
		   convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)),
		   convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108))
		   ) PlannedHours,
			--DATEDIFF(HOUR,ShiftStartTime,ShiftEndTime) As Hours,
			DATEDIFF(HOUR,InTime,OutTime) As Hours,
			isnull( DATEDIFF(hour,		   
		   convert(datetime, CONVERT(varchar,s_shiftexceptions.StartTime, 101) + ' ' +  CONVERT(varchar, s_shiftexceptions.StartTime, 108)),
		   convert(datetime,CONVERT(varchar,s_shiftexceptions.EndTime, 101) + ' ' +  CONVERT(varchar, s_shiftexceptions.EndTime, 108))
		   ),0) ExceptionHours,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeDescription
	     --    DATEDIFF(hour,		   
		 --  convert(datetime, CONVERT(varchar,S_Shifts.ShiftStartTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.StartTime, 108)),
		--   convert(datetime,CONVERT(varchar,S_Shifts.ShiftEndTime, 101) + ' ' +  CONVERT(varchar, D_ShiftBand.EndTime, 108))
		--   )			
		--	- DATEDIFF(HOUR,InTime,OutTime) As Deviation		
	FROM   C_Employee WITH (NOLOCK)
	inner JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
	        INNER JOIN  C_OrganizationNode WITH (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId			
			inner JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
			inner JOIN D_ShiftBand WITH (NOLOCK) ON  S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			left outer join s_shiftexceptions WITH (NOLOCK) on s_shiftexceptions.shiftid=S_Shifts.ShiftId
			LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
			LEFT OUTER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	WHERE     C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND     (D_ShiftBand.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand)) or @ShiftBand='0')
	AND     (convert(date,S_Shifts.ShiftStartTime)>=convert(date,@StartDate) and convert(date,S_Shifts.ShiftStartTime)<=convert(date,@EndDate))
	AND    (C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroup)) or @RosterGroup ='0')		
	AND		(D_Roles.RoleGroupId  IN (SELECT * FROM fnStringToTable(@RoleGroup)) or @RoleGroup ='0')	
	and (S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId  or  S_Shifts.CombinationShiftId is  null)
	ORDER BY C_OrganizationNode.OUName,EmployeeNumber, Convert(Date,S_Shifts.ShiftStartTime)

	END
	

	
	GO
	
	

	
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_IndividualLeave')
	DROP PROC prRpt_IndividualLeave
GO

CREATE PROCEDURE [dbo].[prRpt_IndividualLeave]
(
	--@OUID                  BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate			   datetime,
	@EndDate			   datetime,
	@EmployeeNumber        nvarchar(50)
)
	
AS
BEGIN
	SELECT C_Employee.EmployeeNumber,C_Employee.DisplayName LastName,D_EmploymentBasis.EmploymentBasisCode LabourClassName,C_OrganizationNode.OUName Department,L_Leaves.LeaveStart From_Date,L_Leaves.LeaveEnd To_Date,L_Leaves.NoOfDays no_of_days,C_Employee.HiredDate CompanyHireDate,
	(CASE WHEN D_ExceptionCodes.ExceptionCodeId =1
	THEN
	count(D_ExceptionCodes.ExceptionCodeId)END)as Al_Days_Entitle,
	(CASE WHEN D_ExceptionCodes.ExceptionCodeId =2
	THEN
	count(D_ExceptionCodes.ExceptionCodeId)END)as mc_days_entitle
	FROM  L_Leaves WITH (NOLOCK)	 
inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
inner join D_EmploymentBasis WITH (NOLOCK) on D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
WHERE D_ExceptionCodes.ExceptionCodeId in (1,2)and
(L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
and  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
and C_Employee.IsTerminated=0
and C_Employee.EmployeeNumber=@EmployeeNumber
Group By C_Employee.EmployeeNumber,C_Employee.DisplayName,C_OrganizationNode.OUName,L_Leaves.LeaveStart,L_Leaves.LeaveEnd,L_Leaves.NoOfDays,D_EmploymentBasis.EmploymentBasisCode,C_Employee.HiredDate,D_ExceptionCodes.ExceptionCodeId

END
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_LeaveHistory')
	DROP PROC prRpt_LeaveHistory
GO
/****** Object:  StoredProcedure [dbo].[prRpt_LeaveHistory]    Script Date: 7/15/2019 11:40:59 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prRpt_LeaveHistory]
(
	@StartDate			datetime,
	@EndDate			datetime,
	@FilteredOUList		nVarchar(max)
)
AS
BEGIN
	select AppliedDate Trans_Date,D_ExceptionCodes.ExcpetionCodeName LeaveCode,L_Leaves.LeaveStart From_Date,L_Leaves.LeaveEnd To_Date,W_ApprovalStatus.ApprovalStatus,ApprovedBy ApproverName,EmployeeNumber EmpNo,C_Employee.DisplayName EmployeeName,D_ExceptionCodes.ExceptionCodeDesc LeaveName,	C_OrganizationNode.OUName OrganizationName
	from L_Leaves WITH (NOLOCK)	
	inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
	INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
	inner join W_ApprovalStatus WITH (NOLOCK) on W_ApprovalStatus.ApprovalStatusId = L_Leaves.ApprovalStatusId
	where
	W_ApprovalStatus.ApprovalStatusId in (1,2,3)
	and (L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
	and  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	and C_Employee.IsTerminated=0
	END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_LeaveProfile')
	DROP PROC prRpt_LeaveProfile
GO
/****** Object:  StoredProcedure [dbo].[prRpt_LeaveProfile]    Script Date: 7/22/2019 5:15:04 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prRpt_LeaveProfile](
	@LeaveYear			int,
	@LeaveType	        bigint,
	@FilteredOUList		nVarchar(max)
)
AS
BEGIN

select EmployeeNumber EMPNO,DisplayName LASTNAME,ExcpetionCodeName LeaveCode,L_EmployeeLeaveProfiles.EntitlementDays DAYS_ENTITLE,CEILING(L_EmployeeLeaveProfiles.EarnedDays) DAYS_EARNED,L_EmployeeLeaveProfiles.UsedDays ,CEILING(L_EmployeeLeaveProfiles.BalanceDays) DAYS_BALANCE,L_EmployeeLeaveProfiles.CarryForwardDays PendingLeaves,
ExceptionCodeDesc LeaveName,L_EmployeeLeaveProfiles.LeaveYear,C_OrganizationNode.OUName OrganizationName,
isnull((NULLIF(L_EmployeeLeaveProfiles.BalanceDays,0)/NULLIF(L_EmployeeLeaveProfiles.UsedDays,0)),0)*100 Utilization 
from L_EmployeeLeaveProfiles WITH (NOLOCK)
inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId= L_EmployeeLeaveProfiles.EmployeeId
INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_EmployeeLeaveProfiles.ExceptionId
INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
where 
 L_EmployeeLeaveProfiles.LeaveYear=@LeaveYear
 and D_ExceptionCodes.ExceptionCodeId=@LeaveType
 and C_Employee.IsTerminated=0
 AND C_OrganizationNode.OUID IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
 And Exists (SELECT EMPLOYEEID FROM C_EmployeeLeaveProfile WITH (NOLOCK))
 Group By D_ExceptionCodes.ExceptionCodeDesc,C_Employee.EmployeeNumber,C_Employee.DisplayName,D_ExceptionCodes.ExcpetionCodeName,L_EmployeeLeaveProfiles.EntitlementDays,L_EmployeeLeaveProfiles.EarnedDays,L_EmployeeLeaveProfiles.UsedDays,L_EmployeeLeaveProfiles.BalanceDays,L_EmployeeLeaveProfiles.LeaveYear,C_OrganizationNode.OUName,L_EmployeeLeaveProfiles.CarryForwardDays

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_MonthlyLeave')
	DROP PROC prRpt_MonthlyLeave
GO
CREATE PROCEDURE [dbo].[prRpt_MonthlyLeave]
(
	--@OUId               BigInt,
	@FilteredOUList		nVarchar(max),
	@LeaveType	        nVarchar(max),
	@Month              int,
	@Year		     	int
)
AS
BEGIN

	SELECT C_OrganizationNode.OUName orgNodeName,D_ExceptionCodes.ExcpetionCodeName LeaveName,L_Leaves.NoOfDays noOfDays,count(L_Leaves.NoOfDays) Total,L_EmployeeLeaveProfiles.LeaveYear,(L_Leaves.NoOfDays/count(D_ExceptionCodes.ExceptionCodeId))*100 PercentLeave
	FROM  L_Leaves	WITH (NOLOCK) 
			inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
		inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
		inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
		inner join L_EmployeeLeaveProfiles WITH (NOLOCK) on L_EmployeeLeaveProfiles.EmployeeId=C_Employee.EmployeeId 
	WHERE C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
		and C_Employee.IsTerminated=0
		and D_ExceptionCodes.ExceptionCodeId IN (SELECT * FROM fnStringToTable(@LeaveType)) 
		and L_EmployeeLeaveProfiles.LeaveYear=@Year
		and( MONTH(L_Leaves.LeaveStart)=@Month or MONTH(L_Leaves.LeaveEnd)=@Month)
	GROUP BY C_OrganizationNode.OUName,D_ExceptionCodes.ExcpetionCodeName,NoOfDays,LeaveYear

END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_OvertimeSummary')
	DROP PROC prRpt_OvertimeSummary
GO


create PROCEDURE [dbo].[prRpt_OvertimeSummary]    
(
	@FilteredOUList		nVarchar(max),
	--@OUId				BigInt,
	@StartDate	Datetime,
	@EndDate	Datetime

)
AS
BEGIN
		/*	
		SELECT C_Employee.EmployeeId,C_Employee.EmployeeNumber,C_Employee.DisplayName EmployeeName ,D_Roles.RoleName,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 2 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT1,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 2 THEN 'Day' ELSE '0' END Reg_OT1_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 3 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT2,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 3 THEN 'Night' ELSE '0' END Reg_OT2_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 4 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT3,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 4 THEN 'Public' ELSE '0' END Reg_OT3_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 9 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT4,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 9 THEN 'OnCall' ELSE '0' END Reg_OT4_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 5 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT5,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 5 THEN 'Ramadan Day' ELSE '0' END Reg_OT5_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 6 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT6,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 6 THEN 'Ramadan Night' ELSE '0' END Reg_OT6_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 7 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT7,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 7 THEN 'Ramadan Public' ELSE '0' END Reg_OT7_Desc,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 8 THEN SUM(P_ShiftCosts.ShiftCost) ELSE 0 END Reg_OT8,
		CASE 		WHEN P_ShiftCosts.PayCodeId = 8 THEN 'Ramadan OnCall' ELSE '0' END Reg_OT8_Desc
		FROM S_Shifts
		INNER JOIN P_ShiftCosts ON P_ShiftCosts.ShiftId=S_Shifts.ShiftId
		INNER JOIN C_Employee ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN C_EmployeeRoles ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole=1
		INNER JOIN D_Roles ON D_Roles.RoleId = C_EmployeeRoles.RoleId
		WHERE ( CONVERT(DATE,ShiftStartTime) >= CONVERT(DATE,@StartDate) AND CONVERT(DATE,ShiftStartTime) <= CONVERT(DATE,@EndDate))
		AND S_Shifts.OUId=@OUId
		GROUP BY C_Employee.EmployeeId,C_Employee.EmployeeNumber,C_Employee.DisplayName ,D_Roles.RoleName,P_ShiftCosts.PayCodeId 
*/	
		SELECT	C_Employee.EmployeeId,C_Employee.EmployeeNumber,C_Employee.DisplayName EmployeeName , D_Roles.RoleName,
				C_OrganizationNode.OUName		
		FROM C_Employee	WITH (NOLOCK) 	
		INNER JOIN C_EmployeeRoles WITH (NOLOCK)  ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole=1
		INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
		INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
		WHERE
		-- C_Employee.OvertimeId is not null AND
		 C_Employee.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
		and (TerminationDate is null or TerminationDate<=@EndDate)		
		order by EmployeeNumber



		select S_Shifts.EmployeeId,P_ShiftCosts.PayCodeId,Sum(ApprovedHours) ActualHour, D_PaygroupCodes.PaycodeType 
		from P_ShiftCosts WITH (NOLOCK) 
		inner join S_Shifts WITH (NOLOCK) on S_Shifts.ShiftId = P_ShiftCosts.ShiftId
		inner join D_PaygroupCodes WITH (NOLOCK) on D_PaygroupCodes.PayCodeId=P_ShiftCosts.PayCodeId -- and D_PaygroupCodes.PaycodeType=8
		WHERE ( CONVERT(DATE,S_Shifts.ActualStartTime) >= CONVERT(DATE,@StartDate) AND CONVERT(DATE,S_Shifts.ActualStartTime) <= CONVERT(DATE,@EndDate))
		AND		P_ShiftCosts.ApprovalStatus = 1
		--	WHERE ( CONVERT(DATE,StartTime) >= CONVERT(DATE,'2019-09-15') AND CONVERT(DATE,ShiftStartTime) <= CONVERT(DATE,'2019-09-20'))
		and S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
		And ActualHour >= 0 
			group by EmployeeId,P_ShiftCosts.PayCodeId,D_PaygroupCodes.PaycodeType
			order by EmployeeId



		/*
		 Normal = 1,
            Overtime = 2,
            PublicHoliday = 3,
            PremiumOverTime = 4,
            Ramadan = 5,
            Leave =6,
            NightOvertime=7,
            ActingIncentive=8,
			*/

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_ShiftDetails')
	DROP PROC prRpt_ShiftDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prRpt_ShiftDetails]    
(
	@RoleGroup   	    nVarchar(max),
	@ShiftBand		    nVarchar(max),
	@ShiftDate	        DateTime,
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),	
	@RosterGroup   	    nVarchar(max),
	@EmploymentBasis 	nVarchar(max)
)

AS
BEGIN

if(len(@RoleGroup) = 0)
	set @RoleGroup='0'
	
	if(len(@RosterGroup) = 0)
	set @RosterGroup='0'

	if(len(@EmploymentBasis) = 0)
	set @EmploymentBasis='0'

	SELECT 	Displayname 'FirstName' ,
			LastName, 
			EmployeeNumber,
			D_Roles.RoleId,
			--D_Roles.RoleName PrimaryCompetency,
			S_Shifts.ShiftId,
			S_Shifts.ShiftStartTime ShiftStart,
			S_Shifts.ShiftEndTime ShiftEnd,
			S_Shifts.ActualStartTime ClockIn,
			S_Shifts.ActualEndTime ClockOut,
			S_Shifts.ShiftBandId,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			C_OrganizationNode.OUName OrganizationName,
			D_ShiftBand.ShiftBandId,
			D_ShiftBand.ShiftBandName ,
			(select top 1 Skill from J_Activity  WITH (NOLOCK) 
			inner join D_Skill WITH (NOLOCK)  on D_Skill.SkillId= J_Activity.SkillId where  shiftid = S_Shifts.ShiftId order by J_Activity.StartTime ) PrimaryCompetency
	FROM    C_Employee WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
			LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON  D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			LEFT OUTER JOIN D_ShiftBand WITH (NOLOCK) ON  S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	--WHERE  	C_OrganizationNode.OUId = @OUId
	WHERE	C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	and (D_RoleGroup.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroup)) or @RoleGroup='0')
	AND     D_ShiftBand.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))	
	AND     Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date,@ShiftDate)
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroup)) or @RosterGroup='0')
	AND		(C_Employee.EmploymentBasisId IN (SELECT * FROM fnStringToTable(@EmploymentBasis)) or @EmploymentBasis='0')
	AND		S_Shifts.ShiftId not in (select shiftid from s_shiftexceptions WITH (NOLOCK)  where exceptioncodeid = 3)
	ORDER BY D_RoleGroup.RoleGroupId


END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_StandByEmployee')
	DROP PROC prRpt_StandByEmployee
GO

Create PROCEDURE [dbo].[prRpt_StandByEmployee]    
(
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate	Datetime,
	@RoleGroupList		nVarchar(max),
	@ShiftBandList nVarchar(max)
	
)
AS
BEGIN

if(len(@RoleGroupList) = 0)
	set @RoleGroupList='0'

if(len(@ShiftBandList) = 0)
	set @ShiftBandList='0'

	select EmployeeNumber,DisplayName 'EmployeeName',D_Roles.RoleName,S_Shifts.ShiftStartTime,S_Shifts.InTime 'ClockIn',D_RoleGroup.RoleGroupId,
		   D_RoleGroup.RoleGroupName, C_OrganizationNode.OUName OrganizationName,D_ShiftBand.ShiftBandId,D_ShiftBand.ShiftBandName 
	from C_Employee WITH (NOLOCK)
	inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	inner join S_Shifts WITH (NOLOCK) on S_Shifts.EmployeeId = C_Employee.EmployeeId
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join D_ShiftBand WITH (NOLOCK) ON  S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	where Convert(date,S_Shifts.ShiftStartTime) =  CONVERT(date, @StartDate)
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	
	and S_Shifts.ShiftBandId in (SELECT * FROM fnStringToTable(@ShiftBandList))
	and C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	
END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_THPListingReport')
	DROP PROC prRpt_THPListingReport
GO


Create PROCEDURE [dbo].[prRpt_THPListingReport]    
(
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),
	@Date	Datetime,
	@RoleGroupList		nVarchar(max)
	
	
)
AS
BEGIN

if(len(@RoleGroupList) = 0)
	set @RoleGroupList='0'


	select C_Employee.EmployeeId,EmployeeNumber,DisplayName 'EmployeeName',D_Roles.RoleName,
	sum(S_THPEmployeeDetails.ActivityCounter) ActivityCounter,Sum(S_THPEmployeeDetails.ShiftCounter) ShiftCounter,sum(S_THPEmployeeDetails.NormalHour) NormalHour,sum(S_THPEmployeeDetails.OTHour) OTHour,sum(S_THPEmployeeDetails.LeaveCounter) LeaveHour 
	from C_Employee WITH (NOLOCK)
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId
	inner join D_rolegroup WITH (NOLOCK) on D_rolegroup.RoleGroupId = D_Roles.RoleGroupId
	inner join S_THPEmployeeDetails WITH (NOLOCK) on S_THPEmployeeDetails.EmployeeId = C_Employee.EmployeeId
--	inner join S_THPEmployeePeriods on S_THPEmployeePeriods.EmployeeId=C_Employee.EmployeeId
	inner join S_THPEmployeePeriods WITH (NOLOCK) on S_THPEmployeeDetails.THPPeriodId = S_THPEmployeePeriods.THPPeriodId
	where Convert(date,S_THPEmployeePeriods.PeriodStart) <=  CONVERT(date, @Date) and Convert(date,S_THPEmployeePeriods.PeriodEnd) >=  CONVERT(date, @Date)
	and (D_Roles.RoleGroupId in (SELECT * FROM fnStringToTable(@RoleGroupList)) or @RoleGroupList='0')	
	and C_Employee.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	group by EmployeeNumber,DisplayName,RoleName,C_Employee.EmployeeId
	
	
END



GO

/****** Object:  StoredProcedure [dbo].[prRD_HRAttendanceDetails]    Script Date: 27/05/2019 16:30:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_TimeSheetDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_TimeSheetDetails]
GO
CREATE PROCEDURE  [dbo].[prRpt_TimeSheetDetails](
@OUId				BigInt,
@StartDate	        DateTime,
@EndDate            DateTime,
@EmployeeNumber     nvarchar(50)
)

AS
BEGIN

SELECT  C_Employee.DisplayName FirstName,
	    C_Employee.EmployeeNumber,
		D_Roles.RoleId PrimaryRoleId, 
		D_Roles.RoleName PrimaryRole,
		D_ShiftBand.ShiftBandId,
		D_ShiftBand.ShiftBandName ,
		S_Shifts.InTime ClockIn,
		S_Shifts.OutTime ClockOut,
		C_OrganizationNode.OUName OrganizationName,
		S_Shifts.InStatus,
		S_Shifts.OutStatus ,
		D_ExceptionCodes.ExcpetionCodeName LeaveType,
		C_Employee.RosterGroupId,
		D_Roles.RoleGroupId,
		S_RosterGroup.GroupName RosterGroup,
		S_Shifts.ShiftStartTime ShiftStart,
		S_Shifts.ShiftEndTime ShiftEnd,
		DATEDIFF(HOUR,ShiftStartTime,ShiftEndTime)As WorkedHours,
		DATEDIFF(DAY,ShiftStartTime,ShiftEndTime)As WorkedDay
		--(CASE 
		  --      WHEN D_ExceptionCodes.ExceptionCodeId=1 THEN count(D_ExceptionCodes.ExceptionCodeId)END )as ALCount, 
		--(CASE
			--	WHEN D_ExceptionCodes.ExceptionCodeId=2 THEN count(D_ExceptionCodes.ExceptionCodeId)END)as SickCount,
		--(CASE		WHEN D_ExceptionCodes.ExceptionCodeId=5 THEN count(D_ExceptionCodes.ExceptionCodeId)
			--END) as ELCount
FROM   C_Employee WITH (NOLOCK)
			INNER JOIN L_Leaves WITH (NOLOCK) ON C_Employee.EmployeeId=L_Leaves.EmployeeId
	        INNER JOIN  C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN S_RosterGroup WITH (NOLOCK) ON C_Employee.RosterGroupId=S_RosterGroup.RosterGroupId
			INNER JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON  S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
WHERE  D_ExceptionCodes.ExceptionCodeId in (1,2,5)  
AND C_OrganizationNode.OUId = @OUId   	
	AND     (S_Shifts.ShiftStartTime>=@StartDate and S_Shifts.ShiftEndTime<=@EndDate)
	AND     C_Employee.EmployeeNumber=@EmployeeNumber
	GROUP BY C_Employee.DisplayName,C_Employee.EmployeeNumber,D_Roles.RoleId,D_Roles.RoleName,D_ShiftBand.ShiftBandId,D_ShiftBand.ShiftBandName,S_Shifts.InTime,
         S_Shifts.OutTime,C_OrganizationNode.OUName,S_Shifts.InStatus,S_Shifts.OutStatus,D_ExceptionCodes.ExcpetionCodeName,C_Employee.RosterGroupId,S_RosterGroup.GroupName,
		 D_Roles.RoleGroupId,S_Shifts.ShiftEndTime,S_Shifts.ShiftStartTime,D_ExceptionCodes.ExceptionCodeId
ORDER BY S_Shifts.ShiftStartTime
END

GO

/****** Object:  StoredProcedure [dbo].[prRD_HRAttendanceDetails]    Script Date: 27/05/2019 16:30:10 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prRpt_TimeSheetReport]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prRpt_TimeSheetReport]
GO

CREATE PROCEDURE [dbo].[prRpt_TimeSheetReport](
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate	        DateTime,
	@EndDate            DateTime,
	@LeaveType	        nVarchar(max),
	@RoleGroup	        nVarchar(max),
	@RosterGroup		nVarchar(max)

)
	
AS
BEGIN

if len(@RoleGroup) =0
		set @RoleGroup='0'

	if len(@RosterGroup) =0
		set @RosterGroup='0'


SELECT  C_Employee.EmployeeId,
		C_Employee.DisplayName FirstName,
	    C_Employee.EmployeeNumber,
		D_Roles.RoleName PrimaryRole,	
		C_OrganizationNode.OUName OrganizationName,	
		C_Employee.RosterGroupId,
		S_RosterGroup.GroupName RosterGroup,
		D_Roles.RoleGroupId	
FROM   C_Employee WITH (NOLOCK)
	inner join C_EmployeeRoles WITH (NOLOCK) on C_EmployeeRoles.EmployeeId= C_Employee.EmployeeId and C_EmployeeRoles.IsPrimaryRole=1
	inner join D_Roles WITH (NOLOCK) on D_Roles.RoleId=C_EmployeeRoles.RoleId		
			INNER JOIN S_RosterGroup WITH (NOLOCK) ON C_Employee.RosterGroupId=S_RosterGroup.RosterGroupId
	        INNER JOIN  C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId				
WHERE  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	AND    (C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroup)) or @RosterGroup ='0')		
	AND		(D_Roles.RoleGroupId  IN (SELECT * FROM fnStringToTable(@RoleGroup)) or @RoleGroup ='0')
GROUP BY   C_Employee.EmployeeId,C_Employee.DisplayName,
	    C_Employee.EmployeeNumber,
		--D_Roles.RoleId PrimaryRoleId, 
		D_Roles.RoleName ,	
		C_OrganizationNode.OUName ,	
		C_Employee.RosterGroupId,
		S_RosterGroup.GroupName ,
		D_Roles.RoleGroupId
order by C_Employee.EmployeeNumber

	select EmployeeId, sum(DATEDIFF(HOUR,ShiftStartTime,ShiftEndTime)) As WorkedHours,
	count(*) WorkedDay
	from S_Shifts WITH (NOLOCK)
	where (convert(date,S_Shifts.ShiftStartTime)>=convert(date,@StartDate) and convert(date,S_Shifts.ShiftEndTime)<=convert(date,@EndDate))
	and  S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	and (S_Shifts.ShiftBandId !=S_Shifts.CombinationShiftId or S_Shifts.CombinationShiftId is null)
	and shiftid not in (select shiftid from S_EmployeeLeaves where (convert(date,FromDate)>=convert(date,@StartDate) and convert(date,EndDate)<=convert(date,@EndDate)) and shiftid is not null)
	group by EmployeeId


	select EmployeeId,
	count(*) InStatus
	from S_Shifts WITH (NOLOCK)
	where (S_Shifts.ShiftStartTime>=@StartDate and S_Shifts.ShiftEndTime<=@EndDate)
	and  S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	and (S_Shifts.ShiftBandId !=S_Shifts.CombinationShiftId or S_Shifts.CombinationShiftId is null)
	and InStatus = 3
	group by EmployeeId

	select EmployeeId,
	count(*) OutStatus
	from S_Shifts WITH (NOLOCK)
	where (S_Shifts.ShiftStartTime>=@StartDate and S_Shifts.ShiftEndTime<=@EndDate)
	and  S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	and (S_Shifts.ShiftBandId !=S_Shifts.CombinationShiftId or S_Shifts.CombinationShiftId is null)
	and InStatus = 4
	group by EmployeeId

	select EmployeeId,S_EmployeeLeaves.ExceptionCodeId,Count(*) LeaveCount,
	ExceptionCodeDesc
	from S_EmployeeLeaves WITH (NOLOCK)
	INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	where (S_EmployeeLeaves.fromDate>=@StartDate and S_EmployeeLeaves.EndDate<=@EndDate)
	and  S_EmployeeLeaves.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	group by EmployeeId,S_EmployeeLeaves.ExceptionCodeId,ExceptionCodeDesc


END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_UnAssigned')
	DROP PROC prRpt_UnAssigned
GO

Create PROCEDURE [dbo].[prRpt_UnAssigned]    
(
	--@OUId				BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate	Datetime,
	@EndDate DateTime,
	@RoleGroupList		nVarchar(max),
	@EquipmentTypeList nVarchar(max),
	@RBId BigInt
)
AS
BEGIN

if(len(@RoleGroupList) = 0)
	set @RoleGroupList='0'

if(len(@EquipmentTypeList) = 0)
	set @EquipmentTypeList='0'

	select STARTTIME StartDate,ENDTIME EndDate,D_Skill.Skill,M_Cranes.CraneNumber 'EquipmentName',D_Skill.Skill SkillName
	 from J_Activity WITH (NOLOCK)
	inner join D_Skill WITH (NOLOCK) on D_Skill.SkillId = J_Activity.SkillId 
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 1 
	inner join M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId = J_ActivityAttributes.ScheduleId 
	inner join M_Cranes WITH (NOLOCK) on M_Cranes.CraneId = M_CraneSchedule.CraneId
	where ShiftId is null
	and J_Activity.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	and D_Skill.SkillId  !=@RBId
	and (convert(date,STARTTIME)>=convert(date,@StartDate) and convert(date,ENDTIME)<=convert(date,@EndDate))
	
	union
	select STARTTIME,ENDTIME,D_Skill.Skill,M_Equipments.EquipmentName 'EquipmentName',D_Skill.Skill SkillName 
	from J_Activity WITH (NOLOCK)
	inner join D_Skill WITH (NOLOCK) on D_Skill.SkillId = J_Activity.SkillId 
	inner join J_ActivityAttributes WITH (NOLOCK) on J_Activity.ActivityId= J_ActivityAttributes.ActivityId and  J_Activity.WorkType= 2
	inner join M_EquipmentSchedule WITH (NOLOCK) on M_EquipmentSchedule.EquipmentScheduleId = J_ActivityAttributes.ScheduleId 
	inner join M_Equipments WITH (NOLOCK) on M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
	where ShiftId is null
	and J_Activity.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	and D_Skill.SkillId  !=@RBId
	and (convert(date,STARTTIME)>=convert(date,@StartDate) and convert(date,ENDTIME)<=convert(date,@EndDate))
	order by STARTTIME,EquipmentName
	
	
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prRpt_WeeklyLeave')
	DROP PROC prRpt_WeeklyLeave
GO
CREATE PROCEDURE prRpt_WeeklyLeave
(
	@StartDate			datetime,
	@EndDate			datetime,
	--@OUID               BigInt,
	@FilteredOUList		nVarchar(max),
	@LeaveType	        bigint
)
	
AS
BEGIN
	SELECT C_Employee.EmployeeNumber,C_Employee.DisplayName FirstName,L_Leaves.NoOfDays,L_Leaves.LeaveStart DateFrom,L_Leaves.LeaveEnd DateTo,C_OrganizationNode.OUName Department,D_ExceptionCodes.ExcpetionCodeName LeaveType
	FROM  L_Leaves	WITH (NOLOCK)
inner join C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = L_Leaves.EmployeeId
inner join C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
	WHERE  (L_Leaves.LeaveStart>=@StartDate and L_Leaves.LeaveStart<=@EndDate)
and  C_OrganizationNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
and C_Employee.IsTerminated=0
and D_ExceptionCodes.ExceptionCodeId=@LeaveType

END

GO

/****** Object:  StoredProcedure [dbo].[prR_GetOverAllActualHoursRpt]    Script Date: 6/20/2018 11:08:40 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prR_GetOverAllActualHoursRpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prR_GetOverAllActualHoursRpt]
GO
/****** Object:  StoredProcedure [dbo].[prR_GetOverAllActualHoursRpt]    Script Date: 6/20/2018 11:08:41 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prR_GetOverAllActualHoursRpt]    
(
	
	--@OUID				BigInt,
	@FilteredOUList		nVarchar(max),
	@StartDate	        datetime,
	@EndDate            DateTime,
	@RoleGroupItems		nVarchar(max),
	@RosterGroupItems	nVarchar(max)	
)
AS


BEGIN
	
	if len(@RoleGroupItems) =0
		set @RoleGroupItems='0'

	if len(@RosterGroupItems) =0
		set @RosterGroupItems='0'

	-- Employee Info
	SELECT	Employee.EmployeeId,
			Employee.OUId,
			Employee.RosterGroupId,
			S_RosterGroup.GroupName RosterGroupName,
			S_RosterGroup.GroupDesc RosterGroupDescription,
			EmployeeNumber,
			BadgeNumber,
			FirstName,
			MiddleName,
			LastName,
			DisplayName 'Name',
			DateOfBirth,
			Convert(nvarchar,DateOfBirth,120) DateOfBirthString,
			Employee.EmploymentBasisId,
			MaritalStatusId,
			GenderId,
			ReligionId,
			Address1,
			Address2,
			Address3,
			City,
			PostCode,
			State,
			CountryId,
			HomePhone HomePhoneNumber,
			MobilePhone MobileNumber,
			EmailAddress,
			IsTerminated 'EmployeeTerminated',
			TerminationDate,
			Convert(nvarchar,TerminationDate,120) TerminationDateString,
			HiredDate,
			Convert(nvarchar,HiredDate,120) HireDateString,
			Position,
			Title,
			IsNull(Employee.ScheduleRuleId,0) ScheduleRuleId,
			IsNull(Employee.PayGroupId,0) PayGroupId,
			D_PayGroup.PayGroupCode,
			D_PayGroup.PayGroupDesc,
			IsNull(HourlyRate,0) HourlyRate,
			IsNull(ContractedHours,0) ContractedHours,
			Employee.ActiveStatus, 
			Employee.CreatedBy, 
			Employee.CreatedDate,
			Employee.UpdatedBy,
			Employee.UpdatedDate,
			OrgUnit.OUDesc OUDescription,
			OrgUnit.OUName,
			Employee.ProbationExpiryDate,
			D_Roles.RoleName,
			C_EmployeeRoles.RoleId,
			Convert(nvarchar,Employee.ProbationExpiryDate) ProbationExpiryString,
			D_EmploymentBasis.EmploymentBasisCode,
			D_EmploymentBasis.EmploymentBasisDesc,
			Employee.OverTimeId,
			D_RoleGroup.RoleGroupName
	FROM	C_Employee Employee WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode OrgUnit WITH (NOLOCK) ON Employee.OUId= OrgUnit.OUId  
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON Employee.ScheduleRuleId=S_ScheduleRules.ScheduleRuleId 
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK)  ON Employee.PayGroupId= D_PayGroup.PayGroupId 
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON  Employee.RosterGroupId= S_RosterGroup.RosterGroupId 
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON   Employee.EmployeeId=C_EmployeeRoles.EmployeeId AND  C_EmployeeRoles.IsPrimaryRole = 1
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId= D_Roles.RoleId   AND D_Roles.ActiveStatus=1
			left outer join D_RoleGroup (nolock) on D_Roles.RoleGroupId= D_RoleGroup.RoleGroupId
			LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = Employee.EmploymentBasisId
	WHERE	Employee.ActiveStatus = 1
	AND		OrgUnit.ActiveStatus = 1
	AND		OrgUnit.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) or @RosterGroupItems='0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) or @RoleGroupItems='0')
	ORDER BY S_RosterGroup.RosterGroupId,
		D_RoleGroup.RoleGroupId ,Employee.EmployeeNumber
	

	-- Employee Shifts
	 SELECT Employee.EmployeeId,
           D_ShiftBand.ShiftBandName,
           S_Shifts.ActualStartTime ShiftDate,
           D_ShiftBand.ColorCode ShiftBandColour,
           D_ShiftBand.ShiftBandId ShiftBandId,
           (CASE
             WHEN S_Shifts.ShiftBandId <> ISNULL(S_Shifts.CombinationShiftId, 0) THEN
              0
             ELSE
              1
           END) ShiftStatus,
		   CONVERT(VARCHAR(5),DATEADD(MINUTE,DATEDIFF(MINUTE,S_Shifts.ActualStartTime,S_Shifts.ActualEndTime),0),114)  ActualHours
    FROM	C_Employee Employee WITH (NOLOCK) 			
			INNER JOIN S_Shifts ON S_Shifts.EmployeeId= Employee.EmployeeId 
			INNER JOIN D_ShiftBand ON D_ShiftBand.ShiftBandId=S_Shifts.ShiftBandId AND D_ShiftBand.ActiveStatus=1
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId			
	WHERE	S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @RosterGroupItems = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @RoleGroupItems = '0')
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	ORDER BY Employee.EmployeeNumber
	
	-- leave exception
	  SELECT S_EmployeeLeaves.EmployeeId , D_ExceptionCodes.ExcpetionCodeName LeaveCode, S_EmployeeLeaves.FromDate LeaveDate, D_ExceptionCodes.ColorCode LeaveColor
      FROM  C_Employee Employee WITH (NOLOCK) 
	  inner join S_EmployeeLeaves on S_EmployeeLeaves.EmployeeId=Employee.EmployeeId	   
     INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId and D_ExceptionCodes.ActiveStatus=1					
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId			
	WHERE	 S_EmployeeLeaves.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @RosterGroupItems = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @RoleGroupItems = '0')
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	ORDER BY Employee.EmployeeNumber
	

	
  -- dayname
 
    SELECT Substring(DATENAME(dw,@StartDate),0,4) AS v1,
           Substring(DATENAME(dw,@StartDate +1 ),0,4) AS v2,
           Substring(DATENAME(dw,@StartDate+ + 2 ),0,4) AS v3,
          Substring(DATENAME(dw,@StartDate+ + 3 ),0,4)  AS v4,
           Substring(DATENAME(dw,@StartDate+ 4 ),0,4)  AS v5,
           Substring(DATENAME(dw,@StartDate+ + 5 ),0,4)  AS v6,
           Substring(DATENAME(dw,@StartDate+ + 6 ),0,4)  AS v7,
          Substring(DATENAME(dw,@StartDate+ + 7 ),0,4)  AS v8,
           Substring(DATENAME(dw,@StartDate+ + 8 ),0,4)  AS v9,
           Substring(DATENAME(dw,@StartDate+ + 9 ),0,4)  AS v10,
           Substring(DATENAME(dw,@StartDate+ + 10 ),0,4)  AS v11,
           Substring(DATENAME(dw,@StartDate+ + 11 ),0,4)  AS v12,
           Substring(DATENAME(dw,@StartDate+ + 12 ),0,4)  AS v13,
           Substring(DATENAME(dw,@StartDate+ + 13 ),0,4)  AS v14,
          Substring(DATENAME(dw,@StartDate+ + 14 ),0,4)  AS v15,
           Substring(DATENAME(dw,@StartDate+ + 15 ),0,4)  AS v16,
           Substring(DATENAME(dw,@StartDate+ + 16 ),0,4)  AS v17,
           Substring(DATENAME(dw,@StartDate+ + 17 ),0,4)  AS v18,
           Substring(DATENAME(dw,@StartDate+ + 18 ),0,4)  AS v19,
           Substring(DATENAME(dw,@StartDate+ + 19 ),0,4)  AS v20,
           Substring(DATENAME(dw,@StartDate+ + 20 ),0,4)  AS v21,
           Substring(DATENAME(dw,@StartDate+ + 21 ),0,4)  AS v22,
           Substring(DATENAME(dw,@StartDate+ + 22 ),0,4)  AS v23,
           Substring(DATENAME(dw,@StartDate+ + 23 ),0,4)  AS v24,
           Substring(DATENAME(dw,@StartDate+ + 24 ),0,4)  AS v25,
           Substring(DATENAME(dw,@StartDate+ + 25 ),0,4)  AS v26,
           Substring(DATENAME(dw,@StartDate+ + 26 ),0,4)  AS v27,
          Substring(DATENAME(dw,@StartDate+ + 27 ),0,4)  AS v28,
           Substring(DATENAME(dw,@StartDate+ + 28 ),0,4)  AS v29,
           Substring(DATENAME(dw,@StartDate+ + 29 ),0,4)  AS v30,
           Substring(DATENAME(dw,@StartDate+ + 30 ),0,4)  AS v31
    

	-- days
	SELECT @StartDate AS v1,
           @StartDate + 1 AS v2,
           @StartDate + 2 AS v3,
           @StartDate + 3 AS v4,
           @StartDate + 4 AS v5,
           @StartDate + 5 AS v6,
           @StartDate + 6 AS v7,
           @StartDate + 7 AS v8,
           @StartDate + 8 AS v9,
           @StartDate + 9 AS v10,
           @StartDate + 10 AS v11,
           @StartDate + 11 AS v12,
           @StartDate + 12 AS v13,
           @StartDate + 13 AS v14,
           @StartDate + 14 AS v15,
           @StartDate + 15 AS v16,
           @StartDate + 16 AS v17,
           @StartDate + 17 AS v18,
           @StartDate + 18 AS v19,
           @StartDate + 19 AS v20,
           @StartDate + 20 AS v21,
           @StartDate + 21 AS v22,
           @StartDate + 22 AS v23,
           @StartDate + 23 AS v24,
           @StartDate + 24 AS v25,
           @StartDate + 25 AS v26,
           @StartDate + 26 AS v27,
           @StartDate + 27 AS v28,
           @StartDate + 28 AS v29,
           @StartDate + 29 AS v30,
           @StartDate + 30 AS v31
    

	
  -- retrieve public holidays between selected dates
 
    SELECT  D_PublicHolidays.HolidayName PublicHolidayName, HolidayDate StartDate, HolidayDate EndDate
      FROM D_PublicHolidays
     --WHERE trunc(startdate) <= trunc(v_enddate) AND trunc(enddate) >= trunc(v_startdate);
END

GO





/****** Object:  StoredProcedure [dbo].[prC_EmployeeSel]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prR_GetOverAllEmployeeRpt]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prR_GetOverAllEmployeeRpt]
GO


CREATE PROCEDURE [dbo].[prR_GetOverAllEmployeeRpt]    
(
	
	@OUID				BigInt,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@RoleGroupItems		nVarchar(max),
	@RosterGroupItems	nVarchar(max),
	@FilteredOUList		nVarchar(max)	
)
AS


BEGIN
	
	if len(@RoleGroupItems) =0
		set @RoleGroupItems='0'

	if len(@RosterGroupItems) =0
		set @RosterGroupItems='0'

	-- Employee Info
	SELECT	Employee.EmployeeId,
			Employee.OUId,
			Employee.RosterGroupId,
			S_RosterGroup.GroupName RosterGroupName,
			S_RosterGroup.GroupDesc RosterGroupDescription,
			EmployeeNumber,
			BadgeNumber,
			FirstName,
			MiddleName,
			LastName,
			DisplayName 'Name',
			DateOfBirth,
			Convert(nvarchar,DateOfBirth,120) DateOfBirthString,
			Employee.EmploymentBasisId,
			MaritalStatusId,
			GenderId,
			ReligionId,
			Address1,
			Address2,
			Address3,
			City,
			PostCode,
			State,
			CountryId,
			HomePhone HomePhoneNumber,
			MobilePhone MobileNumber,
			EmailAddress,
			IsTerminated 'EmployeeTerminated',
			TerminationDate,
			Convert(nvarchar,TerminationDate,120) TerminationDateString,
			HiredDate,
			Convert(nvarchar,HiredDate,120) HireDateString,
		--	Position,
			Title,
			IsNull(Employee.ScheduleRuleId,0) ScheduleRuleId,
			IsNull(Employee.PayGroupId,0) PayGroupId,
			D_PayGroup.PayGroupCode,
			D_PayGroup.PayGroupDesc,
			IsNull(HourlyRate,0) HourlyRate,
			IsNull(ContractedHours,0) ContractedHours,
			Employee.ActiveStatus, 
			Employee.CreatedBy, 
			Employee.CreatedDate,
			Employee.UpdatedBy,
			Employee.UpdatedDate,
			OrgUnit.OUDesc OUDescription,
			OrgUnit.OUName,
			Employee.ProbationExpiryDate,
			D_Roles.RoleName 'Position',
			C_EmployeeRoles.RoleId,
			Convert(nvarchar,Employee.ProbationExpiryDate) ProbationExpiryString,
			D_EmploymentBasis.EmploymentBasisCode,
			D_EmploymentBasis.EmploymentBasisDesc,
			Employee.OverTimeId,
			D_RoleGroup.RoleGroupName
	FROM	C_Employee Employee WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode OrgUnit WITH (NOLOCK) ON Employee.OUId= OrgUnit.OUId  
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON Employee.ScheduleRuleId=S_ScheduleRules.ScheduleRuleId 
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK)  ON Employee.PayGroupId= D_PayGroup.PayGroupId 
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON  Employee.RosterGroupId= S_RosterGroup.RosterGroupId 
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON   Employee.EmployeeId=C_EmployeeRoles.EmployeeId AND  C_EmployeeRoles.IsPrimaryRole = 1
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId= D_Roles.RoleId   AND D_Roles.ActiveStatus=1
			left outer join D_RoleGroup WITH (NOLOCK)  on D_Roles.RoleGroupId= D_RoleGroup.RoleGroupId
			LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = Employee.EmploymentBasisId
	WHERE	OrgUnit.ActiveStatus = 1
	AND		OrgUnit.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) or @RosterGroupItems='0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) or @RoleGroupItems='0')
	ORDER BY S_RosterGroup.RosterGroupId,
		D_RoleGroup.RoleGroupId ,Employee.EmployeeNumber
	

	-- Employee Shifts
	 SELECT Employee.EmployeeId,
           D_ShiftBand.ShiftBandName,
           S_Shifts.ActualStartTime ShiftDate,
           D_ShiftBand.ColorCode ShiftBandColour,
           D_ShiftBand.ShiftBandId ShiftBandId,
           (CASE
             WHEN S_Shifts.ShiftBandId <> ISNULL(S_Shifts.CombinationShiftId, 0) THEN
              0
             ELSE
              1
           END) ShiftStatus
    FROM	C_Employee Employee WITH (NOLOCK) 			
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.EmployeeId= Employee.EmployeeId 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId=S_Shifts.ShiftBandId AND D_ShiftBand.ActiveStatus=1
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId			
	WHERE	 S_Shifts.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList)) 
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @RosterGroupItems = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @RoleGroupItems = '0')
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	and (convert(date,S_Shifts.ActualStartTime) >=CONVERT(Date,@StartDate) and convert(date,S_Shifts.ActualStartTime) <=CONVERT(Date,@EndDate))
	ORDER BY Employee.EmployeeNumber
	
	-- leave exception
	SELECT S_EmployeeLeaves.EmployeeId , D_ExceptionCodes.ExcpetionCodeName LeaveCode, S_EmployeeLeaves.FromDate LeaveDate, D_ExceptionCodes.ColorCode LeaveColor
    FROM	C_Employee Employee WITH (NOLOCK) 
			INNER JOIN S_EmployeeLeaves WITH (NOLOCK) on S_EmployeeLeaves.EmployeeId=Employee.EmployeeId	   
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId and D_ExceptionCodes.ActiveStatus=1					
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId			
	WHERE	Employee.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	AND		(Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @RosterGroupItems = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @RoleGroupItems = '0')
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	and (convert(date,S_EmployeeLeaves.EndDate) >=CONVERT(Date,@StartDate) and convert(date,S_EmployeeLeaves.FromDate) <=CONVERT(Date,@EndDate))
	ORDER BY Employee.EmployeeNumber
	

	
  -- dayname
 
    SELECT Substring(DATENAME(dw,@StartDate),0,4) AS v1,
           Substring(DATENAME(dw,@StartDate +1 ),0,4) AS v2,
           Substring(DATENAME(dw,@StartDate+ + 2 ),0,4) AS v3,
          Substring(DATENAME(dw,@StartDate+ + 3 ),0,4)  AS v4,
           Substring(DATENAME(dw,@StartDate+ 4 ),0,4)  AS v5,
           Substring(DATENAME(dw,@StartDate+ + 5 ),0,4)  AS v6,
           Substring(DATENAME(dw,@StartDate+ + 6 ),0,4)  AS v7,
          Substring(DATENAME(dw,@StartDate+ + 7 ),0,4)  AS v8,
           Substring(DATENAME(dw,@StartDate+ + 8 ),0,4)  AS v9,
           Substring(DATENAME(dw,@StartDate+ + 9 ),0,4)  AS v10,
           Substring(DATENAME(dw,@StartDate+ + 10 ),0,4)  AS v11,
           Substring(DATENAME(dw,@StartDate+ + 11 ),0,4)  AS v12,
           Substring(DATENAME(dw,@StartDate+ + 12 ),0,4)  AS v13,
           Substring(DATENAME(dw,@StartDate+ + 13 ),0,4)  AS v14,
          Substring(DATENAME(dw,@StartDate+ + 14 ),0,4)  AS v15,
           Substring(DATENAME(dw,@StartDate+ + 15 ),0,4)  AS v16,
           Substring(DATENAME(dw,@StartDate+ + 16 ),0,4)  AS v17,
           Substring(DATENAME(dw,@StartDate+ + 17 ),0,4)  AS v18,
           Substring(DATENAME(dw,@StartDate+ + 18 ),0,4)  AS v19,
           Substring(DATENAME(dw,@StartDate+ + 19 ),0,4)  AS v20,
           Substring(DATENAME(dw,@StartDate+ + 20 ),0,4)  AS v21,
           Substring(DATENAME(dw,@StartDate+ + 21 ),0,4)  AS v22,
           Substring(DATENAME(dw,@StartDate+ + 22 ),0,4)  AS v23,
           Substring(DATENAME(dw,@StartDate+ + 23 ),0,4)  AS v24,
           Substring(DATENAME(dw,@StartDate+ + 24 ),0,4)  AS v25,
           Substring(DATENAME(dw,@StartDate+ + 25 ),0,4)  AS v26,
           Substring(DATENAME(dw,@StartDate+ + 26 ),0,4)  AS v27,
          Substring(DATENAME(dw,@StartDate+ + 27 ),0,4)  AS v28,
           Substring(DATENAME(dw,@StartDate+ + 28 ),0,4)  AS v29,
           Substring(DATENAME(dw,@StartDate+ + 29 ),0,4)  AS v30,
           Substring(DATENAME(dw,@StartDate+ + 30 ),0,4)  AS v31
    

	-- days
	SELECT @StartDate AS v1,
           @StartDate + 1 AS v2,
           @StartDate + 2 AS v3,
           @StartDate + 3 AS v4,
           @StartDate + 4 AS v5,
           @StartDate + 5 AS v6,
           @StartDate + 6 AS v7,
           @StartDate + 7 AS v8,
           @StartDate + 8 AS v9,
           @StartDate + 9 AS v10,
           @StartDate + 10 AS v11,
           @StartDate + 11 AS v12,
           @StartDate + 12 AS v13,
           @StartDate + 13 AS v14,
           @StartDate + 14 AS v15,
           @StartDate + 15 AS v16,
           @StartDate + 16 AS v17,
           @StartDate + 17 AS v18,
           @StartDate + 18 AS v19,
           @StartDate + 19 AS v20,
           @StartDate + 20 AS v21,
           @StartDate + 21 AS v22,
           @StartDate + 22 AS v23,
           @StartDate + 23 AS v24,
           @StartDate + 24 AS v25,
           @StartDate + 25 AS v26,
           @StartDate + 26 AS v27,
           @StartDate + 27 AS v28,
           @StartDate + 28 AS v29,
           @StartDate + 29 AS v30,
           @StartDate + 30 AS v31
    

	
  -- retrieve public holidays between selected dates
 
    SELECT  D_PublicHolidays.HolidayName PublicHolidayName, HolidayDate StartDate, HolidayDate EndDate
      FROM D_PublicHolidays WITH (NOLOCK) 
     --WHERE trunc(startdate) <= trunc(v_enddate) AND trunc(enddate) >= trunc(v_startdate);

	  -- Retrieve Employee Termination & Suspension Status
	 SELECT EmployeeId, StartDate, EndDate, StatusId, LTrim(RTrim(Upper(D_MasterCodes.CodeValue))) StatusDescription
	 FROM	C_EmployeeDiciplinary INNER JOIN D_MasterCodes ON C_EmployeeDiciplinary.StatusId = D_MasterCodes.CodeId
	 WHERE	C_EmployeeDiciplinary.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))
	 AND	Convert(Date,StartDate) >= Convert(Date,@StartDate)
	 AND	C_EmployeeDiciplinary.DisciplinaryActionStatus = 0
END









GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddPublicHolidayEmployeeList')
	DROP PROC prS_AddPublicHolidayEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_AddPublicHolidayEmployeeList
----------------------------------------------------------------------------
CREATE PROC prS_AddPublicHolidayEmployeeList
	@EmployeeId		BigInt,
	@TypeId			Int,
	@TypeDesc		nVarchar(500),
	@CreatedBy		nVarchar(50)
AS
BEGIN
	INSERT INTO S_PublicholidayEmployeeList
	(EmployeeId, TypeId, TypeDesc, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @TypeId, @TypeDesc, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS INTEGER)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddRamadanPeriodEmployeeList')
	DROP PROC prS_AddRamadanPeriodEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_AddRamadanPeriodEmployeeList
----------------------------------------------------------------------------
CREATE PROC prS_AddRamadanPeriodEmployeeList
	@RamadanPeriodId	BigInt,
	@EmployeeId			BigInt,
	@TypeId				Int,
	@TypeDesc			nVarchar(500),
	@CreatedBy			nVarchar(50)
AS
BEGIN
	INSERT INTO D_RamadanPeriodEmployeeList
	(RamadanPeriodId, EmployeeId, TypeId, TypeDescription, CreatedBy, CreatedDate)
	VALUES(@RamadanPeriodId, @EmployeeId, @TypeId, @TypeDesc, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS INTEGER)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddSchedulePeriod')
	DROP PROC prS_AddSchedulePeriod
GO

----------------------------------------------------------------------------
-- Insert a single record into S_SchedulePeriod
----------------------------------------------------------------------------
CREATE PROC prS_AddSchedulePeriod
	@OUId bigint = NULL,
	@ScheduleRuleId bigint = NULL,
	@StartDate date = NULL,
	@EndDate date = NULL,
	@PeriodYear int = NULL,
	@PeriodNo int = NULL,
	@ReferenceNotes text = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT S_SchedulePeriod( OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate)
VALUES ( @OUId, @ScheduleRuleId, @StartDate, @EndDate, @PeriodYear, @PeriodNo, @ReferenceNotes, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddShiftExceptionByTimeOffId')
	DROP PROC prS_AddShiftExceptionByTimeOffId
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_AddShiftExceptionByTimeOffId
----------------------------------------------------------------------------
CREATE PROC prS_AddShiftExceptionByTimeOffId
	@TimeOffId				BigInt,
	@ExceptionCodeId		BigInt,
	@CreatedBy				nVarchar(50),
	@ChangeReconStatus		Bit
AS
DECLARE @TimeOffParamName nVarchar(50) = '', @TimeOffExceptionId BigInt = 0, @ShiftId BigInt = 0
BEGIN
	
	If (@ExceptionCodeId = 0)
	BEGIN
		SELECT	@TimeOffParamName = LTrim(RTrim(IsNull(ParamValue,'')))
		FROM	D_SystemParams	WITH (NOLOCK)
		WHERE	ParamName	='TimeOffExceptionCode'

		If (@TimeOffParamName != '')
		BEGIN
			SELECT	@TimeOffExceptionId = IsNull(ExceptionCodeId,0)
			FROM	D_ExceptionCodes	
			WHERE	LTrim(RTrim(ExcpetionCodeName)) = @TimeOffParamName

			SET @ExceptionCodeId = @TimeOffExceptionId
		END
	END

	If (@ExceptionCodeId != 0)
	BEGIN
		SELECT	@ShiftId = IsNull(ShiftId,0) 
		From	L_TimeOff Where TimeOffId = @TimeOffId

		INSERT INTO S_ShiftExceptions
		(ShiftId, ExceptionCodeId, StartTime, EndTime, ApprovalStatus, Remarks, CreatedBy, CreatedDate)
		SELECT	ShiftId, @ExceptionCodeId, StartTime, DATEADD(HOUR, Duration, StartTime), ApprovalStatusId, Remarks, @CreatedBy, GETDATE() 	 
		FROM	L_TimeOff WITH (NOLOCK)
		WHERE	TimeOffId	=	@TimeOffId

		If (@ShiftId != 0 And @ChangeReconStatus = 1) EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, @CreatedBy

		SELECT  CAST(@@Identity AS INTEGER)
	END
	ELSE
	BEGIN
		SELECT 0
	END
END
GO
/****** Object:  StoredProcedure [dbo].[prS_AddShiftExceptions]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_AddShiftExceptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_AddShiftExceptions]
GO

CREATE PROCEDURE [dbo].[prS_AddShiftExceptions]    
(
	@ShiftId			BigInt,
	@ExceptionCodeId	BigInt,
	@StartTime			DateTime,
	@EndTime			DateTime,
	@ApprovalStatus		Int,
	@Remarks			nVarchar(max),
	@SystemParamName	nVarchar(255),
	@EmployeeId			BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @SystemParamValue nVarchar(255) = '', @ExceptionId BigInt = 0
BEGIN

	If (@ExceptionCodeId = 0)
	BEGIN
		SELECT	@SystemParamValue = LTrim(RTrim(IsNull(ParamValue,'')))
		FROM	D_SystemParams	WITH (NOLOCK)
		WHERE	ParamName	= @SystemParamName

		If (@SystemParamValue != '')
		BEGIN
			SELECT	@ExceptionId = IsNull(ExceptionCodeId,0)
			FROM	D_ExceptionCodes WITH (NOLOCK)
			WHERE	LTrim(RTrim(ExcpetionCodeName)) = @SystemParamValue

			SET @ExceptionCodeId = @ExceptionId
		END
	END

	IF (@ShiftId = 0)
	BEGIN
		SELECT @ShiftId = ShiftId, @StartTime = ActualStartTime, @EndTime = ActualEndTime
		FROM	S_Shifts WITH (NOLOCK)
		WHERE	Convert(Date,ActualStartTime) = Convert(Date,@StartTime) 
		AND		EmployeeId	=	@EmployeeId
	END	

	If (@ExceptionCodeId != 0 AND @ShiftId != 0)
	BEGIN
		INSERT INTO S_ShiftExceptions
		(ShiftId, ExceptionCodeId, StartTime, EndTime, ApprovalStatus, Remarks, CreatedBy, CreatedDate)
		VALUES(@ShiftId, @ExceptionCodeId, @StartTime, @EndTime, @ApprovalStatus, @Remarks, @CreatedBy, GETDATE())

		SELECT  CAST(@@Identity AS INTEGER)  
	END
	Else
	BEGIN
		If (@ShiftId = 0) SELECT 1 ELSE SELECT 0
	END
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddShiftValidations')
	DROP PROC prS_AddShiftValidations
GO

----------------------------------------------------------------------------
-- Insert a single record into S_ShiftValidations
----------------------------------------------------------------------------
CREATE PROC prS_AddShiftValidations
	@ShiftId bigint = NULL,
	@EmployeeId bigint = NULL,
	@SchedulePeriodId bigint = NULL,
	@ShiftDate datetime = NULL,
	@IsError bit = NULL,
	@ErrorId int = NULL,
	@ErrorDesc nvarchar(100) = NULL,
	@CreatedBy nvarchar(100) = NULL
	
AS

INSERT S_ShiftValidations(ShiftId, EmployeeId, SchedulePeriodId, ShiftDate, IsError, ErrorId, ErrorDesc, CreatedBy, CreatedDate)
VALUES (@ShiftId, @EmployeeId, @SchedulePeriodId, @ShiftDate, @IsError, @ErrorId, @ErrorDesc, @CreatedBy, Getdate())

SELECT SCOPE_IDENTITY()

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddTHPEmployeeDetails')
	DROP PROC prS_AddTHPEmployeeDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeDetails
----------------------------------------------------------------------------
CREATE PROC [dbo].[prS_AddTHPEmployeeDetails]
	@THPPeriodId bigint = NULL,
	@EmployeeId bigint = NULL,
	@ShiftDate datetime = NULL,
	@ShiftId bigint = NULL,
	@LeaveId bigint = NULL,
	@ShiftCounter decimal(18, 2) = NULL,
	@ActivityCounter decimal(18, 2) = NULL,
	@LeaveCounter decimal(18, 2) = NULL,
	@NormalHour decimal(18, 2) = NULL,
	@OTHour decimal(18, 2) = NULL,
	@THPProcessDate datetime = NULL,
	@THPNotes text = NULL,
	@CreatedBy nvarchar(100) = NULL
AS
BEGIN
	DELETE FROM S_THPEmployeeDetails 
	Where	EmployeeId				=	@EmployeeId
	And		Convert(Date,ShiftDate)	=	Convert(Date,@ShiftDate)

	INSERT S_THPEmployeeDetails(THPPeriodId, EmployeeId, ShiftDate, ShiftId, LeaveId, ShiftCounter, ActivityCounter, LeaveCounter, NormalHour, OTHour, THPProcessDate, THPNotes, CreatedBy, CreatedDate)
	VALUES (@THPPeriodId, @EmployeeId, @ShiftDate, @ShiftId, @LeaveId, @ShiftCounter, @ActivityCounter, @LeaveCounter, @NormalHour, @OTHour, @THPProcessDate, @THPNotes, @CreatedBy, getdate())

	update S_THPEmployeePeriods
	set ShiftCounter=ShiftCounter+@ShiftCounter,ActivityCounter=ActivityCounter+@ActivityCounter
	where EmployeeId=@EmployeeId and ( @ShiftDate between PeriodStart and PeriodEnd)

	update S_Shifts
	Set PickedByTHP= 1, UpdatedDate=GETDATE(),UpdatedBy='THP Process'
	where ShiftId=@ShiftId

	select  CAST(@@Identity AS INTEGER) 

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddTHPEmployeePeriods')
	DROP PROC prS_AddTHPEmployeePeriods
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeePeriods
----------------------------------------------------------------------------
CREATE PROC prS_AddTHPEmployeePeriods
	@OUId bigint = NULL,
	@THPSettingsId bigint = NULL,
	@EmployeeId bigint = NULL,
	@PeriodStart date = NULL,
	@PeriodEnd date = NULL,
	@PeriodUnit int = NULL,
	@PeriodLength int = NULL,
	@ShiftCounter decimal(18, 2) = NULL,
	@LeaveCounter decimal(18, 2) = NULL,
	@ActivityCounter decimal(18, 2) = NULL,
	@NormalHourCounter decimal(18, 2) = NULL,
	@OTHourCounter decimal(18, 2) = NULL,
	@CreatedBy nvarchar(100) = NULL

AS

INSERT S_THPEmployeePeriods(OUId, THPSettingsId, EmployeeId, PeriodStart, PeriodEnd, PeriodUnit, PeriodLength, ShiftCounter, LeaveCounter, ActivityCounter, NormalHourCounter, OTHourCounter, CreatedBy, CreatedDate)
VALUES (@OUId, @THPSettingsId, @EmployeeId, @PeriodStart, @PeriodEnd, @PeriodUnit, @PeriodLength, @ShiftCounter, @LeaveCounter, @ActivityCounter, @NormalHourCounter, @OTHourCounter, @CreatedBy, GETDATE())

select  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddTHPSettingRosterGroups')
	DROP PROC prS_AddTHPSettingRosterGroups
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPSettingRosterGroups
----------------------------------------------------------------------------
CREATE PROC prS_AddTHPSettingRosterGroups
	@THPSettingId bigint = NULL,
	@RosterGroupId bigint = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT S_THPSettingRosterGroups(THPSettingId, RosterGroupId, CreatedBy, CreatedDate)
VALUES (@THPSettingId, @RosterGroupId, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_AddTHPSettings')
	DROP PROC prS_AddTHPSettings
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPSettings
----------------------------------------------------------------------------
CREATE PROC prS_AddTHPSettings
	@OUId bigint = NULL,
	@THPSettingsName nVarchar(255) = NULL,
	@StartDate date = NULL,
	@PeriodUnit int = NULL,
	@PeriodLength int = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT S_THPSettings(OUId, THPSettingsName, StartDate, PeriodUnit, PeriodLength, CreatedBy, CreatedDate)
VALUES (@OUId, @THPSettingsName, @StartDate, COALESCE(@PeriodUnit, (1)), @PeriodLength, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_DeleteEmployeeLeavesByDateEmployeeId]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prS_DeleteEmployeeLeavesByDateEmployeeId]
GO
 
Create PROCEDURE [dbo].[prS_DeleteEmployeeLeavesByDateEmployeeId] 
(
	@LeaveDate			DateTime,
	@ExceptionCodeId	BigInt,
	@EmployeeId			BigInt
)
AS
BEGIN

	DELETE FROM S_EmployeeLeaves WHERE EmployeeId = @EmployeeId And Convert(Date,FromDate) = @LeaveDate And ExceptionCodeId = @ExceptionCodeId

	SELECT 1
END 
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prS_DeleteFlexiShiftsByCurrentYear') AND type in (N'P', N'PC'))
	DROP PROCEDURE prS_DeleteFlexiShiftsByCurrentYear
GO
 
CREATE PROCEDURE prS_DeleteFlexiShiftsByCurrentYear
AS
BEGIN	 
	
	--UPDATE	S_EmployeeLeaves 
	--SET		ShiftId = NULL 
	--where	ShiftId IN (Select ShiftId From S_Shifts 
	--					Where	Convert(Date,ActualStartTime) < Convert(Date,GetDate())
	--					AND		S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId
	--					AND		Year(ActualStartTime) = Year(GETDATE()))

	DELETE FROM S_Shifts 
	WHERE	Convert(Date,ActualStartTime) < Convert(Date,GetDate())
	AND		S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId
	AND		Year(ActualStartTime) = Year(GETDATE())
	AND		ShiftId NOT IN 
	(
		SELECT ShiftId FROM S_EmployeeLeaves with (nolock) 
		where Convert(Date,FromDate) < Convert(Date,GETDATE()) And Year(FromDate) = Year(GETDATE())
		AND   ShiftId IS NOT NULL
	)

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeletePublicHolidayEmployeeList')
	DROP PROC prS_DeletePublicHolidayEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_DeletePublicHolidayEmployeeList
----------------------------------------------------------------------------
CREATE PROC prS_DeletePublicHolidayEmployeeList
	@EmployeeId	BigInt
AS
BEGIN
	DELETE FROM S_PublicholidayEmployeeList
	WHERE	EmployeeId	=	@EmployeeId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeleteRosterLeaveByDateEmployeeId')
	DROP PROCEDURE prS_DeleteRosterLeaveByDateEmployeeId
GO
/****** Object:  StoredProcedure [dbo].[prS_DeleteRosterLeaveByDateEmployeeId]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE prS_DeleteRosterLeaveByDateEmployeeId    
(
	@EmployeeId		BigInt,
	@LeaveDate		DateTime,
	@ExceptionId	BigInt
)
AS

BEGIN
	DELETE FROM S_EmployeeLeaves 
	WHERE	Convert(Date,FromDate)  =	Convert(Date,@LeaveDate)
	AND		EmployeeId				=	@EmployeeId
	AND		ExceptionCodeId			=	@ExceptionId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeleteShiftExceptionByTimeOffId')
	DROP PROC prS_DeleteShiftExceptionByTimeOffId
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_DeleteShiftExceptionByTimeOffId
----------------------------------------------------------------------------
CREATE PROC prS_DeleteShiftExceptionByTimeOffId
	@TimeOffId			BigInt
AS
BEGIN
	DECLARE @ShiftExceptionId	BigInt = 0, @StartTime	DateTime, @EndTime DateTime, @ShiftId BigInt;

	SELECT	@StartTime	= StartTime, @EndTime = DATEADD(HOUR, Duration, StartTime), @ShiftId = ShiftId
	FROM	L_TimeOff
	WHERE	TimeOffId	=	@TimeOffId

	DELETE FROM S_ShiftExceptions
	WHERE	StartTime	=	@StartTime
	AND		EndTime		=	@EndTime
	AND		ShiftId		=	@ShiftId

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prS_DeleteShiftExceptions]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_DeleteShiftExceptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_DeleteShiftExceptions]
GO

CREATE PROCEDURE [dbo].[prS_DeleteShiftExceptions]    
(	
	@ShiftExceptionId	BigInt
)
AS
BEGIN
	DELETE FROM S_ShiftExceptions
	WHERE	ShiftExceptionId	=	@ShiftExceptionId

	SELECT @ShiftExceptionId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeleteShiftsBetweenDatesByEmployeeId')
	DROP PROC prS_DeleteShiftsBetweenDatesByEmployeeId
GO

----------------------------------------------------------------------------
-- Delete Existing Shifts Between Defined Dates By Employee Id
----------------------------------------------------------------------------
CREATE PROC prS_DeleteShiftsBetweenDatesByEmployeeId
(
	@StartDate		DateTime,
	@EndDate		DateTime,
	@EmployeeId		BigInt
)
AS
BEGIN
	
	DELETE FROM S_THPEmployeeDetails 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	AND		S_THPEmployeeDetails.EmployeeId	=	@EmployeeId

	-- Delete Available Shifts From Termination Date Till 
	DELETE FROM S_Shifts
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.EmployeeId	=	@EmployeeId

	SELECT 1

END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeleteShiftValidationsByEmployeeIdAndDateRange')
	DROP PROC prS_DeleteShiftValidationsByEmployeeIdAndDateRange
GO

----------------------------------------------------------------------------
-- Delete a single record from S_ShiftValidations
----------------------------------------------------------------------------
CREATE PROC prS_DeleteShiftValidationsByEmployeeIdAndDateRange
	@EmployeeId bigint,
	@StartDate DateTime,
	@EndDate DateTime
AS

DELETE	S_ShiftValidations
WHERE 	EmployeeId = @EmployeeId
	AND 	(ShiftDate >= CONVERT(DATETIME, @StartDate)
	AND 	ShiftDate <= CONVERT(DATETIME, @EndDate))

SELECT 1

GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prS_DeleteTemplateRosterById') AND type in (N'P', N'PC'))
DROP PROCEDURE prS_DeleteTemplateRosterById
GO

CREATE PROCEDURE prS_DeleteTemplateRosterById
(
	@TemplateRosterId		BigInt
)
AS
BEGIN
	--DELETE FROM S_TemplateRoster_Shifts WHERE	TemplateId = @TemplateRosterId

	--DELETE FROM S_TemplateRosterLine WHERE TemplateId = @TemplateRosterId

	UPDATE	S_TemplateRoster SET ActiveStatus = 0  
	WHERE	TemplateId = @TemplateRosterId

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_DeleteTemplateRosterLine]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_DeleteTemplateRosterLine]
GO

/****** Object:  StoredProcedure [dbo].[prS_DeleteTemplateRosterLine]    Script Date: 20/6/2018 7:07:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_DeleteTemplateRosterLine]    
(
	@TemplateID		BigInt,
	@RosterGroupId	BigInt
)
AS
BEGIN
	DELETE FROM S_TemplateRoster_Shifts
	WHERE TemplateLineId = (SELECT TemplateLineId FROM S_TemplateRosterLine WHERE TemplateId = @TemplateID AND RosterGroupId = @RosterGroupId)	

	DELETE FROM S_TemplateRosterLine
	WHERE  TemplateId = @TemplateID AND RosterGroupId = @RosterGroupId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_DeleteTHPSettingRosterGroupsByRosterGroupId')
	DROP PROC prS_DeleteTHPSettingRosterGroupsByRosterGroupId
GO

----------------------------------------------------------------------------
-- Delete a single record from S_THPSettingRosterGroups
----------------------------------------------------------------------------
CREATE PROC prS_DeleteTHPSettingRosterGroupsByRosterGroupId
	@RosterGroupId bigint
AS

DELETE	S_THPSettingRosterGroups
WHERE 	RosterGroupId = @RosterGroupId

SELECT 1

GO
/****** Object:  StoredProcedure [dbo].[prS_EmployeeApproval]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeApproval]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeApproval]
GO

CREATE PROCEDURE [dbo].[prS_EmployeeApproval] (
	  @moduleId	 bigInt ,
      @employeeId  bigInt
)
AS
BEGIN
	SELECT  C_EmployeeWorkflow.EmployeeId,
	   W_WorkflowRouteDetails.RouteLevel,
       W_WorkflowRouteDetails.ApprovalRequirement,
       C_Employee.EmployeeNumber,
       C_Employee.DisplayName EmployeeName,
       C_EmployeeWorkflow.RouteId,
       C_EmployeeWorkflow.ModuleId,
       C_OrganizationNode.OUName,
	   C_EmployeeRoles.RoleId,
	   D_Roles.RoleName
	  
FROM   W_WorkflowRouteDetails WITH (NOLOCK)	
       INNER JOIN W_WorkflowRoute WITH (NOLOCK) ON W_WorkflowRouteDetails.RouteId = W_WorkflowRoute.RouteId
       INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
       INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = W_WorkflowRouteDetails.EmployeeId
	   INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId=C_Employee.OUId
	   INNER JOIN C_EmployeeRoles WITH(NOLOCK) ON C_EmployeeRoles.EmployeeId=C_Employee.EmployeeId
	   INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId=C_EmployeeRoles.RoleId

WHERE  C_EmployeeWorkflow.EmployeeId = @employeeId--1204
  AND  C_EmployeeWorkflow.ModuleId = @moduleId --(201, 202, 203)
ORDER BY W_WorkflowRouteDetails.RouteLevel
END

GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeForRosterByOU]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeForRosterByOU]
GO
/****** Object:  StoredProcedure [dbo].[prS_EmployeeForRosterByOU]    Script Date: 7/10/2018 3:18:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prS_EmployeeForRosterByOU]   
(
	@EmployeeItems		nVarchar(max),
	@RosterGroupItems	nVarchar(max),
	@RoleGroupItems		nVarchar(max),
	@OUID				BigInt
	
)
AS
DECLARE @__employeeItemsId INT = 0, @__rosterGroupItemsId INT = 0, @__roleGroupItemsId INT = 0
BEGIN	 

	SELECT TOP 1 @__employeeItemsId = sID FROM fnStringToTable(@EmployeeItems)
	
	SELECT TOP 1 @__rosterGroupItemsId = sID FROM fnStringToTable(@RosterGroupItems)

	SELECT TOP 1 @__roleGroupItemsId = sID FROM fnStringToTable(@RoleGroupItems)

	SELECT	DISTINCT C_Employee.EmployeeId, 
			C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			C_Employee.OUId, C_OrganizationNode.OUName,
			D_Roles.RoleName PrimaryRoleName,
			D_SKill.Skill PrimarySkillName, -- D_Skill.SkillDesc 
			IsNull(C_EmployeeRoles.RoleId,0) PrimaryRoleId,
			IsNull(C_EmployeeSkills.SkillId,0) PrimarySkillId,
			D_RoleGroup.RoleGroupName,
			IsNull(D_RoleGroup.RoleGroupId,0) RoleGroupId,
			S_RosterGroup.GroupName RosterGroupName,
			IsNull(S_RosterGroup.RosterGroupId,0) RosterGroupId,
			IsNull(C_Employee.HourlyRate,0) HourlyRate,
			C_Employee.ScheduleRuleId,
			S_ScheduleRules.Name ScheduleRuleName,
			C_Employee.PayGroupId,
			D_PayGroup.PayGroupCode PayGroupName
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId 
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId AND C_EmployeeRoles.IsPrimaryRole = 1
			LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_ROLES.RoleGroupId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId =  C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId 
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
	WHERE	C_Employee.ActiveStatus = 1 AND C_OrganizationNode.ActiveStatus = 1
	AND		C_Employee.OUId = @OUID
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @__rosterGroupItemsId = 0)
	AND		(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeItems)) OR @__employeeItemsId  = 0)
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @__roleGroupItemsId = 0)
	--AND 	C_EmployeeRoles.IsPrimaryRole = 1
	--AND		C_EmployeeSkills.IsPrimary = 1
	ORDER BY C_Employee.EmployeeNumber
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeForShiftValidations]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeForShiftValidations]
GO
/****** Object:  StoredProcedure [dbo].[prS_EmployeeForShiftValidations]    Script Date: 7/10/2018 3:18:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prS_EmployeeForShiftValidations]   
(
	@EmployeeItems		nVarchar(max),
	@RosterGroupItems	nVarchar(max),
	@RoleGroupItems		nVarchar(max),
	@OUID				BigInt
	
)
AS
DECLARE @__employeeItemsId INT = 0, @__rosterGroupItemsId INT = 0, @__roleGroupItemsId INT = 0
BEGIN	 

	SELECT TOP 1 @__employeeItemsId = sID FROM fnStringToTable(@EmployeeItems)
	
	SELECT TOP 1 @__rosterGroupItemsId = sID FROM fnStringToTable(@RosterGroupItems)

	SELECT TOP 1 @__roleGroupItemsId = sID FROM fnStringToTable(@RoleGroupItems)

	SELECT	DISTINCT C_Employee.EmployeeId, 
			C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			C_Employee.OUId, C_OrganizationNode.OUName,
			D_Roles.RoleName PrimaryRoleName,
			D_SKill.Skill PrimarySkillName, -- D_Skill.SkillDesc 
			IsNull(C_EmployeeRoles.RoleId,0) PrimaryRoleId,
			IsNull(C_EmployeeSkills.SkillId,0) PrimarySkillId,
			D_RoleGroup.RoleGroupName,
			IsNull(D_RoleGroup.RoleGroupId,0) RoleGroupId,
			S_RosterGroup.GroupName RosterGroupName,
			IsNull(S_RosterGroup.RosterGroupId,0) RosterGroupId,
			IsNull(C_Employee.HourlyRate,0) HourlyRate,
			C_Employee.ScheduleRuleId,
			S_ScheduleRules.Name ScheduleRuleName,
			C_Employee.PayGroupId,
			D_PayGroup.PayGroupCode PayGroupName
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId 
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
			LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_ROLES.RoleGroupId
			LEFT OUTER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId 
			LEFT OUTER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId =  C_EmployeeSkills.SkillId
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId 
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
	WHERE	C_Employee.ActiveStatus = 1 AND C_OrganizationNode.ActiveStatus = 1
	AND		C_Employee.OUId = @OUID
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @__rosterGroupItemsId = 0)
	AND		(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeItems)) OR @__employeeItemsId  = 0)
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @__roleGroupItemsId = 0)
	AND 	C_EmployeeRoles.IsPrimaryRole = 1
	--AND		C_EmployeeSkills.IsPrimary = 1
	ORDER BY C_Employee.EmployeeNumber
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeavesBetweenDatesSel]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prS_EmployeeLeavesBetweenDatesSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_EmployeeLeavesBetweenDatesSel]    
(
	@StartDate	DateTime,
	@EndDate	DateTime,
	@OUId		BigInt	
)
AS
BEGIN
	SELECT	S_EmployeeLeaves.LeaveId,
			S_EmployeeLeaves.EmployeeId,
			S_EmployeeLeaves.ExceptionCodeId,
			S_EmployeeLeaves.FromDate,
			S_EmployeeLeaves.EndDate,
			S_EmployeeLeaves.ApprovedBy,
			S_EmployeeLeaves.LeaveHours,
			IsNull(S_EmployeeLeaves.ShiftId,0) ShiftId,
			S_EmployeeLeaves.Remarks,
			S_EmployeeLeaves.PickedTHP,
			S_EmployeeLeaves.Note,
			S_EmployeeLeaves.CreatedBy,
			S_EmployeeLeaves.CreatedDate,
			S_EmployeeLeaves.UpdatedBy,
			S_EmployeeLeaves.UpdatedDate,
			D_ExceptionCodes.ExcpetionCodeName,
			D_ExceptionCodes.ColorCode ExceptionColor,
			C_Employee.FirstName + '' + C_Employee.LastName as EmployeeName,
			IsNull(L_LeaveProfiles.DayCalculation,0) DayCalculation
	FROM	S_EmployeeLeaves WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId=S_EmployeeLeaves.EmployeeId
			INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId=S_EmployeeLeaves.ExceptionCodeId
			LEFT OUTER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_LeaveProfiles.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
						--AND	L_LeaveProfiles.LeaveProfileId = C_EmployeeLeaveProfile.EmployeeLeaveProfileId
						AND	L_LeaveProfiles.LeaveProfileHeaderId = C_EmployeeLeaveProfile.LeaveProfileHeaderId
	WHERE	(Convert(Date,S_EmployeeLeaves.EndDate) >= CONVERT(date, @StartDate)
	AND		Convert(Date,S_EmployeeLeaves.FromDate) <= CONVERT(date, @EndDate))
	AND		(C_OrganizationNode.OUId = @OUId OR @OUId = 0)
	--AND		S_EmployeeLeaves.ShiftId IS NOT NULL
	ORDER BY S_EmployeeLeaves.FromDate, C_Employee.EmployeeNumber
END
go

 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeavesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeavesDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_EmployeeLeavesDel] 
(
	@LeaveId		BigInt	 
)
AS
BEGIN

	DELETE FROM S_EmployeeLeaves WHERE LeaveId=@LeaveId	  

	SELECT 1
END 
go
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeavesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeavesIns]
GO
  

Create PROCEDURE [dbo].[prS_EmployeeLeavesIns]    
(
	@LeaveId				bigint,
	@OUId					BigInt,
	@EmployeeID				BigInt,	
	@ExceptionCodeId		BigInt,
	@FromDate				datetime,
	@EndDate				datetime,
	@ApprovedBy				nvarchar(50),
	@LeaveHours				bigint,
	@ShiftId				bigint,
	@Remarks				nvarchar(1000),
	@PickedTHP				bit,
	@Note					text,
	@SystemParamName		nVarchar(100),
	@ChangeReconStatus		Bit,
	@CreatedBy				nVarchar(50),
	@UpdatedBy				nvarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0, @RosterGroupDetailsID BigInt = 0,@leaveid1 bigint, @SelectedShiftId BigInt = 0,
		@SystemParamValue nVarchar(255) = '', @ExceptionId BigInt = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_EmployeeLeaves WITH (NOLOCK)
	WHERE	EmployeeId		= @EmployeeID
	--AND		ExceptionCodeId	= @ExceptionCodeId
	AND		convert(date,FromDate)		=convert(date,@FromDate)
	AND		Convert(date,EndDate)		=convert(date,@FromDate)

	IF (@LeaveHours IS NULL OR @LeaveHours = 0)
	BEGIN
		SELECT	@LeaveHours = IsNull(D_ExceptionCodes.ShiftLength,0)
		FROM	D_ExceptionCodes WITH (NOLOCK)
		WHERE	ExceptionCodeId		=	@ExceptionCodeId

	END

	If (@ExceptionCodeId = 0)
	BEGIN
		SELECT	@SystemParamValue = LTrim(RTrim(IsNull(ParamValue,'')))
		FROM	D_SystemParams	WITH (NOLOCK)
		WHERE	ParamName	= @SystemParamName

		If (@SystemParamValue != '')
		BEGIN
			SELECT	@ExceptionId = IsNull(ExceptionCodeId,0)
			FROM	D_ExceptionCodes WITH (NOLOCK)
			WHERE	LTrim(RTrim(ExcpetionCodeName)) = @SystemParamValue

			SET @ExceptionCodeId = @ExceptionId
		END
	END

	IF (IsNull(@ShiftId,0) = 0)
	BEGIN
		SELECT @ShiftId = IsNull(ShiftId,0), @FromDate = Convert(Date,ActualStartTime), @EndDate = ActualEndTime
		FROM	S_Shifts WITH (NOLOCK)
		WHERE	Convert(Date,ActualStartTime) = Convert(Date,@FromDate)
		AND		EmployeeId		=	@EmployeeID

		If (@ShiftId = 0) SET @ShiftId = NULL
	END	

	SELECT @OUId = OUId From C_Employee WITH (NOLOCK) WHERE EmployeeId = @EmployeeId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_EmployeeLeaves
		(OUId, EmployeeId,ExceptionCodeId, FromDate,EndDate,ApprovedBy,LeaveHours,ShiftId,Remarks,PickedTHP,Note,CreatedBy,CreatedDate)
		VALUES(@OUId, @EmployeeID,@ExceptionCodeId ,@FromDate,@FromDate,@ApprovedBy,@LeaveHours,@ShiftId,@Remarks,
		@PickedTHP,@Note,@CreatedBy,GETDATE())

		If (@ShiftId != 0 And @ChangeReconStatus = 1) EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, @CreatedBy
		 
		SELECT SCOPE_IDENTITY();
	--select 1;
	END
	Else If (@ShiftId != 0)
	BEGIN
	
	SELECT	@leaveid1 =  LeaveId
	FROM	S_EmployeeLeaves WITH (NOLOCK)
	WHERE	EmployeeId		= @EmployeeID
	AND		ExceptionCodeId	= @ExceptionCodeId
	AND		convert(date,FromDate)		= convert(date,@FromDate)
	AND		Convert(date,EndDate)		= convert(date,@FromDate)

	UPDATE	S_EmployeeLeaves
				SET	OUId					=	@OUId, 
				EmployeeId					=	@EmployeeId, 
				ExceptionCodeId				=	@ExceptionCodeId, 				 
				FromDate					=	@FromDate, 
				EndDate						=	@FromDate, 
				ApprovedBy					=	@ApprovedBy,
				LeaveHours					=	@LeaveHours,
				ShiftId						=	@ShiftId,
				Remarks						=	@Remarks,
				PickedTHP					=	@PickedTHP,
				Note						=	@Note,
				UpdatedBy					=	@UpdatedBy,
				UpdatedDate					=	GETDATE()
		WHERE	LeaveId						=	@LeaveId

		If (@ShiftId != 0 And @ChangeReconStatus = 1) EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, @UpdatedBy
					
		SELECT 1;
		 
	END

	SELECT 1;
	--ELSE If (@ShiftId = 0) SELECT 1 ELSE SELECT 0
END
go

 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeavesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeavesSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_EmployeeLeavesSel]    
(
	@LeaveId	    BigInt,
	@OUId		    BigInt,
	@startDate      datetime,
	@endDate        datetime,
	@employeeNumber nvarchar(50)
)
AS
BEGIN
	SELECT	C_Employee.EmployeeNumber,
			S_EmployeeLeaves.LeaveId,
			S_EmployeeLeaves.EmployeeId,
			S_EmployeeLeaves.ExceptionCodeId,
			S_EmployeeLeaves.FromDate,
			S_EmployeeLeaves.EndDate,
			S_EmployeeLeaves.ApprovedBy,
			S_EmployeeLeaves.LeaveHours,
			S_EmployeeLeaves.ShiftId,
			S_EmployeeLeaves.Remarks,
			S_EmployeeLeaves.PickedTHP,
			S_EmployeeLeaves.Note,
			S_EmployeeLeaves.CreatedBy,
			S_EmployeeLeaves.CreatedDate,
			S_EmployeeLeaves.UpdatedBy,
			S_EmployeeLeaves.UpdatedDate,
			D_ExceptionCodes.ExcpetionCodeName,
			C_Employee.EmployeeNumber + ' ' + C_Employee.DisplayName as EmployeeName
	FROM	S_EmployeeLeaves WITH (NOLOCK) INNER JOIN C_OrganizationNode with (NOLOCK) ON S_EmployeeLeaves.OUId = C_OrganizationNode.OUId
			inner join D_ExceptionCodes with (nolock) on D_ExceptionCodes.ExceptionCodeId=S_EmployeeLeaves.ExceptionCodeId
			inner join C_Employee with (nolock) on C_Employee.EmployeeId=S_EmployeeLeaves.EmployeeId
	WHERE	(S_EmployeeLeaves.LeaveId = @LeaveId OR @LeaveId = 0)
	AND		(C_OrganizationNode.OUId = @OUId)
    AND CONVERT(DATE,S_EmployeeLeaves.FromDate)>=CONVERT(DATE,@startDate)
	AND	CONVERT(DATE,S_EmployeeLeaves.EndDate)<=CONVERT(DATE,@endDate)
	AND	C_Employee.EmployeeNumber LIKE('%' + @employeeNumber + '%')
	ORDER BY S_EmployeeLeaves.FromDate, C_Employee.EmployeeNumber
END

go


 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeavesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeavesUpd]
GO
 
 

Create PROCEDURE [dbo].[prS_EmployeeLeavesUpd]    
(
	@LeaveId				BIGINT,
	@OUId					BigInt,
	@EmployeeID				BigInt,	
	@ExceptionCodeId		BigInt,
	@FromDate				datetime,
	@EndDate				datetime,
	@ApprovedBy				nvarchar(50),
	@LeaveHours				bigint,
	@ShiftId				bigint,
	@Remarks				nvarchar(1000),
	@PickedTHP				bit,
	@Note					text,	 
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_EmployeeLeaves WITH (NOLOCK)
	WHERE	EmployeeId		= @EmployeeID
	AND		ExceptionCodeId	= @ExceptionCodeId
	AND		FromDate		=@FromDate
	AND		EndDate			=@EndDate
	AND		LeaveId != @LeaveId

	IF (@LeaveHours IS NULL OR @LeaveHours = 0)
	BEGIN
		SELECT	@LeaveHours = IsNull(D_ExceptionCodes.ShiftLength,0)
		FROM	D_ExceptionCodes 
		WHERE	ExceptionCodeId		=	@ExceptionCodeId

	END

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	S_EmployeeLeaves
				SET	OUId					=	@OUId, 
				EmployeeId					=	@EmployeeId, 
				ExceptionCodeId				=	@ExceptionCodeId, 				 
				FromDate					=	@FromDate, 
				EndDate						=	@EndDate, 
				ApprovedBy					=	@ApprovedBy,
				LeaveHours					=	@LeaveHours,
				ShiftId						=	@ShiftId,
				Remarks						=	@Remarks,
				PickedTHP					=	@PickedTHP,
				Note						=	@Note,
				UpdatedBy					=	@UpdatedBy,
				UpdatedDate					=	GETDATE()
		WHERE	ExceptionCodeId				=	@ExceptionCodeId
					
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prS_EmployeeShiftsSel') AND type in (N'P', N'PC'))
DROP PROCEDURE prS_EmployeeShiftsSel
GO
 
CREATE PROCEDURE prS_EmployeeShiftsSel
(
	@StartDate	DateTime,
	@EndDate	DateTime,
	@OUId		BigInt,
	@EmployeeId	nVarchar(max)
)
AS
BEGIN	 
	SELECT	C_Employee.EmployeeId, 
			C_Employee.DisplayName, 
			S_Shifts.ShiftId, 
			S_Shifts.ShiftBandId, 
			D_ShiftBand.ShiftBandCode, 
			D_ShiftBand.ColorCode ShiftBandColor,
			--S_Shifts.CombinationShiftId, 
			S_Shifts.Notes, 
			S_Shifts.OnCallShift,
			S_Shifts.ActualStartTime, 
			S_Shifts.ActualEndTime,
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime,
			S_Shifts.RoleId, 
			D_Roles.RoleName, 
			S_Shifts.OUId, 
			C_OrganizationNode.OUName,
			S_Shifts.ShiftCost,
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN D_Roles WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
	WHERE	C_Employee.ActiveStatus = 1
	AND		D_ShiftBand.ActiveStatus = 1
	AND		Convert(Date,S_Shifts.ActualEndTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
	AND		(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	ORDER BY S_Shifts.ActualStartTime, C_Employee.EmployeeNumber
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetAllEmployeesByLeaveProfileHeaderId')
	DROP PROCEDURE prS_GetAllEmployeesByLeaveProfileHeaderId
GO
CREATE PROCEDURE prS_GetAllEmployeesByLeaveProfileHeaderId    
(
    @LeaveProfileHeaderId        BigInt
)
AS
BEGIN
    
    SELECT	EmployeeNumber,DisplayName EmployeeName, OUName 
    FROM 	C_Employee WITH (NOLOCK)
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId=C_OrganizationNode.OUId 
			INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
    WHERE	C_EmployeeLeaveProfile.LeaveProfileHeaderId =  @LeaveProfileHeaderId
    ORDER BY C_Employee.EmployeeNumber
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetAllEmployeesByScheduleRuleId')
	DROP PROC prS_GetAllEmployeesByScheduleRuleId
GO

CREATE PROCEDURE prS_GetAllEmployeesByScheduleRuleId    
(
    @scheduleRuleId        BigInt
)
AS
BEGIN
    
    SELECT EmployeeNumber,DisplayName EmployeeName, OUName 
    from   C_Employee 
       INNER JOIN C_OrganizationNode ON C_Employee.OUId=C_OrganizationNode.OUId 
    WHERE C_Employee.ScheduleRuleId =  @scheduleRuleId
    ORDER BY C_Employee.EmployeeNumber
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetAllShiftValidationCodes')
	DROP PROC prS_GetAllShiftValidationCodes
GO

----------------------------------------------------------------------------
-- Select a single record from S_ShiftValidationCodes
----------------------------------------------------------------------------
CREATE PROC prS_GetAllShiftValidationCodes
	
AS

SELECT	ErrorId,
	ValidationCode,
	ValidationDesc,
	ValidationMessage,
	ColorCode,
	CreatedBy,
	CreatedDate
FROM	S_ShiftValidationCodes


GO

 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetEmployeeLeavesByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetEmployeeLeavesByDateRange]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_GetEmployeeLeavesByDateRange]    
(
	@StartDate      datetime,
	@EndDate        datetime
)
AS
BEGIN
	SELECT	C_Employee.EmployeeNumber,
			S_EmployeeLeaves.LeaveId,
			S_EmployeeLeaves.EmployeeId,
			S_EmployeeLeaves.ExceptionCodeId,
			S_EmployeeLeaves.FromDate,
			S_EmployeeLeaves.EndDate,
			S_EmployeeLeaves.ApprovedBy,
			S_EmployeeLeaves.LeaveHours,
			S_EmployeeLeaves.ShiftId,
			S_EmployeeLeaves.Remarks,
			S_EmployeeLeaves.PickedTHP,
			S_EmployeeLeaves.Note,
			S_EmployeeLeaves.CreatedBy,
			S_EmployeeLeaves.CreatedDate,
			S_EmployeeLeaves.UpdatedBy,
			S_EmployeeLeaves.UpdatedDate,
			D_ExceptionCodes.ExcpetionCodeName,
			C_Employee.EmployeeNumber + ' ' + C_Employee.DisplayName as EmployeeName
	FROM	S_EmployeeLeaves WITH (NOLOCK) INNER JOIN C_OrganizationNode with (NOLOCK) ON S_EmployeeLeaves.OUId = C_OrganizationNode.OUId
			inner join D_ExceptionCodes with (nolock) on D_ExceptionCodes.ExceptionCodeId=S_EmployeeLeaves.ExceptionCodeId
			inner join C_Employee with (nolock) on C_Employee.EmployeeId=S_EmployeeLeaves.EmployeeId
	WHERE	CONVERT(DATE,S_EmployeeLeaves.EndDate) >= CONVERT(DATE,@StartDate)
	AND		CONVERT(DATE,S_EmployeeLeaves.FromDate) <= CONVERT(DATE,@EndDate)
	ORDER BY S_EmployeeLeaves.FromDate, C_Employee.EmployeeNumber
END

go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetEmployeeLeavesByIdDateRange')
	DROP PROC prS_GetEmployeeLeavesByIdDateRange
GO
 
Create PROCEDURE prS_GetEmployeeLeavesByIdDateRange    
(
	@LeaveDate		DateTime,
	@EmployeeId		BigInt
)
AS
BEGIN
	SELECT	S_EmployeeLeaves.LeaveId,
			S_EmployeeLeaves.EmployeeId,
			S_EmployeeLeaves.ExceptionCodeId,
			IsNull(S_EmployeeLeaves.ShiftId,0) ShiftId,
			S_EmployeeLeaves.Remarks,
			S_EmployeeLeaves.PickedTHP,
			S_EmployeeLeaves.Note,
			L_Leaveprofiles.DayCalculation
	FROM	S_EmployeeLeaves WITH (NOLOCK) 
			INNER JOIN L_EmployeeLeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.EmployeeId = S_EmployeeLeaves.EmployeeId 
			AND LeaveYear = Year(@LeaveDate) And L_EmployeeLeaveProfiles.ExceptionId = S_EmployeeLeaves.ExceptionCodeId
			INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_Leaveprofiles.LeaveProfileHeaderId 
			AND L_LeaveProfiles.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	WHERE	Convert(Date,FromDate)			=	Convert(Date,@LeaveDate)
	AND		S_EmployeeLeaves.EmployeeId		=	@EmployeeId
END
go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetEmployeeLeavesByLeaveId')
	DROP PROC prS_GetEmployeeLeavesByLeaveId
GO

----------------------------------------------------------------------------
-- Select a single record from S_EmployeeLeaves
----------------------------------------------------------------------------
CREATE PROC prS_GetEmployeeLeavesByLeaveId
	@LeaveId bigint
AS

SELECT	LeaveId,
	OUId,
	EmployeeId,
	S_EmployeeLeaves.ExceptionCodeId,
	FromDate,
	EndDate,
	ApprovedBy,
	LeaveHours,
	ShiftId,
	Remarks,
	PickedTHP,
	Note,
	D_ExceptionCodes.IsPaid,D_ExceptionCodes.ShiftLength
FROM	S_EmployeeLeaves WITH (NOLOCK)
inner join D_ExceptionCodes WITH (NOLOCK) on D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
WHERE 	LeaveId = @LeaveId

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prS_GetEmployeeShiftsByDate') AND type in (N'P', N'PC'))
	DROP PROCEDURE prS_GetEmployeeShiftsByDate
GO
 
CREATE PROCEDURE prS_GetEmployeeShiftsByDate
(
	@SelectedDate		DateTime
)
AS
BEGIN	 
	SELECT	ShiftId, EmployeeId
	From	S_Shifts WITH (NOLOCK)
	Where	Convert(Date,ActualStartTime) = Convert(Date,@SelectedDate)
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	--And		EmployeeId = 2155
	ORDER BY EmployeeId, ShiftId
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetEmployeeShiftsByEmployeeSchedulePeriod]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetEmployeeShiftsByEmployeeSchedulePeriod]
GO
/****** Object:  StoredProcedure [dbo].[prS_GetEmployeeShiftsByEmployeeSchedulePeriod]    Script Date: 7/10/2018 3:18:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[prS_GetEmployeeShiftsByEmployeeSchedulePeriod]   
(
	@StartDate	DateTime,
	@EndDate	DateTime,
	@EmployeeId Bigint
)
AS
BEGIN	 
	SELECT	C_Employee.EmployeeId, C_Employee.DisplayName, 
			S_Shifts.ShiftId, S_Shifts.ShiftBandId, D_ShiftBand.ShiftBandCode, D_ShiftBand.ColorCode,
			S_Shifts.CombinationShiftId, S_Shifts.Notes, S_Shifts.OnCallShift,
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime,
			S_Shifts.RoleId, D_Roles.RoleName, 
			S_Shifts.OUId, 
			C_OrganizationNode.OUName,
			S_Shifts.ShiftCost
	FROM	C_Employee with (nolock)
			INNER JOIN S_Shifts with (nolock) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_ShiftBand with (nolock) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
			INNER JOIN D_Roles with (nolock) ON S_Shifts.RoleId = D_Roles.RoleId
			INNER JOIN C_OrganizationNode with (nolock) ON C_OrganizationNode.OUId = S_Shifts.OUId
	WHERE	C_Employee.ActiveStatus = 1
	AND		D_ShiftBand.ActiveStatus = 1
	AND		Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.EmployeeId = @EmployeeId
	AND		S_Shifts.ReconStatusId = 1 AND S_Shifts.OnCallShift = 0
	And		Convert(Date,S_Shifts.ActualStartTime) NOT IN (SELECT D_PublicHolidays.HolidayDate From D_PublicHolidays)
	ORDER BY S_Shifts.ActualStartTime, C_Employee.EmployeeNumber
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetNoPublicHolidayBenefitEmployees')
	DROP PROC prS_GetNoPublicHolidayBenefitEmployees
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_GetNoPublicHolidayBenefitEmployees
----------------------------------------------------------------------------
CREATE PROC prS_GetNoPublicHolidayBenefitEmployees
AS
BEGIN
	SELECT  C_Employee.EmployeeId, C_Employee.OUId, 
			EmployeeNumber, DisplayName EmployeeName, OUName
	FROM    C_Employee INNER JOIN C_OrganizationNode ON C_Employee.OUId = C_OrganizationNode.OUId
	Where	C_Employee.EmployeeId NOT IN (SELECT EmployeeId From S_PublicholidayEmployeeList)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetRosterPatternByRosterGroupId')
	DROP PROC prS_GetRosterPatternByRosterGroupId
GO

----------------------------------------------------------------------------
-- Get Roster Pattern And Shift Details By Roster Group ID
----------------------------------------------------------------------------
CREATE PROC prS_GetRosterPatternByRosterGroupId
	@RosterGroupId	BigInt
AS
BEGIN
	-- Template Roster Details By Roster Group
	SELECT	S_TemplateRoster.TemplateId, 
			S_TemplateRoster.TemplateName, 
			S_TemplateRoster.TemplateDesc, 
			S_TemplateRoster.NoOfDays
	FROM	S_TemplateRoster 
			INNER JOIN S_TemplateRosterLine ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId  And S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId = @RosterGroupId 
	--AND		S_TemplateRosterLine.FirstPublishDate IS NOT NULL

	-- Get Template Roster Line
	SELECT	S_TemplateRosterLine.TemplateLineId,
			S_TemplateRosterLine.TemplateId,
			S_TemplateRosterLine.RosterGroupId,
			S_TemplateRosterLine.EmployeeId,
			S_TemplateRosterLine.FirstPublishDate FirstPublishedDate,
			S_TemplateRosterLine.LastPublishDate LastPublishedDate,
			S_TemplateRosterLine.LineNumber,
			S_TemplateRosterLine.LineType,
			S_TemplateRosterLine.PublishFrom,
			S_TemplateRosterLine.PublishTo
	FROM	S_TemplateRosterLine 
			INNER JOIN S_TemplateRoster ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId And S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId = @RosterGroupId 
	--AND		S_TemplateRosterLine.FirstPublishDate IS NOT NULL


	-- Template Roster Shifts
	SELECT	S_TemplateRoster_Shifts.TemplateId,
			S_TemplateRoster_Shifts.TemplateLineId,
			S_TemplateRoster_Shifts.ShiftId,
			S_TemplateRoster_Shifts.ShiftBandId,
			S_TemplateRoster_Shifts.RowNumber,
			S_TemplateRoster_Shifts.OnCallShift,
			S_TemplateRoster_Shifts.Notes
	FROM	S_TemplateRoster_Shifts 
			INNER JOIN S_TemplateRosterLine ON S_TemplateRosterLine.TemplateLineId = S_TemplateRoster_Shifts.TemplateLineId
			INNER JOIN S_TemplateRoster ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId AND S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId = @RosterGroupId 
	--AND		S_TemplateRosterLine.FirstPublishDate IS NOT NULL

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetSchedulePeriodByDate')
	DROP PROC prS_GetSchedulePeriodByDate
GO

----------------------------------------------------------------------------
-- Select a single record from S_SchedulePeriod
----------------------------------------------------------------------------
create PROC [dbo].[prS_GetSchedulePeriodByDate]
	@ShiftDate date,
	@ScheduleRuleId bigint,
	@OuId	BigInt
AS

SELECT	SchedulePeriodId,
	OUId,
	ScheduleRuleId,
	StartDate,
	EndDate,
	PeriodYear,
	PeriodNo,
	ReferenceNotes,
	CreatedBy,
	CreatedDate
FROM	S_SchedulePeriod
WHERE  ScheduleRuleId=@ScheduleRuleId and @ShiftDate between StartDate and EndDate
AND		( OUId = @OuId OR @OuId = 0)


go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetSchedulePeriodByOUId')
	DROP PROC prS_GetSchedulePeriodByOUId
GO

----------------------------------------------------------------------------
-- Select a single record from S_SchedulePeriod
----------------------------------------------------------------------------
CREATE PROC [dbo].[prS_GetSchedulePeriodByOUId]
	@OUId bigint,
	@ScheduleRuleId bigint
AS

SELECT	SchedulePeriodId,
	OUId,
	ScheduleRuleId,
	StartDate,
	EndDate,
	PeriodYear,
	PeriodNo,
	ReferenceNotes,
	CreatedBy,
	CreatedDate
FROM	S_SchedulePeriod
WHERE 	OUId=@OUId
and ScheduleRuleId=@ScheduleRuleId


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetSchedulePeriodByPublicHolidayDate')
	DROP PROC prS_GetSchedulePeriodByPublicHolidayDate
GO

----------------------------------------------------------------------------
-- Get List of Schedule Periods By Selected Public Holiday Date
----------------------------------------------------------------------------
create PROC prS_GetSchedulePeriodByPublicHolidayDate
	@ShiftDate	Date
AS
BEGIN
	SELECT	SchedulePeriodId,
			OUId,
			ScheduleRuleId,
			StartDate,
			EndDate,
			PeriodYear,
			PeriodNo,
			ReferenceNotes,
			CreatedBy,
			CreatedDate
	FROM	S_SchedulePeriod WITH (NOLOCK)
	WHERE	Convert(Date, @ShiftDate)	>= Convert(Date,StartDate)
	AND		Convert(Date, @ShiftDate)	<= Convert(Date,EndDate)
END
GO
/****** Object:  StoredProcedure [dbo].[prD_GetAllEmailTemplates]  ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetSchedulePeriodByScheduleRuleId]') AND type in (N'P', N'PC'))
DROP PROCEDURE prS_GetSchedulePeriodByScheduleRuleId
GO

CREATE PROCEDURE [dbo].[prS_GetSchedulePeriodByScheduleRuleId]    
(
	@ScheduleRuleId	BigInt
)
AS
BEGIN
	SELECT	StartDate, EndDate, PeriodYear, PeriodNo, CreatedBy, CreatedDate 
	FROM	S_SchedulePeriod Where ScheduleRuleId = @ScheduleRuleId
	ORDER BY StartDate DESC
END

GO
/****** Object:  StoredProcedure [dbo].[prS_GetSchedulePeriodByScheduleRuleId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetSchedulePeriodByScheduleRuleId]') AND type in (N'P', N'PC'))

DROP PROCEDURE [prS_GetSchedulePeriodByScheduleRuleId]
GO



CREATE PROCEDURE [dbo].[prS_GetSchedulePeriodByScheduleRuleId]    
(	
	@ScheduleRuleId BigInt
)
AS
BEGIN 
      Select  StartDate, EndDate, PeriodYear, PeriodNo, CreatedBy, CreatedDate
      from S_SchedulePeriod where ScheduleRuleId=@ScheduleRuleId
	  ORDER BY StartDate DESC

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetSchedulePeriodsShiftsBetweenDatesByOUId')
	DROP PROC prS_GetSchedulePeriodsShiftsBetweenDatesByOUId
GO

----------------------------------------------------------------------------
-- Get List of Schedule Periods Between Selected Date Range By OUId
----------------------------------------------------------------------------
create PROC prS_GetSchedulePeriodsShiftsBetweenDatesByOUId
	@OUId					BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime,
	@EmploymentBasisCodes   nVarchar(50)
AS
BEGIN
	-- 1. Retrieve Shceudle Periods Between Selected Dates
	SELECT	SchedulePeriodId,
			OUId,
			ScheduleRuleId,
			StartDate,
			EndDate,
			PeriodYear,
			PeriodNo,
			ReferenceNotes,
			CreatedBy,
			CreatedDate
	FROM	S_SchedulePeriod WITH (NOLOCK)
	WHERE	Convert(Date, EndDate)		>= Convert(Date,@StartDate)
	AND		Convert(Date, StartDate)	<= Convert(Date,@EndDate)
	AND		S_SchedulePeriod.OUId		=	@OUId 
	AND		S_SchedulePeriod.ScheduleRuleId = 2 --TODO: Change This Value as Procedure Parameter

	-- 2. Retrieve List Of Employees Between Min And Max Dates Of Schedule Period
	;WITH SchedulePeriods (StartDate, EndDate) AS 
	(
		SELECT	Min(StartDate) StartDate, Max(EndDate) EndDate
		FROM	S_SchedulePeriod WITH (NOLOCK)
		WHERE	(OUId		=	@OuId OR @OuId = 0)
		AND		Convert(Date, EndDate)		>= Convert(Date,@StartDate)
		AND		Convert(Date, StartDate)	<= Convert(Date,@EndDate)
		AND		S_SchedulePeriod.ScheduleRuleId = 2 --TODO: Change This Value as Procedure Parameter
	) 
	SELECT	ShiftId, C_Employee.EmployeeId,  C_Employee.ScheduleRuleId, S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
	WHERE	S_Shifts.OUId		=	@OuId
	AND		Convert(Date,ActualStartTime) >= Convert(Date,(SELECT StartDate FROM SchedulePeriods))
	AND		Convert(Date,ActualStartTime) <= Convert(Date,(SELECT EndDate FROM SchedulePeriods))
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)		
	AND		D_EmploymentBasis.EmploymentBasisId =2 -- IN (SELECT * FROM fnStringToTable(@EmploymentBasisCodes))
	AND		S_Shifts.ShiftId NOT IN (
										SELECT	ShiftId 
										FROM	S_EmployeeLeaves WITH (NOLOCK)
										WHERE	Convert(Date,FromDate) >= Convert(Date,(SELECT StartDate FROM SchedulePeriods))
										AND		Convert(Date,FromDate) <= Convert(Date,(SELECT EndDate FROM SchedulePeriods))
										AND		ShiftId IS NOT NULL
									)
	AND		(S_Shifts.InTime IS NOT NULL OR S_Shifts.OutTime IS NOT NULL)

	SELECT	Count(C_Employee.EmployeeId) AS TotalEmployeesCount
	FROM	C_Employee WITH (NOLOCK) 
			INNER JOIN D_EmploymentBasis WITH (NOLOCK)  ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
	WHERE	(D_EmploymentBasis.EmploymentBasisId IN (SELECT * FROM fnStringToTable(@EmploymentBasisCodes)) 
			 OR @EmploymentBasisCodes = '')
	AND		C_Employee.ActiveStatus = 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftByEmployeeIdAndDateRange')
	DROP PROC prS_GetShiftByEmployeeIdAndDateRange
GO

----------------------------------------------------------------------------
-- Select a single record from S_EmployeeLeaves
----------------------------------------------------------------------------

 
create PROCEDURE [dbo].[prS_GetShiftByEmployeeIdAndDateRange]   
(	
	@EmployeeId				 BigInt,
	@StartDate	DateTime,
	@EndDate	DateTime
	
)
AS
BEGIN	 
	
	SELECT * FROM S_Shifts WITH (NOLOCK)
	WHERE	EmployeeId=@EmployeeId	
	AND 	(Convert(Date,ShiftStartTime) >= CONVERT(Date, @StartDate)
	AND 	Convert(Date,ShiftStartTime) <= CONVERT(Date, @EndDate))
	AND		(S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId IS NULL)

END

GO

/****** Object:  StoredProcedure [dbo].[prS_GetShiftExceptionsByShiftId]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetShiftExceptionsByShiftId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetShiftExceptionsByShiftId]
GO

CREATE PROCEDURE [dbo].[prS_GetShiftExceptionsByShiftId]    
(
	@ShiftId	BigInt
)
AS
BEGIN
	SELECT	ShiftExceptionId,
			ShiftId,
			S_ShiftExceptions.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
			StartTime,
			EndTime,
			ApprovalStatus,
			S_ShiftExceptions.Remarks,
			S_ShiftExceptions.CreatedBy,
			S_ShiftExceptions.CreatedDate,
			S_ShiftExceptions.UpdatedBy,
			S_ShiftExceptions.UpdatedDate
	FROM	S_ShiftExceptions
			INNER JOIN D_ExceptionCodes ON S_ShiftExceptions.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHERE	S_ShiftExceptions.ShiftId = @ShiftId
	ORDER BY S_ShiftExceptions.StartTime
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetShiftForTHPProcess]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetShiftForTHPProcess]
GO
 
CREATE PROCEDURE [dbo].[prS_GetShiftForTHPProcess]
	@ShiftDate		DateTime
	
AS
	
	SELECT	ShiftId, C_Employee.EmployeeId, ActualStartTime
	FROM	S_THPSettings WITH (NOLOCK)
			INNER JOIN S_THPSettingRosterGroups WITH (NOLOCK) on S_THPSettingRosterGroups.THPSettingId = S_THPSettings.THPSettingId
			INNER JOIN S_RosterGroup WITH (NOLOCK) on S_RosterGroup.RosterGroupId = S_THPSettingRosterGroups.RosterGroupId
			INNER JOIN S_RosterGroupDetails WITH (NOLOCK) on S_RosterGroupDetails.RosterGroupId = S_RosterGroup.RosterGroupId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_RosterGroupDetails.EmployeeId
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId	
	WHERE	Convert(Date,ActualStartTime) < CONVERT(Date, @ShiftDate)
	AND		PickedByTHP = 0 and (ShiftBandId !=CombinationShiftId OR CombinationShiftId IS NULL)
	ORDER BY  ActualStartTime

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftHoursByShiftId')
	DROP PROC prS_GetShiftHoursByShiftId
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeDetails
----------------------------------------------------------------------------
CREATE PROC prS_GetShiftHoursByShiftId
	@ShiftId bigint
	
AS

declare @ShiftHour Decimal(18,2) 
declare	@ActivityHour Decimal(18,2) 

 select @ShiftHour = DATEDIFF ( hour , ActualStartTime , ActualEndTime )  from S_Shifts WITH (NOLOCK)
 where ShiftId = @ShiftId

 select @ActivityHour = Sum(DATEDIFF ( hour , StartTime , EndTime )) from J_Activity WITH (NOLOCK)
where ShiftId = @ShiftId
 --print  @ShiftHour
 select @ShiftHour 'ShiftHour', @ActivityHour 'ActivityHour'

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftsBetweenDatesByEmploymentBasis')
	DROP PROC prS_GetShiftsBetweenDatesByEmploymentBasis
GO

----------------------------------------------------------------------------
-- Get Shifts Between Dates And Filtered By Employment Basis
----------------------------------------------------------------------------
create PROC prS_GetShiftsBetweenDatesByEmploymentBasis
	@StartDate					Date,
	@EndDate					Date,
	@OUId						BigInt,
	@ScheduleRuleId				BigInt,
	@FilteredEmploymentBasis	nVarchar(max)
AS
BEGIN
	SELECT 	ShiftId, C_Employee.EmployeeId,  C_Employee.ScheduleRuleId, S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, 
			S_PublicholidayEmployeeList.TypeId PublicHolidayTypeId, 
			S_PublicholidayEmployeeList.TypeDesc PublicHolidayTypeDesc
	FROM	S_Shifts WITH (NOLOCK)  INNER JOIN C_Employee ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
			LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = C_Employee.EmployeeId
			INNER JOIN S_SchedulePeriod WITH (NOLOCK) ON C_Employee.ScheduleRuleId = S_SchedulePeriod.ScheduleRuleId 
						AND	S_SchedulePeriod.OUId = S_Shifts.OUId 
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_SHifts.OUId = @OUId
	AND		Convert(Date,S_SchedulePeriod.StartDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_SchedulePeriod.EndDate) <= Convert(Date,@EndDate)
	AND		S_SchedulePeriod.OUId = @OUId	
	AND		S_SchedulePeriod.ScheduleRuleId	=	@ScheduleRuleId
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)		
	AND		(D_EmploymentBasis.EmploymentBasisCode IN (SELECT * FROM fnStringToTable(@FilteredEmploymentBasis)) OR @FilteredEmploymentBasis = '')
	AND		S_Shifts.ShiftId NOT IN (
										SELECT	ShiftId 
										FROM	S_EmployeeLeaves WITH (NOLOCK)
										WHERE	Convert(Date,FromDate) >= Convert(Date,@StartDate)
										AND		Convert(Date,FromDate) <= Convert(Date,@EndDate)
										AND		ShiftId IS NOT NULL
									)
	AND		(S_Shifts.InTime IS NOT NULL OR S_Shifts.OutTime IS NOT NULL)
	--AND		S_Shifts.EmployeeId = 929 
	ORDER	BY S_Shifts.EmployeeId, ActualStartTime
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetShiftsByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetShiftsByDateRange]
GO
 
CREATE PROCEDURE [dbo].[prS_GetShiftsByDateRange]
	@OUId			bigint,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@Skills			nVarchar(max),
	@EquipmentTypes	nVarchar(max),
	@Equipments		nVarchar(max),
	@RoleGroups		nVarchar(max),
	@Roles			nVarchar(max),
	@Employees		nVarchar(max)
AS
DECLARE @__SkillsId BIGINT = 0, @__EquipmentTypesId BIGINT = 0, @__EquipmentsId BIGINT = 0, @__RoleGroupsId BIGINT = 0, @__RolesId BIGINT = 0, @__EmployeeId BIGINT = 0
BEGIN
	
	SELECT TOP 1 @__skillsId = sID FROM fnStringToTable(@Skills)
	
	SELECT TOP 1 @__EquipmentTypesId = sID FROM fnStringToTable(@EquipmentTypes)

	SELECT TOP 1 @__EquipmentsId = sID FROM fnStringToTable(@Equipments)

	SELECT TOP 1 @__RoleGroupsId = sID FROM fnStringToTable(@RoleGroups)
	
	SELECT TOP 1 @__RolesId = sID FROM fnStringToTable(@Roles)

	SELECT TOP 1 @__EmployeeId = sID FROM fnStringToTable(@Employees)

	SELECT	S_Shifts.ShiftId,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			S_Shifts.RoleId,
			S_SHifts.EmployeeId,
			LTrim(RTrim(C_Employee.EmployeeNumber)) EmployeeNumber,
			LTrim(RTrim(C_Employee.DisplayName)) EmployeeName,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandId,
			D_ShiftBand.ShiftBandCode,
			D_ShiftBand.ColorCode ShiftBandColor,
			IsNull(J_Activity.ActivityId,0) ActivityId,
			J_Activity.OUId,
			J_Activity.SkillId,
			D_Roles.RoleName,
			D_Skill.Skill SkillCode,
			D_Skill.ColorCode SkillColor,
			J_Activity.StartTime ActivityStart,
			J_Activity.EndTime ActivityEnd,
			CraneSchedule.ScheduleId CraneScheduleId,
			EquipmentSchedule.ScheduleId EquipmentScheduleId,
			J_Activity.WorkType, J_Activity.AllocationNo
			--M_Equipments.EquipmentName
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN D_SHiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId
				AND (D_Roles.RoleId IN (SELECT * FROM fnStringToTable(@Roles)) OR @__RolesId = 0) -- Roles Filter
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
				AND (C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@Employees)) OR @__EmployeeId = 0) -- Employee Filter
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId 
				AND C_EmployeeRoles.IsPrimaryRole = 1
			LEFT OUTER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId 
				AND (J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__SkillsId = 0) -- Skills Filter
			LEFT OUTER JOIN J_ActivityAttributes CraneSchedule WITH (NOLOCK) ON CraneSchedule.ActivityId = J_Activity.ActivityId AND J_Activity.WorkType=1 
			LEFT OUTER JOIN J_ActivityAttributes EquipmentSchedule WITH (NOLOCK) ON EquipmentSchedule.ActivityId = J_Activity.ActivityId
				AND J_Activity.WorkType=2 
			LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentSchedule.ActivityId
				AND (M_EquipmentSchedule.EquipmentId IN (SELECT * FROM fnStringToTable(@Equipments)) OR @__EquipmentsId = 0) -- Equipment Filter
				AND (M_EquipmentSchedule.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes)) OR @__EquipmentTypesId = 0) -- Equipment Type Filter
			--LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId 
			--	AND (M_Equipments.EquipmentId IN (SELECT * FROM fnStringToTable(@Equipments)) OR @__EquipmentsId = 0) -- Equipment Filter
			--	AND (M_Equipments.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes)) OR @__EquipmentTypesId = 0) -- Equipment Type Filter
			LEFT OUTER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
				AND (J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@Skills)) OR @__SkillsId = 0) -- Skills Filter
	WHERE 	S_Shifts.OUId = @OUId
	AND		(S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId IS NULL)
	AND 	(ActualEndTime > CONVERT(DATETIME, @StartDate)
	AND 	ActualStartTime < CONVERT(DATETIME, @EndDate))
	AND		S_SHIFTS.EmployeeId NOT IN ( SELECT EmployeeId FROM S_EmployeeLeaves WITH (NOLOCK)
					   WHERE EndDate >= Convert(Date,@StartDate) 
					   AND FromDate <= Convert(Date,@EndDate) AND OUId = @OUId)
	ORDER BY ShiftId, ActivityStart
	/*AND		NOT EXISTS (	SELECT	ShiftId  
							FROM	J_Activity 
							WHERE	J_Activity.ShiftId = S_Shifts.ShiftId 
							AND		S_Shifts.OUId = @OUId
							AND 	(ActualEndTime > CONVERT(DATETIME, @StartDate)
							AND 	ActualStartTime < CONVERT(DATETIME, @EndDate))
						)*/


END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetShiftsByEmployeeIdAndDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetShiftsByEmployeeIdAndDateRange]
GO
/****** Object:  StoredProcedure [dbo].[prS_GetShiftsByEmployeeIdAndDateRange]    Script Date: 7/10/2018 3:18:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE PROCEDURE [dbo].[prS_GetShiftsByEmployeeIdAndDateRange]   
(
	@EmployeeId	BigInt,
	@StartDate	DateTime,
	@EndDate	DateTime
)
AS
BEGIN	 
	SELECT	Convert(nVarchar,S_Shifts.ShiftId) id,
			D_ShiftBand.ShiftBandCode + ' <br/> [ ' + Convert(nVarchar(5),Convert(Time,S_Shifts.ShiftStartTime)) + ' - ' + Convert(nVarchar(5),Convert(Time,S_Shifts.ShiftEndTime)) + ' ] ' as text,
			'Shift Details' details,
			Convert(nVarchar,Convert(Date,S_Shifts.ActualStartTime)) as 'start_date',
			IIF(
				Convert(Date,S_Shifts.ActualEndTime) = Convert(Date,S_Shifts.ActualStartTime), 
				Convert(nVarchar,DATEADD(DAY,1,Convert(Date,S_Shifts.ActualEndTime))),
				Convert(nVarchar,Convert(Date,S_Shifts.ActualEndTime))) as 'end_date',
			--Convert(nVarchar,Convert(Date,S_Shifts.ActualEndTime)) as 'end_date',
			D_ShiftBand.ColorCode color,
			'' textColor,
			'Shift' as 'type'
	FROM	S_Shifts WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	C_Employee.EmployeeId = @EmployeeId
	AND		Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	UNION ALL
	SELECT	Convert(nVarchar,S_Shifts.ShiftId) + 'TA' id, 
			IsNull('<i class="fas fa-angle-right"></i> [ ' + Convert(nVarchar(5),Convert(Time,S_Shifts.InTime)) + ' ] <br/>','')  +  
			IsNull('<i class="fas fa-angle-left"></i> [ ' + Convert(nVarchar(5),Convert(Time,S_Shifts.OutTime)) + ' ]','') as text,
			'Time Attendance' details,
			Convert(nVarchar,Convert(Date,S_Shifts.ActualStartTime)) as 'start_date',
			IIF(
				Convert(Date,S_Shifts.ActualEndTime) = Convert(Date,S_Shifts.ActualStartTime), 
				Convert(nVarchar,DATEADD(DAY,1,Convert(Date,S_Shifts.ActualEndTime))),
				Convert(nVarchar,Convert(Date,S_Shifts.ActualEndTime))) as 'end_date',
			--Convert(nVarchar,Convert(Date,S_Shifts.ActualEndTime)) as 'end_date',
			TA_ExceptionCodes.ColorCode color,
			'' textColor,
			'TA' as 'type'
	FROM	S_Shifts  WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN TA_ExceptionCodes WITH (NOLOCK) ON TA_ExceptionCodes.TAExceptionId = S_Shifts.ReconStatusId
	WHERE	C_Employee.EmployeeId = @EmployeeId
	AND		Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	AND		(S_Shifts.InTime IS NOT NULL OR S_Shifts.OutTime IS NOT NULL)
	UNION ALL
	SELECT	Convert(nVarchar,S_EmployeeLeaves.LeaveId) + 'LV' id,
			D_ExceptionCodes.ExcpetionCodeName as text,
			'Leave Details' details,
			Convert(nVarchar,Convert(Date,S_EmployeeLeaves.FromDate)) as 'start_date',
			Convert(nVarchar,Convert(Date,S_EmployeeLeaves.FromDate)) as 'end_date',
			D_ExceptionCodes.ColorCode color,
			'' textColor, 
			'LEAVE' as 'type'
	FROM	S_EmployeeLeaves WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON S_EmployeeLeaves.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	WHERE	C_Employee.EmployeeId = @EmployeeId
	AND		Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@EndDate)
	AND		S_EmployeeLeaves.ShiftId IS NOT NULL
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftsCountBetweenDatesByEmployeeId')
	DROP PROC prS_GetShiftsCountBetweenDatesByEmployeeId
GO

CREATE PROC prS_GetShiftsCountBetweenDatesByEmployeeId
	@EmployeeId			Bigint,
	@StartDate			DateTime,
	@EndDate			DateTime
AS
BEGIN
	SELECT	Count(*) ShiftsCount
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	Convert(Date,S_Shifts.ActualStartTime)	>= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.EmployeeId = @EmployeeId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftStartAndEndByEmployeeIdAndDate')
	DROP PROC prS_GetShiftStartAndEndByEmployeeIdAndDate
GO

----------------------------------------------------------------------------
-- Select a single record from S_Shifts
----------------------------------------------------------------------------

 
create PROCEDURE [dbo].[prS_GetShiftStartAndEndByEmployeeIdAndDate]   
(	
	@EmployeeId		BigInt,
	@ShiftDate		DateTime			
	
)
AS
BEGIN	 
	
	SELECT	ShiftId, ActualStartTime, ActualEndTime 
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	EmployeeId=@EmployeeId	
	AND 	Convert(Date,ShiftStartTime) = CONVERT(Date, @ShiftDate)
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetShiftValidationsByDateRange')
	DROP PROC prS_GetShiftValidationsByDateRange
GO

CREATE PROC prS_GetShiftValidationsByDateRange
(
	@StartDate		DateTime,
	@EndDate		DateTime,
	@OUId			BigInt
)
AS

SELECT  S_ShiftValidations.ValidationId,
		S_ShiftValidations.ShiftId,
		S_ShiftValidations.ShiftDate,
		S_ShiftValidations.SchedulePeriodId,
		S_ShiftValidations.IsError,
		S_ShiftValidations.ErrorId,
		S_ShiftValidations.ErrorDesc,
		S_ShiftValidations.EmployeeId,
		S_ShiftValidations.CreatedDate,
		S_ShiftValidations.CreatedBy,
		S_ShiftValidationCodes.ColorCode
FROM	S_ShiftValidations WITH (NOLOCK) 
		INNER JOIN S_ShiftValidationCodes WITH (NOLOCK) ON S_ShiftValidations.ErrorId = S_ShiftValidationCodes.ErrorId
		INNER JOIN S_Shifts WITH (NOLOCK) ON S_ShiftValidations.ShiftId = S_Shifts.ShiftId AND S_Shifts.OUId = @OUId
WHERE	(Convert(DATE,ShiftDate) >= CONVERT(DATE, @StartDate)
AND 	Convert(DATE, ShiftDate) <= CONVERT(DATE, @EndDate))

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetSkillAndLeaveCount')
	DROP PROC prS_GetSkillAndLeaveCount
GO
/****** Object:  StoredProcedure [dbo].[prS_GetSkillAndLeaveCount]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC prS_GetSkillAndLeaveCount
(
	@StartDate			DateTime,
	@EndDate			DateTime,			
	@RosterGroupItems	nVarchar(max),
	@RoleGroupItems		nVarchar(max),
	@OUID				BigInt
)
AS
BEGIN
	SELECT (D_Skill.Skill) SkillName,
			D_Skill.SkillId,
			Count(S_Shifts.EmployeeId) SkillCount,
			Convert(Date,S_Shifts.ActualStartTime) ShiftDate
	From    S_Shifts
			INNER JOIN D_RoleSkill ON S_Shifts.RoleId = D_RoleSkill.RoleId
			INNER JOIN D_Skill ON D_SKill.SkillId = D_RoleSkill.SkillId
	WHERE	Convert(Date,ActualStartTime)	>=	Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime)	<=	Convert(Date,@EndDate)
	AND		S_Shifts.OUId					=	@OUID
	GROUP BY D_Skill.Skill,D_Skill.SkillId,Convert(Date,S_Shifts.ActualStartTime)
	ORDER BY D_Skill.Skill,Convert(Date,S_Shifts.ActualStartTime)
		
	SELECT (D_ExceptionCodes.ExceptionCodeDesc) ExceptionName,
			S_EmployeeLeaves.ExceptionCodeId,
			Count(D_ExceptionCodes.ExceptionCodeId) LeaveCount,
			Convert(Date,S_EmployeeLeaves.FromDate) LeaveDate
	From    S_EmployeeLeaves
			INNER JOIN D_ExceptionCodes ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
	WHERE	Convert(Date,FromDate)	>=	Convert(Date, @StartDate)
	AND		Convert(Date,FromDate)	<=	Convert(Date, @EndDate)
	AND		S_EmployeeLeaves.OUId	=	@OUID
	GROUP BY S_EmployeeLeaves.ExceptionCodeId, D_ExceptionCodes.ExceptionCodeDesc,S_EmployeeLeaves.LeaveId,Convert(Date,S_EmployeeLeaves.FromDate)
	ORDER BY D_ExceptionCodes.ExceptionCodeDesc,Convert(Date,S_EmployeeLeaves.FromDate)
END	
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetTHPEmployeePeriodsByEmployeeIdAndShiftDate')
	DROP PROC prS_GetTHPEmployeePeriodsByEmployeeIdAndShiftDate
GO

----------------------------------------------------------------------------
-- Select a single record from S_THPEmployeePeriods
----------------------------------------------------------------------------
CREATE PROC prS_GetTHPEmployeePeriodsByEmployeeIdAndShiftDate
	@EmployeeId bigint,
	@ShiftDate DateTime
AS

SELECT	THPPeriodId,
	OUId,
	THPSettingsId,
	EmployeeId,
	PeriodStart,
	PeriodEnd,
	PeriodUnit,
	PeriodLength,
	ShiftCounter,
	LeaveCounter,
	ActivityCounter,
	NormalHourCounter,
	OTHourCounter,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	S_THPEmployeePeriods WITH (NOLOCK)
WHERE 	EmployeeId=@EmployeeId
and (@ShiftDate between PeriodStart and PeriodEnd)

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetTHPEmployeePeriodsByEmployeeId_Top1')
	DROP PROC prS_GetTHPEmployeePeriodsByEmployeeId_Top1
GO

----------------------------------------------------------------------------
-- Select a single record from S_THPEmployeePeriods
----------------------------------------------------------------------------
CREATE PROC prS_GetTHPEmployeePeriodsByEmployeeId_Top1
	@EmployeeId bigint
AS

SELECT	top 1 THPPeriodId,
	OUId,
	THPSettingsId,
	EmployeeId,
	PeriodStart,
	PeriodEnd,
	PeriodUnit,
	PeriodLength,
	ShiftCounter,
	LeaveCounter,
	ActivityCounter,
	NormalHourCounter,
	OTHourCounter,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	S_THPEmployeePeriods WITH (NOLOCK)
WHERE 	EmployeeId = @EmployeeId
order by PeriodEnd desc

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetTHPSettingRosterGroupsByTHPSettingId')
	DROP PROC prS_GetTHPSettingRosterGroupsByTHPSettingId
GO

----------------------------------------------------------------------------
-- Select a single record from S_THPSettingRosterGroups
----------------------------------------------------------------------------
CREATE PROC prS_GetTHPSettingRosterGroupsByTHPSettingId
	@THPSettingId bigint
AS

SELECT	THPEMPId,
	THPSettingId,
	RosterGroupId,
	CreatedBy,
	CreatedDate
FROM	S_THPSettingRosterGroups WITH (NOLOCK)
WHERE 	THPSettingId = @THPSettingId

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetTHPSettingsByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetTHPSettingsByEmployeeId]
GO
 

----------------------------------------------------------------------------
-- Select a single record from S_THPEmployeePeriods
----------------------------------------------------------------------------
Create PROC [dbo].[prS_GetTHPSettingsByEmployeeId]
	@EmployeeId bigint
AS

begin

select S_THPSettings.OUId, EmployeeId,S_THPSettings.THPSettingId 
from S_THPSettings WITH (NOLOCK)
inner join S_THPSettingRosterGroups WITH (NOLOCK) on S_THPSettingRosterGroups.THPSettingId = S_THPSettings.THPSettingId
inner join S_RosterGroup WITH (NOLOCK) on S_RosterGroup.RosterGroupId = S_THPSettingRosterGroups.RosterGroupId
inner join S_RosterGroupDetails WITH (NOLOCK) on S_RosterGroupDetails.RosterGroupId = S_RosterGroup.RosterGroupId
where EmployeeId=@EmployeeId

end 

GO


GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetTHPSettingsByOUId')
	DROP PROC prS_GetTHPSettingsByOUId
GO

----------------------------------------------------------------------------
-- Select a single record from S_THPSettings
----------------------------------------------------------------------------
CREATE PROC prS_GetTHPSettingsByOUId
	@OUId			bigint,
	@THPSettingsId	BigInt
AS

SELECT	THPSettingId,
		OUId,
		THPSettingsName,
		StartDate,
		PeriodUnit,
		PeriodLength,
		CreatedBy,
		CreatedDate,
		UpdatedBy,
		UpdatedDate
FROM	S_THPSettings WITH (NOLOCK)
WHERE 	OUId = @OUId
AND		(THPSettingId = @THPSettingsId OR @THPSettingsId = 0)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetTHPValueFromPeriodByEmployeeId')
	DROP PROC prS_GetTHPValueFromPeriodByEmployeeId
GO


----------------------------------------------------------------------------
-- Select a single record from S_THPEmployeePeriods
----------------------------------------------------------------------------
Create PROC [dbo].[prS_GetTHPValueFromPeriodByEmployeeId]
	@EmployeeId bigint,
	@ShiftDate Date
AS

Declare @PeriodStartDate datetime
Declare @PeriodEndTime datetime


SELECT	@PeriodStartDate = PeriodStart,
	@PeriodEndTime = PeriodEnd
FROM	S_THPEmployeePeriods WITH (NOLOCK)
WHERE 	EmployeeId = @EmployeeId
and (PeriodStart<=  @ShiftDate and PeriodEnd>=@ShiftDate)
order by PeriodEnd desc


select sum(shiftcounter) ShiftCounter,sum(ActivityCounter)  ActivityCounter 
from S_THPEmployeeDetails WITH (NOLOCK)
where EmployeeId=@EmployeeId
and CONVERT(date,ShiftDate) >= convert(date,@PeriodStartDate) and CONVERT(date,ShiftDate) <= convert(date,@PeriodEndTime)



GO
/****** Object:  StoredProcedure [dbo].[prS_PublicHolidayAudit]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_PublicHolidayAudit]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_PublicHolidayAudit]
GO

CREATE PROCEDURE [dbo].[prS_PublicHolidayAudit] (
	  @employeeId      bigInt,
	  @holidayDate     datetime
)
AS
BEGIN
    Select	C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_OrganizationNode.OUName OUName,
			D_PublicHolidays.HolidayName,
			D_PublicHolidays.HolidayDate,
			L_PublicHolidayProcessAudit.ActionType,
			L_PublicHolidayProcessAudit.ActionDesc,
			L_PublicHolidayProcessAudit.ActionCode,
			L_PublicHolidayProcessAudit.ActionLog,
			L_PublicHolidayProcessAudit.ProcessDate,
			L_PublicHolidayProcessAudit.EmployeeId
    FROM	L_PublicHolidayProcessAudit WITH (NOLOCK)
			INNER JOIN D_PublicHolidays WITH (NOLOCK) ON D_PublicHolidays.PublicHolidayId=L_PublicHolidayProcessAudit.PublicHolidayId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId=L_PublicHolidayProcessAudit.EmployeeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	WHERE	CONVERT(DATE,D_PublicHolidays.HolidayDate)=CONVERT(DATE,@holidayDate)
	AND		(L_PublicHolidayProcessAudit.EmployeeId=@employeeId OR @employeeId=0)	
	ORDER By L_PublicHolidayProcessAudit.ProcessDate
	
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_PublicHolidayEmployeDiciplinarySel]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prS_PublicHolidayEmployeDiciplinarySel]
GO

CREATE PROCEDURE [dbo].[prS_PublicHolidayEmployeDiciplinarySel]    
AS
BEGIN
	-- Select Disciplinary Action Details For Those Employees who are in Public Holiday Type
	SELECT	C_Employee.EmployeeId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			C_EmployeeDiciplinary.StartDate DisciplinaryActionStartDate,
			C_EmployeeDiciplinary.EndDate DisciplinaryActionEndDate
	FROM	S_PublicHolidayEmployeeList WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON S_PublicHolidayEmployeeList.EmployeeId = C_Employee.EmployeeId
			INNER JOIN C_EmployeeDiciplinary WITH (NOLOCK) ON C_EmployeeDiciplinary.EmployeeId = C_Employee.EmployeeId
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_PublicHolidayEmployeesSel]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prS_PublicHolidayEmployeesSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_PublicHolidayEmployeesSel]    
(
	@TypeId	Int,
	@OUId	BigInt
)
AS
BEGIN
	-- Get Public Holiday Employee Details
	SELECT	S_PublicHolidayEmployeeList.TranId,
			S_PublicHolidayEmployeeList.EmployeeId,
			S_PublicHolidayEmployeeList.TypeId,
			S_PublicHolidayEmployeeList.TypeDesc,
			S_PublicHolidayEmployeeList.CreatedBy,
			S_PublicHolidayEmployeeList.CreatedDate,
			C_Employee.RosterGroupId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			S_RosterGroup.GroupName RosterGroupName,
			D_Roles.RoleId PrimaryRoleId,
			D_Roles.RoleDesc PrimaryRoleDescription,
			Convert(Bit,0) IsUpdated,
			D_EmploymentBasis.EmploymentBasisCode
			--C_EmployeeDiciplinary.StartDate DisciplinaryActionStartDate,
			--C_EmployeeDiciplinary.EndDate DisciplinaryActionEndDate
	FROM	S_PublicHolidayEmployeeList WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON S_PublicHolidayEmployeeList.EmployeeId = C_Employee.EmployeeId
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId 
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
			--LEFT OUTER JOIN C_EmployeeDiciplinary WITH (NOLOCK) ON C_EmployeeDiciplinary.EmployeeId = C_Employee.EmployeeId
	WHERE	S_PublicHolidayEmployeeList.TypeId = @TypeId OR @TypeId = 0
	--AND		EmployeeNumber IN ('14-00335') --EmployeeNumber IN ('14-04475') --IN ('14-03828') --IN ('14-04163', '14-01196')
END
GO
/****** Object:  StoredProcedure [dbo].[prS_PublishRosterDetailsIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_PublishRosterDetailsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_PublishRosterDetailsIns]
GO

/****** Object:  StoredProcedure [dbo].[prS_PublishRosterDetailsIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[prS_PublishRosterDetailsIns]    
(
	@PublishId		BigInt,
	@TemplateLineId	BigInt,
	@TemplateFrom	DateTime,
	@TemplateTo		DateTime,
	@PublishFrom	DateTime,
	@PublishTo		DateTime,
	@ProcessStatus	int,
	@ProcessStart	DateTime,
	@Notes			nVarchar(500),
	@DefaultForLine	Bit
)
AS
BEGIN

	INSERT INTO S_PublishRosterDetails
	(PublishId, TemplateLineId, TemplateFrom, TemplateTo, PublishFrom, PublishTo, 
	 ProcessStatus, ProcessStart, ProcessEnd, Notes, DefaultForLine)
	VALUES( @PublishId, @TemplateLineId, @TemplateFrom, @TemplateTo, @PublishFrom, @PublishTo, @ProcessStatus,
			@ProcessStart, GETDATE(), @Notes, @DefaultForLine)

	SELECT SCOPE_IDENTITY();
END
GO

/****** Object:  StoredProcedure [dbo].[prS_PublishRosterIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_PublishRosterIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_PublishRosterIns]
GO

/****** Object:  StoredProcedure [dbo].[prS_PublishRosterIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_PublishRosterIns]    
(
	@TemplateId		BigInt,
	@PublishDate	DateTime,
	@PublishUser	nVarchar(50),
	@ProcessStatus	int,
	@ProcessStart	DateTime,
	@Notes			nVarchar(500)
)
AS
BEGIN

	INSERT INTO S_PublishRoster
	(TemplateId, PublishDate, PublishUser, ProcessStatus, ProcessStart, ProcessEnd, Notes)
	VALUES(@TemplateId, @PublishDate, @PublishUser, @ProcessStatus, @ProcessStart, GETDATE(), @Notes)

	SELECT SCOPE_IDENTITY();
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupDel]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupDel]    Script Date: 7/6/2018 2:26:55 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_RosterGroupDel]    
(
	@RosterGroupId	Int,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	S_RosterGroup
	SET		ActiveStatus	=	0,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	RosterGroupId		=@RosterGroupId

	UPDATE	C_Employee 
	SET		RosterGroupId 	=	null,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GetDate()
	WHERE	RosterGroupId		=@RosterGroupId

	SELECT 1
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupDetailsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupDetailsIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupDetailsIns]    Script Date: 7/6/2018 2:27:54 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[prS_RosterGroupDetailsIns]    
(
	@RosterGroupID		BigInt,
	@EmployeeID			BigInt,	
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0, @RosterGroupDetailsID BigInt = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  IsNull(S_RosterGroupDetails.GroupDetId,0)
	FROM	S_RosterGroupDetails WITH (NOLOCK)
	WHERE	EmployeeId		= @EmployeeID
	--AND		RosterGroupId	= @RosterGroupID

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_RosterGroupDetails
		(RosterGroupId, EmployeeId, CreatedBy)
		VALUES(@RosterGroupID, @EmployeeID, @CreatedBy)

		SET @RosterGroupDetailsID =  SCOPE_IDENTITY();
	END
	Else
	BEGIN
		UPDATE S_RosterGroupDetails
		SET		RosterGroupId	=	@RosterGroupID,
				UpdatedBy		=	@CreatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	EmployeeId		=	@EmployeeID
	END
	
	UPDATE	C_Employee 
	SET		RosterGroupId	=	@RosterGroupID 
	WHERE	EmployeeId		=	@EmployeeID
	
	If (@ValidateDuplicate != 0) SET @RosterGroupDetailsID = @ValidateDuplicate

	SELECT @RosterGroupDetailsID	
END

go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupDetailsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupDetailsSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupDetailsSel]    Script Date: 7/6/2018 2:28:49 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prS_RosterGroupDetailsSel]    
(
	@RosterGroupDetailsID	BigInt,
	@RosterGroupID			BigInt
)
AS
BEGIN

	SELECT	RosterGroupD.GroupDetId RosterGroupDetailsId,
			RosterGroupD.RosterGroupId RosterGroupId,
			RosterGroupD.EmployeeId EmployeeId,			 
			RosterGroupD.CreatedBy,
			RosterGroupD.CreatedDate,
			RosterGroupD.UpdatedBy,
			RosterGroupD.UpdatedDate,
			Emp.EmployeeNumber, 
			Emp.DisplayName EmployeeName,
			RosterGroup.GroupName RosterGroupName,
			RosterGroup.GroupDesc RosterGroupDescription
	FROM	S_RosterGroupDetails RosterGroupD WITH (NOLOCK)
			INNER JOIN C_Employee Emp WITH (NOLOCK) ON Emp.EmployeeId = RosterGroupD.EmployeeId 
			INNER JOIN S_RosterGroup RosterGroup WITH (NOLOCK) ON RosterGroup.RosterGroupId = RosterGroupD.RosterGroupId
	WHERE	(RosterGroupD.RosterGroupId = @RosterGroupID)
	AND		(RosterGroupD.GroupDetId = @RosterGroupDetailsID OR @RosterGroupDetailsID = 0)
	ORDER BY RosterGroup.GroupName
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupDetailsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupDetailsUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupDetailsUpd]    Script Date: 7/6/2018 2:29:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prS_RosterGroupDetailsUpd]   
(
	@GroupDetId	BigInt,
	@RosterGroupID			BigInt,
	@EmployeeID				BigInt,	 
	@UpdatedBy				nVarchar(50),
	@MarkAsDelete           bit
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	--SELECT	@ValidateDuplicate =  COUNT(*)
	--FROM	S_RosterGroupDetails WITH (NOLOCK)
	--WHERE	EmployeeId		=	@EmployeeID
	--AND		RosterGroupId	=	@RosterGroupID
	--AND		GroupDetId		!=	@GroupDetId		

	--If (@ValidateDuplicate = 0)
	--BEGIN
		
	--END
	--else
	--BEGIN
	--	SET @ValidateDuplicate = -1;
	--	SELECT @ValidateDuplicate;
	--END
	
	If (@MarkAsDelete = 0)
		begin
		UPDATE	S_RosterGroupDetails
		SET		RosterGroupId		=	@RosterGroupID, 
				EmployeeId			=	@EmployeeID, 				 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	GroupDetId			=	@GroupDetId

		UPDATE	C_Employee
		SET		RosterGroupId		=	@RosterGroupID
		WHERE	EmployeeId			=	@EmployeeID

		end
		else 

		begin
			-- Delete from S_RosterGroupDetails WHERE	GroupDetId			=	@GroupDetId
		Delete from	S_RosterGroupDetails 
		WHERE	GroupDetId			=	@GroupDetId

		UPDATE	C_Employee
		SET		RosterGroupId 		=	NULL
		WHERE	EmployeeId			=	@EmployeeID

		end
						

		SELECT 1;

END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupEmployeeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupEmployeeSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupEmployeeSel]    Script Date: 7/6/2018 2:30:23 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prS_RosterGroupEmployeeSel]    
(
	@RosterGroupID			BigInt,
	@OUID					BigInt
)
AS
BEGIN

	SELECT DISTINCT C_Employee.EmployeeId, C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName, 
		   D_Roles.RoleName + ' ' + D_Roles.RoleDesc RoleDescription,
		   D_RoleGroup.RoleGroupName RoleGroupDescription,
		   IsNull(S_RosterGroup.RosterGroupId,0) RosterGroupId,
		   IsNull(S_RosterGroup.GroupName,'') RosterGroupDescription,
		   C_EmployeeRoles.RoleId, ISNull(D_Roles.RoleGroupId,0) RoleGroupId,
		   IsNull(S_RosterGroupDetails.GroupDetId,0) RosterGroupDetailsId,CONVERT(bit,0) [MarkasDelete]
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeRoles.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN D_Roles WITH (NOLOCK) ON C_EmployeeRoles.RoleId = D_Roles.RoleId
			LEFT OUTER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON C_Employee.RosterGroupId = S_RosterGroup.RosterGroupId
			LEFT OUTER JOIN S_RosterGroupDetails WITH (NOLOCK) ON S_RosterGroupDetails.RosterGroupId = S_RosterGroup.RosterGroupId
			AND C_Employee.RosterGroupId = S_RosterGroupDetails.RosterGroupId 
			AND C_Employee.EmployeeId = S_RosterGroupDetails.EmployeeId
	WHERE	(S_RosterGroup.RosterGroupId = @RosterGroupID OR @RosterGroupID = 0)
	AND		(C_Employee.OUId = @OUID)
	ORDER BY C_Employee.EmployeeNumber
END
go
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupIdByName]    Script Date: 7/31/2018 10:23:34 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prS_RosterGroupIdByName]    
(
	@GroupName nvarchar(50) 
)
AS
DECLARE @RosterGroupId bigint = 0
BEGIN

	SELECT	@RosterGroupId =  RosterGroupId
	FROM	S_RosterGroup WITH (NOLOCK)
	WHERE	GroupName =@GroupName 
 

 SELECT @RosterGroupId;
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupIns]    Script Date: 7/6/2018 2:31:03 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[prS_RosterGroupIns]    
(
	@OUId				BigInt,
	@GroupName			nVarchar(500),
	@GroupDesc	        nVarchar(2000),
	@Remarks			nVarchar(2000),
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_RosterGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(GroupName)))	=	LTrim(RTrim(Upper(@GroupName)))
	AND		S_RosterGroup.OUId	=	@OUId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_RosterGroup
		(OUId, GroupName, GroupDesc, Remarks, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OUId, @GroupName, @GroupDesc, @Remarks, @ActiveStatus, @CreatedBy, GETDATE())	

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END

go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupSel]    Script Date: 7/6/2018 2:32:48 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[prS_RosterGroupSel]    
(
	@RosterGroupID	BigInt,
	@OUID			BigInt,
	@FilteredOUList		nVarchar(max)
)
AS
BEGIN
	SELECT	RosterGroup.RosterGroupId,
			RosterGroup.OUId,
			RosterGroup.GroupName,
			RosterGroup.GroupDesc GroupDesc,
			RosterGroup.Remarks,
			RosterGroup.ActiveStatus,
			RosterGroup.CreatedBy,
			RosterGroup.CreatedDate,
			RosterGroup.UpdatedBy,
			RosterGroup.UpdatedDate,
			OrgNode.OUName,
			OrgNode.OUDesc OUDescription
	FROM	S_RosterGroup RosterGroup WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON  RosterGroup.OUId = OrgNode.OUId
	WHERE	(RosterGroup.RosterGroupId = @RosterGroupID OR @RosterGroupID = 0)
	AND		(OrgNode.OUId = @OUID OR @OUID = 0 OR OrgNode.OUId IN (SELECT * FROM fnStringToTable(@FilteredOUList))) 
	ORDER BY RosterGroup.GroupName
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_RosterGroupUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_RosterGroupUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_RosterGroupUpd]    Script Date: 7/6/2018 2:33:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


create PROCEDURE [dbo].[prS_RosterGroupUpd]    
(
	@RosterGroupId		BigInt,
	@OUId				BigInt,
	@GroupName			nVarchar(500),
	@GroupDesc	        nVarchar(2000),
	@Remarks			nVarchar(2000),
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_RosterGroup WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(GroupName)))	=	LTrim(RTrim(Upper(@GroupName)))
	AND		RosterGroupId != @RosterGroupId
	AND		OUID			=	@OUId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	S_RosterGroup
		SET		OUId			=	@OUId, 
				GroupName		=	@GroupName, 
				GroupDesc		=	@GroupDesc, 
				Remarks			=	@Remarks, 
				ActiveStatus    =   @ActiveStatus,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	RosterGroupId	=	@RosterGroupId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRuleOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRuleOUDel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRuleOUDel]    Script Date: 7/14/2018 4:39:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prS_ScheduleRuleOUDel]    
(	
	@ScheduleRuleId     BigInt,
	@OUID				BigInt
)
AS
BEGIN
	DELETE FROM S_ScheduleRuleOU
	WHERE	OUId = @OUID
	AND		ScheduleRuleId = @ScheduleRuleId
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRuleOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRuleOUIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRuleOUIns]    Script Date: 7/14/2018 4:40:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
create PROCEDURE [dbo].[prS_ScheduleRuleOUIns]    
(
	@ScheduleRuleId			BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ScheduleRuleOU BigInt = 0;
BEGIN

	SELECT	@ScheduleRuleOU = IsNull(ScheduleRuleOU,0)
	FROM S_ScheduleRuleOU WITH (NOLOCK)
	WHERE	ScheduleRuleId =	@ScheduleRuleId
	AND		OUId	=	@OUId

	If (@ScheduleRuleOU = 0)
	BEGIN
		INSERT INTO S_ScheduleRuleOU
		(ScheduleRuleId, OUId, CreatedBy, CreatedDate)
		VALUES(@ScheduleRuleId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRuleOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRuleOUSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRuleOUSel]    Script Date: 7/14/2018 4:41:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prS_ScheduleRuleOUSel]    
(
	@ScheduleRuleId	BigInt
)
AS
BEGIN
	SELECT	S_ScheduleRuleOU.ScheduleRuleOU,
			S_ScheduleRuleOU.ScheduleRuleId,
			S_ScheduleRuleOU.OUId,
			S_ScheduleRuleOU.CreatedBy, 
			S_ScheduleRuleOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	S_ScheduleRuleOU WITH (NOLOCK) 
			INNER JOIN S_ScheduleRules  WITH (NOLOCK) ON S_ScheduleRuleOU.ScheduleRuleId = S_ScheduleRules.ScheduleRuleId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = S_ScheduleRuleOU.OUId  
			WHERE	S_ScheduleRuleOU.ScheduleRuleId		=	@ScheduleRuleId 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodIns]    Script Date: 7/14/2018 4:42:30 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_ScheduleRulePeriodIns]    
(
	@ScheduleRuleId			bigint,
	@ContDaysOnMin			int,
	@ContDaysOnMax			int,	
	@ContDaysOffMin			int,
	@ContDaysOffMax			int,
	@MinHourRest			int,
	@OrderIndex				int,	 
	@ShiftBandPerPeriodMin	Int,
	@ShiftBandPerPeriodMax	Int,
	@CreatedBy		    nvarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	--SELECT	@ValidateDuplicate =  COUNT(*)
	--FROM	S_ScheduleRulePeriod WITH (NOLOCK)
	--WHERE	ScheduleRuleId=@ScheduleRuleId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_ScheduleRulePeriod
		(ScheduleRuleId, ContDaysOnMin, ContDaysOnMax, ContDaysOffMin, ContDaysOffMax, MinHourRest, OrderIndex, 
		 ShiftBandPerPeriodMin, ShiftBandPerPeriodMax, CreatedBy, CreatedDate)
		VALUES(@ScheduleRuleId, @ContDaysOnMin, @ContDaysOnMax, @ContDaysOffMin, @ContDaysOffMax,@MinHourRest, @OrderIndex,
			   @ShiftBandPerPeriodMin, @ShiftBandPerPeriodMax, @CreatedBy,getdate())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodSel]    Script Date: 7/14/2018 4:43:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
 
Create PROCEDURE [dbo].[prS_ScheduleRulePeriodSel]   
(
	@ScheduleRuleId	 bigInt
	 
)
AS
BEGIN	 
	SELECT  S_ScheduleRulePeriod.SCRPeriodId ,
			S_ScheduleRulePeriod.ScheduleRuleId,
			S_ScheduleRulePeriod.ContDaysOnMin, 
		    S_ScheduleRulePeriod.ContDaysOnMax, 
		    S_ScheduleRulePeriod.ContDaysOffMin, 
		    S_ScheduleRulePeriod.ContDaysOffMax, 
		    S_ScheduleRulePeriod.MinHourRest,
			Convert(nVarchar,DATEADD(MINUTE,S_ScheduleRulePeriod.MinHourRest,Convert(DateTime,'2018-01-01')),120) MinHoursResetTimeString,
		    S_ScheduleRulePeriod.OrderIndex,		  
			IsNull(S_ScheduleRulePeriod.ShiftBandPerPeriodMin,0) ShiftBandPerPeriodMin,
			IsNull(S_ScheduleRulePeriod.ShiftBandPerPeriodMax,0) ShiftBandPerPeriodMax,
		    S_ScheduleRulePeriod.CreatedBy,
		    S_ScheduleRulePeriod.CreatedDate,
			S_ScheduleRulePeriod.UpdatedBy	,
			S_ScheduleRulePeriod.UpdatedDate	
	FROM	S_ScheduleRulePeriod 			  
	WHERE	(S_ScheduleRulePeriod.ScheduleRuleId = @ScheduleRuleId OR @ScheduleRuleId = 0)
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodShiftbandsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsDel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodShiftbandsDel]    Script Date: 7/14/2018 4:44:10 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
Create PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsDel]    
(	
	@ShiftBandId	           BigInt,
	@SCRPeriodId				BigInt
)
AS
BEGIN
	DELETE FROM S_ScheduleRulePeriodShiftbands
	WHERE	SCRPeriodId = @SCRPeriodId
	AND		 ShiftBandId = @ShiftBandId
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodShiftbandsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodShiftbandsIns]    Script Date: 7/14/2018 4:44:58 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
create PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsIns]    
( 
	@SCRPeriodId		bigint,
	@ShiftBandId		int,
	@BandIndex		int,	 
	@CreatedBy		    nvarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_ScheduleRulePeriodShiftbands WITH (NOLOCK)
	WHERE	SCRPeriodId=@SCRPeriodId and
		ShiftBandId =	@ShiftBandId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_ScheduleRulePeriodShiftbands
		(SCRPeriodId,
		 ShiftBandId, 
		 BandIndex, 		  		  
		CreatedBy,
		CreatedDate)
 VALUES(@SCRPeriodId, @ShiftBandId, @BandIndex,@CreatedBy,getdate())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodShiftbandsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodShiftbandsSel]    Script Date: 7/14/2018 4:46:06 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
create PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsSel]   
(
	@SCRPeriodId	 bigInt
	 
)
AS
BEGIN	 
	SELECT	S_ScheduleRulePeriodShiftbands.SCRPeriodShiftId,
			S_ScheduleRulePeriodShiftbands.SCRPeriodId, 
		    S_ScheduleRulePeriodShiftbands.ShiftBandId,
			D_ShiftBand.ShiftBandCode ShiftBandCode, 
		    S_ScheduleRulePeriodShiftbands.BandIndex,
			S_ScheduleRulePeriodShiftbands.CreatedBy,
		    S_ScheduleRulePeriodShiftbands.CreatedDate,
			S_ScheduleRulePeriodShiftbands.UpdatedBy,
			S_ScheduleRulePeriodShiftbands.UpdatedDate	
	FROM	S_ScheduleRulePeriodShiftbands WITH (NOLOCK)
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_ScheduleRulePeriodShiftbands.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	(S_ScheduleRulePeriodShiftbands.SCRPeriodId = @SCRPeriodId OR @SCRPeriodId = 0)
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodShiftbandsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodShiftbandsUpd]    Script Date: 7/14/2018 4:47:09 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

create PROCEDURE [dbo].[prS_ScheduleRulePeriodShiftbandsUpd]    
(
	@SCRPeriodShiftId		BigInt,
	@SCRPeriodId		bigint,
	@ShiftBandId		int,
	@BandIndex		int,			 
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_ScheduleRulePeriodShiftbands WITH (NOLOCK)
	WHERE	SCRPeriodShiftId != @SCRPeriodShiftId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE		S_ScheduleRulePeriodShiftbands
					SET		SCRPeriodId  =	@SCRPeriodId,
							ShiftBandId   =	@ShiftBandId, 
						    BandIndex   =	@BandIndex, 						    
							UpdatedBy		=	@UpdatedBy,
							UpdatedDate		=	GETDATE()
				WHERE	SCRPeriodShiftId			=	@SCRPeriodShiftId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulePeriodUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulePeriodUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulePeriodUpd]    Script Date: 7/14/2018 4:48:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prS_ScheduleRulePeriodUpd]    
(
	@SCRPeriodId			BigInt,
	@ScheduleRuleId			bigint,
	@ContDaysOnMin			int,
	@ContDaysOnMax			int,	
	@ContDaysOffMin			int,
	@ContDaysOffMax			int,
	@MinHourRest			int,
	@OrderIndex				int,		 
	@ShiftBandPerPeriodMin	Int,
	@ShiftBandPerPeriodMax	Int,
	@UpdatedBy				nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	--SELECT	@ValidateDuplicate =  COUNT(*)
	--FROM	S_ScheduleRulePeriod WITH (NOLOCK)
	--WHERE	ScheduleRuleId = @ScheduleRuleId
	--and SCRPeriodId != @SCRPeriodId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE		S_ScheduleRulePeriod
					SET		ScheduleRuleId		=	@ScheduleRuleId,
							ContDaysOnMin		=	@ContDaysOnMin, 
						    ContDaysOnMax		=	@ContDaysOnMax, 
						    ContDaysOffMin		=	@ContDaysOffMin, 
						    ContDaysOffMax		=	@ContDaysOffMax, 
						    MinHourRest			=	@MinHourRest,
						    OrderIndex			=	@OrderIndex,
							ShiftBandPerPeriodMin = @ShiftBandPerPeriodMin,
							ShiftBandPerPeriodMax = @ShiftBandPerPeriodMax,
							UpdatedBy			=	@UpdatedBy,
							UpdatedDate			=	GETDATE()
				WHERE	SCRPeriodId				=	@SCRPeriodId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulesIdByName]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulesIdByName]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulesIdByName]    Script Date: 7/31/2018 10:20:00 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prS_ScheduleRulesIdByName]    
(
	@Name nvarchar(500) 
)
AS
DECLARE @ScheduleRuleId bigint = 0
BEGIN

	SELECT	@ScheduleRuleId =  ScheduleRuleId
	FROM	S_ScheduleRules WITH (NOLOCK)
	WHERE	Name =@Name 
 

 SELECT @ScheduleRuleId;
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulesIns]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulesIns]    Script Date: 7/14/2018 4:49:14 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
CREATE	 PROCEDURE [dbo].[prS_ScheduleRulesIns]    
(
	@Name				  nVarchar(500),
	@Description		  nVarchar(1000),
	@ValidFrom			  DATE,	
	@ValidTo				  DATE,
	@PeriodLength         int,
	@ShiftLengthMin       int,
	@ShiftLengthMax       int,
	@DaysPerPeriodMin     int,
	@DaysPerPeriodMax     int,
	@TimePerPeriodMin     int,
	@TimePerPeriodMax      int,
	@ContDaysScheduleOnMin int,
	@ContDaysScheduleOnMax int,
	@ContDaysScheduleOffMin int,
	@ContDaysScheduleOffMax int,
	@MinRestTime           int,
	@RestDelimiter         bit,
	@OffDaysPerPeriodMin   int,
	@OffDaysPerPeriodMax   int,
	@IsOffDaysMaxForced    int,
	@ActiveStatus		   bit,
	@CreatedBy			   nvarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_ScheduleRules WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Name))) = LTrim(RTrim(Upper(@Name))) 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_ScheduleRules
		(Name,
		 Description, 
		 ValidFrom, 
		 ValidTo, 
		 PeriodLength, 
		 ShiftLengthMin,
		 ShiftLengthMax,
		 DaysPerPeriodMin,
		DaysPerPeriodMax,
		TimePerPeriodMin,
		TimePerPeriodMax,
		ContDaysScheduleOnMin,
		ContDaysScheduleOnMax,
		ContDaysScheduleOffMin,
		ContDaysScheduleOffMax,
		MinRestTime,
		RestDelimiter,
		OffDaysPerPeriodMin,
		OffDaysPerPeriodMax,
		IsOffDaysMaxForced,
		ActiveStatus,
		CreatedBy,
		CreatedDate)
 VALUES(@Name, @Description, @ValidFrom, @ValidTo, @PeriodLength,@ShiftLengthMin,@ShiftLengthMax,@DaysPerPeriodMin,
 @DaysPerPeriodMax,@TimePerPeriodMin,@TimePerPeriodMax,@ContDaysScheduleOnMin,@ContDaysScheduleOnMax,@ContDaysScheduleOffMin,
 @ContDaysScheduleOffMax,@MinRestTime,@RestDelimiter,@OffDaysPerPeriodMin,@OffDaysPerPeriodMax,@IsOffDaysMaxForced,
 @ActiveStatus,@CreatedBy,getdate())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulesSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulesSel]    Script Date: 7/14/2018 4:50:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
 
CREATE PROCEDURE [dbo].[prS_ScheduleRulesSel]   
(
	@ScheduleRuleId		 bigInt,
	@OUID				 BigInt
	
)
AS
BEGIN	 
	SELECT		S_ScheduleRules.ScheduleRuleId,
				S_ScheduleRules.Name,
			    S_ScheduleRules.Description, 
			    S_ScheduleRules.ValidFrom, 
			    S_ScheduleRules.ValidTo, 
				Convert(nVarchar,S_ScheduleRules.ValidFrom) ValidFromString,
				Convert(nVarchar,S_ScheduleRules.ValidTo) ValidToString,
				S_ScheduleRules. PeriodLength, 
				Convert(nVarchar,DATEADD(MINUTE,S_ScheduleRules.ShiftLengthMin,Convert(DateTime,S_ScheduleRules.ValidFrom)),120) ShiftLengthMinDateTime,
				Convert(nVarchar,DATEADD(MINUTE,S_ScheduleRules.ShiftLengthMax,Convert(DateTime,S_ScheduleRules.ValidFrom)),120) ShiftLengthMaxDateTime,
		    	S_ScheduleRules.ShiftLengthMin,
				S_ScheduleRules.ShiftLengthMax,
				S_ScheduleRules.DaysPerPeriodMin,
				S_ScheduleRules.DaysPerPeriodMax,
				S_ScheduleRules.TimePerPeriodMin,
				S_ScheduleRules.TimePerPeriodMax,
				S_ScheduleRules.ContDaysScheduleOnMin,
				S_ScheduleRules.ContDaysScheduleOnMax,
				S_ScheduleRules.ContDaysScheduleOffMin,
				S_ScheduleRules.ContDaysScheduleOffMax,
				S_ScheduleRules.MinRestTime,
				S_ScheduleRules.RestDelimiter,
				S_ScheduleRules.OffDaysPerPeriodMin,
				S_ScheduleRules.OffDaysPerPeriodMax,
				S_ScheduleRules.IsOffDaysMaxForced,
				S_ScheduleRules.ActiveStatus, 
				S_ScheduleRules.CreatedBy,
				S_ScheduleRules.CreatedDate,
				S_ScheduleRules.UpdatedBy	,
				S_ScheduleRules.UpdatedDate	
	FROM	S_ScheduleRules 	
			INNER JOIN S_ScheduleRuleOU WITH (NOLOCK)  ON S_ScheduleRules.ScheduleRuleId   = S_ScheduleRuleOU.ScheduleRuleId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON S_ScheduleRuleOU.OUId = C_OrganizationNode.OUId	
	WHERE	(S_ScheduleRuleOU.ScheduleRuleId = @ScheduleRuleId OR @ScheduleRuleId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)  
	Order By S_ScheduleRules.Name
END
go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_ScheduleRulesSelByOUId')
	DROP PROC prS_ScheduleRulesSelByOUId
GO

----------------------------------------------------------------------------
-- Select a single record from S_EmployeeLeaves
----------------------------------------------------------------------------

 
create PROCEDURE [dbo].[prS_ScheduleRulesSelByOUId]   
AS
BEGIN	 
	SELECT		S_ScheduleRules.ScheduleRuleId,
				S_ScheduleRules.Name,
			    S_ScheduleRules.Description, 
			    S_ScheduleRules.ValidFrom, 
			    S_ScheduleRules.ValidTo, 
				Convert(nVarchar,S_ScheduleRules.ValidFrom) ValidFromString,
				Convert(nVarchar,S_ScheduleRules.ValidTo) ValidToString,
				S_ScheduleRules. PeriodLength, 
				Convert(nVarchar,DATEADD(MINUTE,S_ScheduleRules.ShiftLengthMin,Convert(DateTime,S_ScheduleRules.ValidFrom)),120) ShiftLengthMinDateTime,
				Convert(nVarchar,DATEADD(MINUTE,S_ScheduleRules.ShiftLengthMax,Convert(DateTime,S_ScheduleRules.ValidFrom)),120) ShiftLengthMaxDateTime,
		    	S_ScheduleRules.ShiftLengthMin,
				S_ScheduleRules.ShiftLengthMax,
				S_ScheduleRules.DaysPerPeriodMin,
				S_ScheduleRules.DaysPerPeriodMax,
				S_ScheduleRules.TimePerPeriodMin,
				S_ScheduleRules.TimePerPeriodMax,
				S_ScheduleRules.ContDaysScheduleOnMin,
				S_ScheduleRules.ContDaysScheduleOnMax,
				S_ScheduleRules.ContDaysScheduleOffMin,
				S_ScheduleRules.ContDaysScheduleOffMax,
				S_ScheduleRules.MinRestTime,
				S_ScheduleRules.RestDelimiter,
				S_ScheduleRules.OffDaysPerPeriodMin,
				S_ScheduleRules.OffDaysPerPeriodMax,
				S_ScheduleRules.IsOffDaysMaxForced,
				S_ScheduleRules.ActiveStatus, 
				S_ScheduleRules.CreatedBy,
				S_ScheduleRules.CreatedDate,
				S_ScheduleRules.UpdatedBy	,
				S_ScheduleRules.UpdatedDate,
				S_ScheduleRuleOU.OUId
	FROM	S_ScheduleRules 	
			INNER JOIN S_ScheduleRuleOU WITH (NOLOCK)  ON S_ScheduleRules.ScheduleRuleId   = S_ScheduleRuleOU.ScheduleRuleId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON S_ScheduleRuleOU.OUId = C_OrganizationNode.OUId	
	Order By S_ScheduleRules.ScheduleRuleId
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ScheduleRulesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ScheduleRulesUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_ScheduleRulesUpd]    Script Date: 7/14/2018 4:51:39 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prS_ScheduleRulesUpd]    
(
	@ScheduleRuleId				BigInt,
	@Name				  nVarchar(500),
	@Description		  nVarchar(1000),
	@ValidFrom			  DATE,	
	@ValidTo				  DATE,
	@PeriodLength         int,
	@ShiftLengthMin       int,
	@ShiftLengthMax       int,
	@DaysPerPeriodMin     int,
	@DaysPerPeriodMax     int,
	@TimePerPeriodMin     int,
	@TimePerPeriodMax      int,
	@ContDaysScheduleOnMin int,
	@ContDaysScheduleOnMax int,
	@ContDaysScheduleOffMin int,
	@ContDaysScheduleOffMax int,
	@MinRestTime           int,
	@RestDelimiter         bit,
	@OffDaysPerPeriodMin   int,
	@OffDaysPerPeriodMax   int,
	@IsOffDaysMaxForced    int,
	@ActiveStatus		   bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_ScheduleRules WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(Name))) = LTrim(RTrim(Upper(@Name)))
		and	ScheduleRuleId	!=	@ScheduleRuleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	S_ScheduleRules
		SET		 Name					=@Name,
				 Description			=@Description, 
				 ValidFrom				=@ValidFrom, 
				 ValidTo					=@ValidTo, 
				 PeriodLength			=@PeriodLength, 
				 ShiftLengthMin			=@ShiftLengthMin,
				 ShiftLengthMax			=@ShiftLengthMax,
				 DaysPerPeriodMin		=@DaysPerPeriodMin,
				 DaysPerPeriodMax		=@DaysPerPeriodMax,
				 TimePerPeriodMin		=@TimePerPeriodMin,
				 TimePerPeriodMax		=@TimePerPeriodMax,
				 ContDaysScheduleOnMin  =@ContDaysScheduleOnMin,
				 ContDaysScheduleOnMax  =@ContDaysScheduleOnMax,
				 ContDaysScheduleOffMin =@ContDaysScheduleOffMin,
				 ContDaysScheduleOffMax =@ContDaysScheduleOffMax,
				 MinRestTime			=@MinRestTime,
				 RestDelimiter			=@RestDelimiter,
				 OffDaysPerPeriodMin	=@OffDaysPerPeriodMin,
				 OffDaysPerPeriodMax	=@OffDaysPerPeriodMax,
				 IsOffDaysMaxForced		=@IsOffDaysMaxForced,
				 ActiveStatus			=@ActiveStatus, 
				 UpdatedDate			=	GETDATE()
		WHERE	ScheduleRuleId			=	@ScheduleRuleId
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go

/****** Object:  StoredProcedure [dbo].[prS_ShiftIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftByShiftIdDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftByShiftIdDel]
GO

/****** Object:  StoredProcedure [dbo].[prS_ShiftByShiftIdDel]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_ShiftByShiftIdDel]    
(
	@ShiftId			BigInt
)
AS
BEGIN

	DELETE	FROM S_Shifts
	WHERE	ShiftId = @ShiftId

	DELETE FROM S_THPEmployeeDetails 
	WHERE	ShiftId = @ShiftId

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prS_ShiftIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftByShiftIdIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftByShiftIdIns]
GO

/****** Object:  StoredProcedure [dbo].[prS_ShiftByShiftIdIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_ShiftByShiftIdIns]    
(
	@ShiftId			BigInt,
	@EmployeeId			BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @GetEmployeeRoleId BigInt = 0, @GetEmployeeRosterGroupId  BigInt = 0
BEGIN

	-- Get Employee Role ID
	SELECT	@GetEmployeeRoleId = IsNull(C_EmployeeRoles.RoleId,0)
	FROM	C_EmployeeRoles WHERE EmployeeId = @EmployeeId 
	AND		IsPrimaryRole = 1

	-- Get Employee Roster Group ID
	SELECT	@GetEmployeeRosterGroupId = IsNull(RosterGroupId,0)
	FROM	C_Employee 
	WHERE	EmployeeId = @EmployeeId

	if (@GetEmployeeRoleId = 0) SET @GetEmployeeRoleId = NULL
	if (@GetEmployeeRosterGroupId = 0) SET @GetEmployeeRosterGroupId = NULL

	INSERT INTO S_Shifts
	(OUId, EmployeeId, TemplateId, RoleId, RosterGroupId, ShiftBandId, OTStartTime, ShiftStartTime, ShiftEndTime, OTEndTime,
	ActualStartTime, ActualEndTime, PreparationMins, DepreparationMins, OnCallShift, Notes, CombinationShiftId, CreatedBy, CreatedDate)
	SELECT	OUId, @EmployeeId, null, @GetEmployeeRoleId, @GetEmployeeRosterGroupId, ShiftBandId, OTStartTime, ShiftStartTime, ShiftEndTime, OTEndTime,
			ActualStartTime, ActualEndTime, PreparationMins, DepreparationMins, OnCallShift, Notes, CombinationShiftId, @CreatedBy, GETDATE()
	FROM	S_Shifts WITH (NOLOCK) WHERE S_Shifts.ShiftId = @ShiftId	

	SELECT SCOPE_IDENTITY();
END
GO
/****** Object:  StoredProcedure [dbo].[prS_ShiftDel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftDel]
GO

/****** Object:  StoredProcedure [dbo].[prS_ShiftDel]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_ShiftDel]    
(
	@EmployeeId			BigInt,
	@ActualStartTime	DateTime
)
AS
DECLARE @GetShiftID BigInt = 0, @GetShiftBandId BigInt = 0
BEGIN

	SELECT	@GetShiftID = S_Shifts.ShiftId, @GetShiftBandId = S_Shifts.ShiftBandId
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	S_Shifts.EmployeeId = @EmployeeId
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ActualStartTime)
	
	If (@GetShiftID != 0)
	BEGIN

		DELETE FROM S_THPEmployeeDetails 
		WHERE	ShiftId = @GetShiftID

		DELETE	FROM S_Shifts 
		WHERE	Convert(Date,ActualStartTime) = Convert(Date,@ActualStartTime)
		AND		EmployeeId	=	@EmployeeId

		SELECT @GetShiftID
	END
	ELSE SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prS_ShiftIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftIns]
GO

/****** Object:  StoredProcedure [dbo].[prS_ShiftIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_ShiftIns]    
(
	@OUId				BigInt,
	@EmployeeId			BigInt,
	@TemplateId			BigInt,
	@RoleId				BigInt,
	@RosterGroupId		BigInt,
	@ShiftBandId		BigInt,
	@OTStartTime		DateTime,
	@ShiftStartTime		DateTime,
	@ShiftEndTime		DateTime,
	@OTEndTime			DateTime,
	@ActualStartTime	DateTime,
	@ActualEndTime		DateTime,
	@PreparationMins	int,
	@DePreparationMins	int,
	@OnCallShift		Bit,
	@Notes				nVarchar(500),
	@CombinationShiftId	BigInt,
	@ShiftCost			Decimal(18,4),
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @GetShiftID BigInt = 0, @GetShiftBandId BigInt = 0
BEGIN

	SELECT	@GetShiftID = S_Shifts.ShiftId, @GetShiftBandId = S_Shifts.ShiftBandId
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	S_Shifts.EmployeeId = @EmployeeId
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ActualStartTime)

	-- Get Employee Role ID
	If(@RoleId = 0) 
	BEGIN
		SET @RoleId = NULL

		SELECT	@RoleId = ISNULL(C_EmployeeRoles.RoleId,NULL)
		FROM	C_EmployeeRoles WITH (NOLOCK) WHERE C_EmployeeRoles.EmployeeId = @EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
	END
	
	If(@TemplateId = 0) SET @TemplateId = NULL
	
	If (@GetShiftID = 0)
	BEGIN
		INSERT INTO S_Shifts
		(OUId, EmployeeId, TemplateId, RoleId, RosterGroupId, ShiftBandId, OTStartTime, ShiftStartTime, ShiftEndTime, OTEndTime,
			ActualStartTime, ActualEndTime, PreparationMins, DepreparationMins, OnCallShift, Notes, CombinationShiftId, CreatedBy, CreatedDate, ShiftCost)
		VALUES( @OUId, @EmployeeId, @TemplateId, @RoleId, @RosterGroupId, @ShiftBandId, @OTStartTime, @ShiftStartTime, @ShiftEndTime,
				@OTEndTime, @ActualStartTime, @ActualEndTime, @PreparationMins, @DePreparationMins, @OnCallShift, @Notes,
				@CombinationShiftId, @CreatedBy, GETDATE(), @ShiftCost)


		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		UPDATE	S_Shifts
		SET		OUId				=	@OUId,
				TemplateId			=	@TemplateId,
				RoleId				=	@RoleId,
				RosterGroupId		=	@RosterGroupId,
				ShiftBandId			=	@ShiftBandId,
				OTStartTime			=	@OTStartTime,
				ShiftStartTime		=	@ShiftStartTime,
				ShiftEndTime		=	@ShiftEndTime,
				OTEndTime			=	@OTEndTime,
				ActualStartTime		=	@ActualStartTime,
				ActualEndTime		=	@ActualEndTime,
				PreparationMins		=	@PreparationMins,
				DepreparationMins	=	@DePreparationMins,
				OnCallShift			=	@OnCallShift,
				Notes				=	@Notes,
				CombinationShiftId	=	@CombinationShiftId,
				UpdatedBy			=	@CreatedBy,
				UpdatedDate			=	GETDATE(),
				ShiftCost			=	@ShiftCost,
				ReconTime			=	Null,
				Reconciled			=	0,
				ReconStatusId		=	null,
				RPGId				=	null,
				InStatus			=	null,
				OutStatus			=	null,
				InTime				=	null,
				OutTime				=	null
		WHERE	ShiftId				=	@GetShiftID

		SELECT @GetShiftID

	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_ShiftsByShiftId')
	DROP PROC prS_ShiftsByShiftId
GO

----------------------------------------------------------------------------
-- Select a single record from S_Shifts
----------------------------------------------------------------------------
CREATE PROC prS_ShiftsByShiftId
	@ShiftId bigint
AS

SELECT	S_Shifts.ShiftId,
		S_Shifts.OUId,
		S_Shifts.EmployeeId,
		TemplateId,
		RoleId,
		RosterGroupId,
		ShiftBandId,
		OTStartTime,
		ShiftStartTime,
		ShiftEndTime,
		OTEndTime,
		ActualStartTime,
		ActualEndTime,
		PreparationMins,
		DepreparationMins,
		OnCallShift,
		Notes,
		CombinationShiftId,
		ReconTime,
		ReconStatusId,
		RPGId,
		ReconFailureReasonId,
		ReconFailureReasonDetail,
		Reconciled,
		PickedByTHP,
		Deployed,
		S_Shifts.CreatedBy,
		S_Shifts.CreatedDate,
		S_Shifts.UpdatedBy,
		S_Shifts.UpdatedDate,
		IsNull(S_EmployeeLeaves.LeaveId,0) LeaveId,
		IsNull(S_PublicholidayEmployeeList.TypeId,0) PublicHolidayTypeId
FROM	S_Shifts WITH (NOLOCK) 
		LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_Shifts.ShiftId = S_EmployeeLeaves.ShiftId
		LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = S_Shifts.EmployeeId
WHERE 	S_Shifts.ShiftId = @ShiftId

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftsSel]
GO
/****** Object:  StoredProcedure [dbo].[prS_ShiftsSel]    Script Date: 8/8/2018 5:22:37 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_ShiftsSel]  --prS_ShiftsSel 6,4,'',0,0,0,0
(
	@shiftid				Bigint,  
	@OUId					BigInt,
	@date					datetime,
	@shiftbandid			nVarchar(max),
	@EmployeeNumber			nvarchar(50),
	@AttendanceStatusId		int,
	@ReconStatusId			int,
	@LoginUserEmployeeId	BigInt,
	@EmploymentBasisId		BigInt
)
AS
DECLARE @__shiftBandIds BIGINT = 0
BEGIN	 
 SELECT TOP 1 @__shiftBandIds = sID FROM fnStringToTable(@shiftbandid)
	IF @shiftid > 0
	BEGIN
		--WITH Activities (ShiftId, TotalHours)
		WITH ShiftOverTime (ShiftId, ApprovedOverTimeHours)
		AS
		(
			--SELECT  S_Shifts.ShiftId, 
			--		Sum(DATEDIFF(second, J_Activity.StartTime, J_Activity.EndTime) / 3600.0) TotalHours
			--FROM	S_Shifts INNER JOIN J_Activity ON S_Shifts.ShiftId = J_Activity.ShiftId
			--WHERE 	S_Shifts.ShiftId = @shiftid
			--GROUP BY S_Shifts.ShiftId
			SELECT	S_Shifts.ShiftId,
					Sum(P_ShiftCosts.ApprovedHours) ApprovedOverTimeHours
			FROM	S_Shifts INNER JOIN P_ShiftCosts ON S_Shifts.ShiftId = P_ShiftCosts.ShiftId
			WHERE 	S_Shifts.ShiftId = @shiftid
			AND		P_ShiftCosts.PayCodeId NOT IN (1,19)
			GROUP BY S_Shifts.ShiftId		
		) 
		SELECT		S_Shifts.ShiftId,
					S_Shifts.OUId	, 
					S_Shifts.EmployeeId,
					S_Shifts.TemplateId,
					S_Shifts.RoleId, 
					S_Shifts.RosterGroupId,
					S_Shifts.ShiftBandId,
					S_Shifts.OTStartTime ,
					S_Shifts.ShiftStartTime ,
					S_Shifts.ShiftEndTime ,
					S_Shifts.OTEndTime,
					S_Shifts.ActualStartTime,
					S_Shifts.ActualEndTime,
					convert(nvarchar,ActualStartTime) as ConActualStartTime,
					convert(nvarchar,ActualEndTime) as ConActualEndTime,
					S_Shifts.PreparationMins ,
					S_Shifts.DepreparationMins ,
					S_Shifts.OnCallShift,
					S_Shifts.Notes,
					S_Shifts.CombinationShiftId ,
					S_Shifts.ReconTime,
					S_Shifts.ReconStatusId ,
					S_Shifts.RPGId ,
					S_Shifts.ReconFailureReasonId,
					S_Shifts.ReconFailureReasonDetail,
					S_Shifts.Reconciled,
					S_Shifts.InStatus,
					S_Shifts.OutStatus,
					S_Shifts.InTime,
					S_Shifts.OutTime,
					S_Shifts.PickedByTHP,
					S_Shifts.Deployed,
					S_EmployeeLeaves.LeaveId,
					S_Shifts.CreatedBy,
					S_Shifts.CreatedDate,
					S_Shifts.UpdatedBy	,
					S_Shifts.UpdatedDate,
					S_Shifts.Remarks,
					C_Employee.EmployeeNumber,
					C_Employee.FirstName + ' ' + C_Employee.LastName AS EmployeeName,
					D_Roles.RoleName,
					D_ShiftBand.ShiftBandName,
					TA_ExceptionCodes.ColorCode,
					--IsNull(Activities.TotalHours,0) TotalActivityHours,
					IsNull(ShiftOverTime.ApprovedOverTimeHours,0) ApprovedOverTimeHours,
					IsNull(S_Shifts.Remarks,'') ShiftRemarks,
					IsNull(ApprovalStatus,0) ShiftApprovalStatus
		FROM	S_Shifts WITH (NOLOCK)	
				INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
				LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
				LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
				LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
				LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
				LEFT OUTER JOIN ShiftOverTime WITH (NOLOCK) ON ShiftOverTime.ShiftId = S_Shifts.ShiftId
				LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
		WHERE 	S_Shifts.ShiftId = @shiftid
		--AND		S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL
		Order By S_Shifts.EmployeeId
	END
	ELSE
	BEGIN
		--	WITH Activities (ShiftId, TotalHours)
		--	AS
		--	(
		--		SELECT  S_Shifts.ShiftId, 
		--				Sum(DATEDIFF(second, J_Activity.StartTime, J_Activity.EndTime) / 3600.0) TotalHours
		--		FROM	S_Shifts INNER JOIN J_Activity ON S_Shifts.ShiftId = J_Activity.ShiftId
		--				INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
		--				LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
		--				LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
		--				LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
		--				LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
		--		WHERE 	(C_OrganizationNode.OUId = @OUID AND CONVERT(DATE,S_Shifts.ActualStartTime)=CONVERT(DATE,@date))
		--		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
		--		AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
		--		AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
		--		AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
		--		AND		(S_Shifts.ShiftId = @shiftid OR @shiftid=0)
		--		AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
		--		GROUP BY S_Shifts.ShiftId
		--	) 

		--	SELECT	S_Shifts.ShiftId,
		--			S_Shifts.OUId	, 
		--			S_Shifts.EmployeeId,
		--			S_Shifts.TemplateId,
		--			S_Shifts.RoleId, 
		--			S_Shifts.RosterGroupId,
		--			S_Shifts.ShiftBandId,
		--			S_Shifts.OTStartTime ,
		--			S_Shifts.ShiftStartTime ,
		--			S_Shifts.ShiftEndTime ,
		--			S_Shifts.OTEndTime,
		--			S_Shifts.ActualStartTime,
		--			S_Shifts.ActualEndTime,
		--			S_Shifts.PreparationMins ,
		--			S_Shifts.DepreparationMins ,
		--			S_Shifts.OnCallShift,
		--			S_Shifts.Notes,
		--			S_Shifts.CombinationShiftId ,
		--			S_Shifts.ReconTime,
		--			S_Shifts.ReconStatusId ,
		--			S_Shifts.RPGId ,
		--			S_Shifts.ReconFailureReasonId,
		--			S_Shifts.ReconFailureReasonDetail,
		--			S_Shifts.Reconciled,
		--			S_Shifts.InStatus,
		--			S_Shifts.OutStatus,
		--			S_Shifts.InTime,
		--			S_Shifts.OutTime,
		--			S_Shifts.PickedByTHP,
		--			S_Shifts.Deployed,
		--			S_Shifts.LeaveId,
		--			S_Shifts.CreatedBy,
		--			S_Shifts.CreatedDate,
		--			S_Shifts.UpdatedBy	,
		--			S_Shifts.UpdatedDate,
		--			C_Employee.EmployeeNumber,
		--			C_Employee.FirstName + ' ' + C_Employee.LastName AS EmployeeName,
		--			D_Roles.RoleName,
		--			D_ShiftBand.ShiftBandName,
		--			TA_ExceptionCodes.ColorCode,
		--			IsNull(Activities.TotalHours,0) TotalActivityHours
		--FROM	S_Shifts 	
		--		INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
		--		LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
		--		LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
		--		LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
		--		LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
		--		LEFT OUTER JOIN Activities ON Activities.ShiftId = S_Shifts.ShiftId
		--WHERE 	(C_OrganizationNode.OUId = @OUID AND CONVERT(DATE,S_Shifts.ActualStartTime)=CONVERT(DATE,@date))
		--AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
		--AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
		--AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
		--AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
		--AND		(S_Shifts.ShiftId = @shiftid OR @shiftid=0)
		--AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
		--Order By S_Shifts.EmployeeId

		WITH 
		--WorkFlowRoute
		--	AS
		--	(
		--		SELECT	Distinct RouteId 
		--		FROM	W_WorkflowRouteDetails WITH (NOLOCK)
		--		WHERE	EmployeeId = @LoginUserEmployeeId 
		--	), 
			ShiftOverTime (ShiftId, ApprovedOverTimeHours)
			AS
			(
				SELECT  DISTINCT S_Shifts.ShiftId,
						Sum(P_ShiftCosts.ApprovedHours) ApprovedOverTimeHours
						--Sum(DATEDIFF(second, J_Activity.StartTime, J_Activity.EndTime) / 3600.0) TotalHours
				FROM	S_Shifts WITH (NOLOCK) INNER JOIN P_ShiftCosts WITH (NOLOCK) ON S_Shifts.ShiftId = P_ShiftCosts.ShiftId
						INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId
						--INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId = S_Shifts.EmployeeId
						--INNER JOIN WorkFlowRoute ON C_EmployeeWorkflow.RouteId = WorkFlowRoute.RouteId  AND C_EmployeeWorkflow.ModuleId = 204	
						--LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
						--LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
						--LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
						--LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
				WHERE 	(C_OrganizationNode.OUId = @OUID AND CONVERT(DATE,S_Shifts.ActualStartTime)=CONVERT(DATE,@date))
				--AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
				--AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
				--AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
				--AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
				--AND		(S_Shifts.ShiftId = @shiftid OR @shiftid=0)
				--AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
				AND		P_ShiftCosts.PayCodeId NOT IN (1,19)
				GROUP BY S_Shifts.ShiftId
			)
			SELECT	DISTINCT S_Shifts.ShiftId,
					S_Shifts.OUId	, 
					S_Shifts.EmployeeId,
					S_Shifts.TemplateId,
					S_Shifts.RoleId, 
					S_Shifts.RosterGroupId,
					S_Shifts.ShiftBandId,
					S_Shifts.OTStartTime ,
					S_Shifts.ShiftStartTime ,
					S_Shifts.ShiftEndTime ,
					S_Shifts.OTEndTime,
					S_Shifts.ActualStartTime,
					S_Shifts.ActualEndTime,
					S_Shifts.PreparationMins ,
					S_Shifts.DepreparationMins ,
					S_Shifts.OnCallShift,
					S_Shifts.Notes,
					S_Shifts.CombinationShiftId ,
					S_Shifts.ReconTime,
					S_Shifts.ReconStatusId ,
					S_Shifts.RPGId ,
					S_Shifts.ReconFailureReasonId,
					S_Shifts.ReconFailureReasonDetail,
					S_Shifts.Reconciled,
					S_Shifts.InStatus,
					S_Shifts.OutStatus,
					S_Shifts.InTime,
					S_Shifts.OutTime,
					S_Shifts.PickedByTHP,
					S_Shifts.Deployed,
					S_EmployeeLeaves.LeaveId,
					S_Shifts.CreatedBy,
					S_Shifts.CreatedDate,
					S_Shifts.UpdatedBy	,
					S_Shifts.UpdatedDate,
					C_Employee.EmployeeNumber,
					C_Employee.FirstName + ' ' + C_Employee.LastName AS EmployeeName,
					D_Roles.RoleName,
					D_ShiftBand.ShiftBandName,
					TA_ExceptionCodes.ColorCode,
					--IsNull(Activities.TotalHours,0) TotalActivityHours,
					IsNull(ShiftOverTime.ApprovedOverTimeHours,0) ApprovedOverTimeHours,
					S_Shifts.Remarks,
					IsNull(P_ShiftCosts.ApprovalStatus,1) ShiftCostApprovalStatus
		FROM	S_Shifts WITH (NOLOCK)	
				INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
				--LEFT OUTER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId = S_Shifts.EmployeeId
				--INNER JOIN WorkFlowRoute ON C_EmployeeWorkflow.RouteId = WorkFlowRoute.RouteId 
				--				AND C_EmployeeWorkflow.ModuleId = 204	
				LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
				LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
				LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
				LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
				LEFT OUTER JOIN ShiftOverTime WITH (NOLOCK) ON ShiftOverTime.ShiftId = S_Shifts.ShiftId
				LEFT OUTER JOIN P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId --AND P_ShiftCosts.PayCodeId NOT IN (1,19)
				LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
				LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
		WHERE 	(C_OrganizationNode.OUId = @OUID AND CONVERT(DATE,S_Shifts.ActualStartTime)=CONVERT(DATE,@date))
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
		AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
		AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
		AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
		AND		(S_Shifts.ShiftId = @shiftid OR @shiftid=0)
		AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
		AND		(C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
		Order By S_Shifts.EmployeeId
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_ShiftsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_ShiftsUpd]
GO
/****** Object:  StoredProcedure [dbo].[prS_ShiftsUpd]    Script Date: 8/8/2018 5:21:50 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prS_ShiftsUpd]   
(
	@ShiftId		BigInt,
	@ReconStatusId  int,
	@IsAbsent		Bit
)
AS 
DECLARE @ShiftInTime DateTime = NULL, @ShiftOutTime DateTime = NULL
BEGIN
	
		--If @IsAbsent = 0
		--BEGIN
		SELECT @ShiftInTime = S_Shifts.OTStartTime, @ShiftOutTime = S_Shifts.OTEndTime
		FROM   S_Shifts WITH (NOLOCK) WHERE S_Shifts.ShiftId = @ShiftId
		--END

		update	S_Shifts 
		SET		ShiftStartTime				=	@ShiftInTime,
				ShiftEndTime				=	@ShiftOutTime,
				ActualStartTime				=	@ShiftInTime,
				ActualEndTime				=	@ShiftOutTime,
				ReconStatusId				=	@ReconStatusId ,
				InTime						=	IIF(@IsAbsent = 1, NULL, @ShiftInTime),
				OutTime						=	IIF(@IsAbsent = 1, NULL, @ShiftOutTime),
				InStatus					=	IIF(@IsAbsent = 1, NULL, 1),
				OutStatus					=	IIF(@IsAbsent = 1, NULL, 1),
				ReconTime					=	GETDATE(),
				ReconFailureReasonId		=	NULL,
				ReconFailureReasonDetail	=	NULL,
				Reconciled=1
				where ShiftId =@ShiftId
	
		select 1 
	 
END
go
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterIns
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterIns]    
(
	@OUId				BigInt,
	@TemplateName		nVarchar(100),
	@TemplateDesc		nVarchar(1000),
	@NoOfDays			Int,
	@StartDate			DateTime,
	@EndDate			DateTime,
	@FirstPublishDate	DateTime,
	@LastPublishDate	DateTime,
	@PublishFrom		DateTime,
	@PublishTo			DateTime,
	@ActiveStatus		Bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_TemplateRoster WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName)))	=	LTrim(RTrim(Upper(@TemplateName)))
	AND		S_TemplateRoster.OUId = @OUId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_TemplateRoster
		(OUId, TemplateName, TemplateDesc, NoOfDays, StartDate, EndDate, FirstPublishDate, LastPublishDate, 
		 PublishFrom, PublishTo, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OUId, @TemplateName, @TemplateDesc, @NoOfDays, @StartDate, @EndDate, @FirstPublishDate, @LastPublishDate,
			   @PublishFrom, @PublishTo, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();

	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	
END
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterLineIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterLineIns
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterLineIns]    
(
	@TemplateId			BigInt,
	@LineType			Int,
	@LineNumber			Int,
	@RosterGroupId		BigInt,
	@EmployeeId			BigInt,
	@FirstPublishDate	DateTime,
	@LastPublishDate	DateTime,
	@PublishFrom		DateTime,
	@PublishTo			DateTime,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	
	INSERT INTO S_TemplateRosterLine
	(TemplateId, LineType, LineNumber, RosterGroupId, EmployeeId, FirstPublishDate, LastPublishDate, 
	 PublishFrom, PublishTo, CreatedBy, CreatedDate)
	VALUES(@TemplateId, @LineType, @LineNumber, @RosterGroupId, @EmployeeId, @FirstPublishDate, @LastPublishDate,
		   @PublishFrom, @PublishTo, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
	
END

GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLinePublishUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterPublishUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_TemplateRosterLinePublishUpd]
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLinePublishUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[prS_TemplateRosterLinePublishUpd]    
(
	@TemplateLineId		BigInt,
	@FirstPublishDate	DateTime,
	@LastPublishDate	DateTime,
	@PublishFrom		DateTime,
	@PublishTo			DateTime,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN

	UPDATE	S_TemplateRosterLine
	SET		FirstPublishDate	=	@FirstPublishDate,
			LastPublishDate		=	@LastPublishDate,
			PublishFrom			=	@PublishFrom,
			PublishTo			=	@PublishTo,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	TemplateLineId		=	@TemplateLineId

	SELECT @TemplateLineId
END
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterLineSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterLineSel
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterLineSel]    Script Date: 20/6/2018 7:07:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterLineSel]    
(
	@TemplateID	BigInt
)
AS
BEGIN
	SELECT  S_TemplateRosterLine.TemplateLineId,
			S_TemplateRosterLine.TemplateId,
			S_TemplateRosterLine.LineType,
			S_TemplateRosterLine.LineNumber,
			IsNull(S_TemplateRosterLine.RosterGroupId,0) RosterGroupId,
			IsNull(S_TemplateRosterLine.EmployeeId,0) EmployeeId,
			S_TemplateRosterLine.FirstPublishDate FirstPublishedDate,
			S_TemplateRosterLine.LastPublishDate LastPublishedDate,
			Convert(nVarchar,S_TemplateRosterLine.FirstPublishDate,120) FirstPublishedDateString,
			Convert(nVarchar,S_TemplateRosterLine.LastPublishDate,120) LastPublishedDateString,
			S_TemplateRosterLine.PublishFrom,
			S_TemplateRosterLine.PublishTo,
			Convert(nVarchar,S_TemplateRosterLine.PublishFrom,120) PublishFromString,
			Convert(nVarchar,S_TemplateRosterLine.PublishTo,120) PublishToString,
			S_TemplateRosterLine.CreatedBy,
			S_TemplateRosterLine.UpdatedBy,
			S_TemplateRosterLine.CreatedDate,
			S_TemplateRosterLine.UpdatedDate,
			S_RosterGroup.GroupName RosterGroupName
	FROM	S_TemplateRoster WITH (NOLOCK)
			INNER JOIN S_TemplateRosterLine WITH (NOLOCK) ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId
			INNER JOIN S_RosterGroup WITH (NOLOCK) ON S_TemplateRosterLine.RosterGroupId = S_RosterGroup.RosterGroupId 
	WHERE	S_TemplateRoster.TemplateId = @TemplateID
	ORDER BY S_TemplateRosterLine.TemplateId, S_TemplateRosterLine.LineNumber
END


GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterPublishUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterPublishUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_TemplateRosterPublishUpd]
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterPublishUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [dbo].[prS_TemplateRosterPublishUpd]    
(
	@TemplateId			BigInt,
	@FirstPublishDate	DateTime,
	@LastPublishDate	DateTime,
	@PublishFrom		DateTime,
	@PublishTo			DateTime,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN

	UPDATE	S_TemplateRoster
	SET		FirstPublishDate	=	@FirstPublishDate,
			LastPublishDate		=	@LastPublishDate,
			PublishFrom			=	@PublishFrom,
			PublishTo			=	@PublishTo,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	TemplateId			=	@TemplateId

	SELECT @TemplateId
END


GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterSel
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterSel]    Script Date: 20/6/2018 7:07:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterSel]    
(
	@TemplateID	BigInt,
	@OUID		BigInt
)
AS
BEGIN
	SELECT	S_TemplateRoster.TemplateId,
			S_TemplateRoster.TemplateName,
			S_TemplateRoster.TemplateDesc,
			S_TemplateRoster.NoOfDays NumberOfDays,
			S_TemplateRoster.StartDate,
			S_TemplateRoster.EndDate,
			S_TemplateRoster.FirstPublishDate FirstPublishedDate,
			S_TemplateRoster.LastPublishDate LastPublishedDate,
			S_TemplateRoster.ActiveStatus,
			S_TemplateRoster.CreatedBy,
			S_TemplateRoster.CreatedDate,
			S_TemplateRoster.UpdatedBy,
			S_TemplateRoster.UpdatedDate 
	FROM	S_TemplateRoster WITH (NOLOCK) INNER JOIN C_OrganizationNode with (NOLOCK) ON S_TemplateRoster.OUId = C_OrganizationNode.OUId
	WHERE	(S_TemplateRoster.TemplateId = @TemplateID OR @TemplateID = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
	ORDER BY S_TemplateRoster.TemplateName, S_TemplateRoster.StartDate
END


GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterShiftsIns]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterShiftsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterShiftsIns
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterShiftsIns]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterShiftsIns]    
(
	@TemplateId			BigInt,
	@TemplateLineId		BigInt,
	@ShiftBandId		BigInt,
	@IsOnCallShift		Bit,
	@Notes				nVarchar(1000),
	@RowNumber			Int,
	@CreatedBy			nVarchar(50)
)
AS
--DECLARE @RosterShiftID  BIGINT = 0
BEGIN
	
	INSERT INTO S_TemplateRoster_Shifts
	(TemplateId, TemplateLineId, ShiftBandId, OnCallShift, Notes, RowNumber, CreatedBy, CreatedDate)
	VALUES(@TemplateId, @TemplateLineId, @ShiftBandId, @IsOnCallShift, @Notes, @RowNumber, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();

	--SELECT	@RosterShiftID	= IsNull(S_TemplateRoster_Shifts.ShiftId,0)
	--FROM	S_TemplateRoster_Shifts
	--WHERE	TemplateId		=	@TemplateId
	--AND		TemplateLineId	=	@TemplateLineId
	--AND		RowNumber		=	@RowNumber

	--If (@RosterShiftID = 0)
	--Begin	
	--	INSERT INTO S_TemplateRoster_Shifts
	--	(TemplateId, TemplateLineId, ShiftBandId, OnCallShift, Notes, RowNumber, CreatedBy, CreatedDate)
	--	VALUES(@TemplateId, @TemplateLineId, @ShiftBandId, @IsOnCallShift, @Notes, @RowNumber, @CreatedBy, GETDATE())

	--	SELECT SCOPE_IDENTITY();
	--End
	--Else
	--Begin
	--	UPDATE	S_TemplateRoster_Shifts
	--	SET		ShiftBandId		=	@ShiftBandId,
	--			Notes			=	@Notes,
	--			OnCallShift		=	@IsOnCallShift
	--	WHERE	ShiftId			=	@RosterShiftID

	--	SELECT 1;
	--End
	
END
GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterShiftsSel]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterShiftsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterShiftsSel
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterShiftsSel]    Script Date: 20/6/2018 7:07:32 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterShiftsSel]    
(
	@TemplateID	BigInt
)
AS
BEGIN
	SELECT  S_TemplateRoster_Shifts.ShiftId TemplateRosterShiftId,
			S_TemplateRoster_Shifts.TemplateId,
			S_TemplateRoster_Shifts.TemplateLineId,
			S_TemplateRoster_Shifts.ShiftBandId,
			S_TemplateRoster_Shifts.OnCallShift,
			S_TemplateRoster_Shifts.Notes,
			S_TemplateRoster_Shifts.RowNumber,
			S_TemplateRoster_Shifts.CreatedBy,
			S_TemplateRoster_Shifts.CreatedDate,
			S_TemplateRoster_Shifts.UpdatedBy,
			S_TemplateRoster_Shifts.UpdatedDate,
			D_ShiftBand.ShiftBandCode,
			D_ShiftBand.ShiftBandName,
			D_ShiftBand.ShiftBandDesc,
			D_ShiftBand.StartTime,
			D_ShiftBand.EndTime,
			D_ShiftBand.ShiftTypeId,
			D_ShiftBand.OvertimeType OverTimeType,
			D_ShiftBand.OverttimeStart OverTimeStart,
			D_ShiftBand.OvertimeEnd OverTimeEnd,
			D_ShiftBand.ColorCode ShiftBandColorCode,
			IsNull(S_TemplateRosterLine.RosterGroupId,0) RosterGroupId,
			IsNull(S_TemplateRosterLine.EmployeeId,0) EmployeeId
	FROM	S_TemplateRoster_Shifts WITH (NOLOCK)
			INNER JOIN S_TemplateRosterLine WITH (NOLOCK) ON S_TemplateRoster_Shifts.TemplateLineId = S_TemplateRosterLine.TemplateLineId
			INNER JOIN S_TemplateRoster WITH (NOLOCK) ON S_TemplateRoster_Shifts.TemplateId = S_TemplateRoster.TemplateId
			LEFT OUTER JOIN D_ShiftBand WITH (NOLOCK) ON S_TemplateRoster_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	S_TemplateRoster.TemplateId = @TemplateID
	ORDER BY S_TemplateRoster_Shifts.TemplateId, S_TemplateRoster_Shifts.TemplateLineId, S_TemplateRoster_Shifts.RowNumber
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prS_TemplateRosterShiftsUpd') AND type in (N'P', N'PC'))
DROP PROCEDURE prS_TemplateRosterShiftsUpd
GO

CREATE PROCEDURE prS_TemplateRosterShiftsUpd    
(
	@TemplateRosterShiftId BigInt,
	@ShiftBandId		BigInt,
	@IsOnCallShift		Bit,
	@Notes				nVarchar(1000),
	@UpdatedBy			nVarchar(50)
)
AS
--DECLARE @RosterShiftID  BIGINT = 0
BEGIN
	
	UPDATE	S_TemplateRoster_Shifts
	SET		ShiftBandId		=	@ShiftBandId,
			OnCallShift		=	@IsOnCallShift,
			Notes			=	@Notes,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	ShiftId			=	@TemplateRosterShiftId

	SELECT 1
	
END
GO
/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterUpd]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_TemplateRosterUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].prS_TemplateRosterUpd
GO

/****** Object:  StoredProcedure [dbo].[prS_TemplateRosterUpd]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prS_TemplateRosterUpd]    
(
	@TemplateId			BigInt,
	@OUId				BigInt,
	@TemplateName		nVarchar(100),
	@TemplateDesc		nVarchar(1000),
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
	
	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_TemplateRoster WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateName)))	=	LTrim(RTrim(Upper(@TemplateName)))
	AND		S_TemplateRoster.OUId = @OUId
	AND		S_TemplateRoster.TemplateId != @TemplateId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	S_TemplateRoster
		SET		TemplateName		=	@TemplateName,
				TemplateDesc		=	@TemplateDesc,
				ActiveStatus		=	@ActiveStatus,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	TemplateId			=	@TemplateId

		SELECT 1
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateEmployeeLeaveShiftIdByLeaveId')
	DROP PROC prS_UpdateEmployeeLeaveShiftIdByLeaveId
GO
 
Create PROCEDURE prS_UpdateEmployeeLeaveShiftIdByLeaveId  
(
	@ShiftId		BigInt,
	@LeaveId		BigInt,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	UPDATE	S_EmployeeLeaves 
	SET		ShiftId			=	@ShiftId,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	LeaveId			=	@LeaveId

	SELECT 1
END
go

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdatePublicHolidayEmployeeList')
	DROP PROC prS_UpdatePublicHolidayEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_UpdatePublicHolidayEmployeeList
----------------------------------------------------------------------------
CREATE PROC prS_UpdatePublicHolidayEmployeeList
	@EmployeeId		BigInt,
	@TypeId			Int,
	@TypeDesc		nVarchar(500)
AS
BEGIN
	UPDATE	S_PublicholidayEmployeeList
	SET		TypeId		=	@TypeId, 
			TypeDesc	=	@TypeDesc
	WHERE	EmployeeId	=	@EmployeeId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateRamadanPeriodEmployeeList')
	DROP PROC prS_UpdateRamadanPeriodEmployeeList
GO

----------------------------------------------------------------------------
-- Insert a single record into prS_UpdateRamadanPeriodEmployeeList
----------------------------------------------------------------------------
CREATE PROC prS_UpdateRamadanPeriodEmployeeList
	@EmployeeId			BigInt,
	@TypeId				Int,
	@TypeDesc			nVarchar(500),
	@UpdatedBy			nVarchar(50)
AS
BEGIN
	UPDATE	D_RamadanPeriodEmployeeList
	SET		TypeId			=	@TypeId, 
			TypeDescription	=	@TypeDesc
	WHERE	EmployeeId		=	@EmployeeId

	SELECT 1
END
GO
/****** Object:  StoredProcedure [dbo].[prS_UpdateShiftExceptions]    Script Date: 6/20/2018 11:08:41 AM ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_UpdateShiftExceptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_UpdateShiftExceptions]
GO

CREATE PROCEDURE [dbo].[prS_UpdateShiftExceptions]    
(	
	@ShiftExceptionId	BigInt,
	@ShiftId			BigInt,
	@ExceptionCodeId	BigInt,
	@StartTime			DateTime,
	@EndTime			DateTime,
	@ApprovalStatus		Int,
	@Remarks			nVarchar(max),
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	S_ShiftExceptions
	SET		ShiftId				=	@ShiftId, 
			ExceptionCodeId		=	@ExceptionCodeId, 
			StartTime			=	@StartTime, 
			EndTime				=	@EndTime, 
			ApprovalStatus		=	@ApprovalStatus, 
			Remarks				=	@Remarks, 
			UpdatedBy			=	@UpdatedBy,
			UPdatedDate			=	GETDATE()
	WHERE	ShiftExceptionId	=	@ShiftExceptionId

	SELECT @ShiftExceptionId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateShiftReconStatusByShiftId')
	DROP PROC prS_UpdateShiftReconStatusByShiftId
GO

----------------------------------------------------------------------------
-- Change the status of Shift Recon Process to 0, which will re-execute the reconcilation process in next run
----------------------------------------------------------------------------
CREATE PROC prS_UpdateShiftReconStatusByShiftId
	@ShiftId				BigInt,
	@UpdatedBy				nVarchar(50)
AS
BEGIN
	
	UPDATE	S_Shifts 
	SET		ReconTime = Null,
			Reconciled = 0,
			ReconStatusId = null,
			ReconFailureReasonId = NULL,
			ReconFailureReasonDetail= NULL,
			RPGId = null,
			InStatus = null,
			OutStatus = null,
			InTime = null,
			OutTime = null,
			ActualStartTime = ShiftStartTime,
			ActualEndTime = ShiftEndTime,
			UpdatedBy	=	@UpdatedBy
	WHERE ShiftId = @ShiftId 

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateShiftRemarks')
	DROP PROC prS_UpdateShiftRemarks
GO

----------------------------------------------------------------------------
-- Update a single record into prS_UpdateShiftRemarks
----------------------------------------------------------------------------
CREATE PROC prS_UpdateShiftRemarks
	@ShiftId	BigInt,
	@Remarks	nVarchar(max),
	@UpdatedBy	nvarchar(50) = NULL
	
AS

UPDATE	S_Shifts
SET		Remarks			=	@Remarks,
		UpdatedBy		=	@UpdatedBy
WHERE	ShiftId			=	@ShiftId

SELECT 1

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateTHPSettings')
	DROP PROC prS_UpdateTHPSettings
GO

----------------------------------------------------------------------------
-- Update S_THPSettings
----------------------------------------------------------------------------
CREATE PROC prS_UpdateTHPSettings
	@THPSettingsID	BigInt = NULL,
	@OUId			bigint = NULL,
	@StartDate		date = NULL,
	@PeriodUnit		int = NULL,
	@PeriodLength	int = NULL,
	@UpdatedBy		nvarchar(100) = NULL
AS

UPDATE	S_THPSettings 
SET		OUId			=	@OUId, 
		StartDate		=	@StartDate, 
		PeriodUnit		=	@PeriodUnit, 
		PeriodLength	=	@PeriodLength, 
		UpdatedBy		=	@UpdatedBy, 
		UpdatedDate		=	GETDATE()
WHERE	THPSettingId	=	@THPSettingsID

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_WeekShiftsSel')
	DROP PROC prS_WeekShiftsSel
GO

----------------------------------------------------------------------------
-- Insert a single record into prD_ShiftAuditSel
----

create PROCEDURE [dbo].[prS_WeekShiftsSel] 
(
	@ShiftId			Bigint,  
	@OUId				BigInt,
	@StartDate			datetime,
	@EndDate			datetime,
	@EmployeeNumber		nvarchar(50),
	@AttendanceStatusId	int,
	@ReconStatusId		int,
	@EmploymentBasisId  Bigint
)
AS
DECLARE @__shiftBandIds BIGINT = 0
BEGIN	 
			WITH 
		--WorkFlowRoute
		--	AS
		--	(
		--		SELECT	Distinct RouteId 
		--		FROM	W_WorkflowRouteDetails WITH (NOLOCK)
		--		WHERE	EmployeeId = @LoginUserEmployeeId 
		--	), 
			ShiftOverTime (ShiftId, ApprovedOverTimeHours)
			AS
			(
				SELECT  DISTINCT S_Shifts.ShiftId,
						Sum(P_ShiftCosts.ApprovedHours) ApprovedOverTimeHours
						--Sum(DATEDIFF(second, J_Activity.StartTime, J_Activity.EndTime) / 3600.0) TotalHours
				FROM	S_Shifts WITH (NOLOCK) INNER JOIN P_ShiftCosts ON S_Shifts.ShiftId = P_ShiftCosts.ShiftId
						INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId
						--INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId = S_Shifts.EmployeeId
						--INNER JOIN WorkFlowRoute ON C_EmployeeWorkflow.RouteId = WorkFlowRoute.RouteId  AND C_EmployeeWorkflow.ModuleId = 204	
						--LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
						--LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
						--LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
						--LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
				WHERE 	C_OrganizationNode.OUId = @OUId 
				AND		CONVERT(DATETIME,S_Shifts.ActualStartTime)>=CONVERT(DATETIME,@StartDate)
				AND		CONVERT(DATETIME,S_Shifts.ActualStartTime)<=CONVERT(DATETIME,@EndDate)
				--AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@shiftbandid)) OR @__shiftBandIds = 0)
				--AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
				--AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
				--AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
				--AND		(S_Shifts.ShiftId = @ShiftId OR @ShiftId=0)
				--AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
				AND		P_ShiftCosts.PayCodeId NOT IN (1,19)
				GROUP BY S_Shifts.ShiftId
			)
			SELECT	DISTINCT S_Shifts.ShiftId,
					S_Shifts.OUId	, 
					S_Shifts.EmployeeId,
					S_Shifts.TemplateId,
					S_Shifts.RoleId, 
					S_Shifts.RosterGroupId,
					S_Shifts.ShiftBandId,
					S_Shifts.OTStartTime ,
					S_Shifts.ShiftStartTime ,
					S_Shifts.ShiftEndTime ,
					S_Shifts.OTEndTime,
					S_Shifts.ActualStartTime,
					S_Shifts.ActualEndTime,
					S_Shifts.PreparationMins ,
					S_Shifts.DepreparationMins ,
					S_Shifts.OnCallShift,
					S_Shifts.Notes,
					S_Shifts.CombinationShiftId ,
					S_Shifts.ReconTime,
					S_Shifts.ReconStatusId ,
					S_Shifts.RPGId ,
					S_Shifts.ReconFailureReasonId,
					S_Shifts.ReconFailureReasonDetail,
					S_Shifts.Reconciled,
					S_Shifts.InStatus,
					S_Shifts.OutStatus,
					S_Shifts.InTime,
					S_Shifts.OutTime,
					S_Shifts.PickedByTHP,
					S_Shifts.Deployed,
					IsNull(S_EmployeeLeaves.LeaveId,0) LeaveId,
					S_Shifts.CreatedBy,
					S_Shifts.CreatedDate,
					S_Shifts.UpdatedBy	,
					S_Shifts.UpdatedDate,
					C_Employee.EmployeeNumber,
					C_Employee.FirstName + ' ' + C_Employee.LastName AS EmployeeName,
					D_Roles.RoleName,
					D_ShiftBand.ShiftBandName,
					IsNull(TA_ExceptionCodes.ColorCode, IsNull(D_ExceptionCodes.ExcpetionCodeName + '|' + D_ExceptionCodes.ColorCode,'')) ColorCode,
					--IsNull(Activities.TotalHours,0) TotalActivityHours,
					IsNull(ShiftOverTime.ApprovedOverTimeHours,0) ApprovedOverTimeHours,
					S_Shifts.Remarks,
					IsNull(P_ShiftCosts.ApprovalStatus,1) ShiftCostApprovalStatus
		FROM	S_Shifts WITH (NOLOCK)	
				INNER JOIN C_OrganizationNode with (NOLOCK) ON S_Shifts.OUId = C_OrganizationNode.OUId	
				--INNER JOIN C_EmployeeWorkflow WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId = S_Shifts.EmployeeId
				--INNER JOIN WorkFlowRoute ON C_EmployeeWorkflow.RouteId = WorkFlowRoute.RouteId 
				--				AND C_EmployeeWorkflow.ModuleId = 204	
				LEFT OUTER JOIN C_Employee with (NOLOCK) ON C_Employee.EmployeeId= S_Shifts.EmployeeId
				LEFT OUTER JOIN D_Roles with (NOLOCK) ON D_Roles.RoleId= S_Shifts.RoleId
				LEFT OUTER JOIN D_ShiftBand with (NOLOCK) ON D_ShiftBand.ShiftBandId= S_Shifts.ShiftBandId
				LEFT OUTER JOIN TA_ExceptionCodes with (NOLOCK) ON TA_ExceptionCodes.TAExceptionId=S_Shifts.ReconStatusId
				LEFT OUTER JOIN ShiftOverTime WITH (NOLOCK) ON ShiftOverTime.ShiftId = S_Shifts.ShiftId
				LEFT OUTER JOIN P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId --AND P_ShiftCosts.PayCodeId NOT IN (1,19)
				LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId
				LEFT OUTER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
		WHERE 	C_OrganizationNode.OUId = @OUId 		
		AND		CONVERT(DATETIME,S_Shifts.ActualStartTime)>=CONVERT(DATETIME,@StartDate)
		AND		CONVERT(DATETIME,S_Shifts.ActualStartTime)<=CONVERT(DATETIME,@EndDate)		
		AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
		AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
		AND		(S_Shifts.InStatus = @AttendanceStatusId OR S_Shifts.OutStatus = @AttendanceStatusId OR @AttendanceStatusId = 0)
		AND		(S_Shifts.ShiftId = @ShiftId OR @ShiftId=0)
		AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
		AND     (C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
		Order By S_Shifts.EmployeeId
	END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prTA_AddClockOutTimeChangeShiftReconStatus')
	DROP PROC prTA_AddClockOutTimeChangeShiftReconStatus
GO

CREATE PROCEDURE prTA_AddClockOutTimeChangeShiftReconStatus
(
	@TypeId					Int,
	@CardNo					nVarchar(50),
	@TerminalName			nVarchar(50),
	@SwipeDateTime			DateTime,
	@EmployeeNo				nVarchar(50),
	@EmployeeId				BigInt,
	@ShiftId				BigInt,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN	 
	
	UPDATE	S_Shifts 
	SET		Remarks						=	@TerminalName,
			ReconTime					=	Null,
			Reconciled					=	0,
			ReconStatusId				=	null,
			ReconFailureReasonId		=	NULL,
			ReconFailureReasonDetail	=	NULL,
			RPGId						=	NULL,
			ActualStartTime				=	ShiftStartTime,
			ActualEndTime				=	ShiftEndTime,
			UpdatedBy					=	@CreatedBy
	WHERE	ShiftId						=	@ShiftId 

	INSERT INTO TA_Rawclocking
	(TypeId, SwipeDateTime, EmployeeNo, EmployeeId, CollectionDateTime, Allocated, CreatedBy, CreatedDate)
	VALUES(@TypeId, @SwipeDateTime, @EmployeeNo, @EmployeeId, GETDATE(), 1, @CreatedBy, GETDATE())
	
	SELECT  CAST(@@Identity AS bigint)   
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ExceptionCodesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ExceptionCodesSel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ExceptionCodesSel]    Script Date: 8/3/2018 2:19:21 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


Create PROCEDURE [dbo].[prTA_ExceptionCodesSel]    
(
	@TAExceptionId			Numeric(18,0)
	
)
AS
BEGIN
	SELECT	TAExceptionId,
			TAException,
			ColorCode,
			ActiveStatus,
			CreatedBy,
			CreatedDate			
	FROM	TA_ExceptionCodes WITH (NOLOCK)  
	WHERE	(TAExceptionId= @TAExceptionId	 OR @TAExceptionId	= 0)
	ORDER BY TAException
END
go


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ExceptionCodesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ExceptionCodesUpd]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ExceptionCodesUpd]    Script Date: 8/3/2018 2:20:25 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prTA_ExceptionCodesUpd]   
(
	@TAExceptionId			BigInt,
	@TAException		nvarchar(1000),
	@ColorCode			nVarchar(50), 
	@ActiveStatus			Bit 
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	  @ValidateDuplicate=COUNT(*)
	FROM	TA_ExceptionCodes WITH (NOLOCK)
	WHERE	 LTrim(RTrim(Upper(TAException))) = LTrim(RTrim(Upper(@TAException)))
	and TAExceptionId != @TAExceptionId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	TA_ExceptionCodes
				SET	ColorCode				=	@ColorCode, 				 
				ActiveStatus				=	@ActiveStatus
		WHERE	TAExceptionId				=	@TAExceptionId
					
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_GetShiftByEmployeeSwipeTransById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_GetShiftByEmployeeSwipeTransById]
GO

/****** Object:  StoredProcedure [dbo].[prTA_GetShiftByEmployeeSwipeTransById]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_GetShiftByEmployeeSwipeTransById]    
(
	@EmployeeId		BigInt,
	@SwipeDateTime	DateTime
)
AS
BEGIN
	SELECT	S_Shifts.ActualStartTime ShiftActualStart, 
			S_Shifts.ActualEndTime ShiftActualEnd, 
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime,
			S_Shifts.ShiftId, 
			TA_RPGOU.OUId, 
			S_Shifts.EmployeeId, 
			TA_RPGRoles.RoleId, 
			S_SHIFTS.ShiftBandId, 
			TA_RPGConfig.RPGId,
			TA_RPGConfig.ClockingIdentificationMethod,
			IsNull(S_EmployeeLeaves.LeaveId,0) LeaveId,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftInEarly,S_Shifts.ActualStartTime) ReconShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate, S_Shifts.ActualStartTime) ReconShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftOutEarly, S_Shifts.ActualEndTime) ReconShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, S_Shifts.ActualEndTime) ReconShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftInEarly,S_Shifts.ActualStartTime) ReconGranularShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate, S_Shifts.ActualStartTime) ReconGranularShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftOutEarly, S_Shifts.ActualEndTime) ReconGranularShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate, S_Shifts.ActualEndTime) ReconGranularShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftInEarly,S_Shifts.ActualStartTime) ReconToPlanShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,S_Shifts.ActualStartTime) ReconToPlanShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftOutEarly,S_Shifts.ActualEndTime) ReconToPlanShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,S_Shifts.ActualEndTime) ReconToPlanShiftOutLate,
			TA_RPGConfig.ReconGranularShiftInEarly GranularityInEarlyMin,
			TA_RPGConfig.ReconGranularShiftInLate GranularityInLateMin,
			TA_RPGConfig.ReconGranularShiftOutEarly GranularityOutEarlyMin,
			TA_RPGConfig.ReconGranularShiftOutLate GranularityOutLateMin,
			C_Employee.OvertimeId, C_Employee.HourlyRate,
			IsNull(S_PublicholidayEmployeeList.TypeId,0) PublicHolidayTypeId,
			IsNull(D_RamadanPeriodEmployeeList.TypeId,0) RamadanPeriodTypeId,
			C_Employee.PayGroupId,
			Convert(bit, IsNull(P_OvertimeSettings.ApprovalRequired,0)) OverTimeApprovalRequired,
			InTime, OutTime, InStatus, OutStatus
	FROM	S_Shifts WITH (NOLOCK) INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN TA_RPGRoles WITH (NOLOCK) ON S_Shifts.RoleId = TA_RPGRoles.RoleId 
			INNER JOIN TA_RPGConfig WITH (NOLOCK) ON TA_RPGConfig.RPGId = TA_RPGRoles.RPGId
			INNER JOIN TA_RPGOU WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId AND S_Shifts.OUId = TA_RPGOU.OUId
			LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_Shifts.ShiftId = S_EmployeeLeaves.ShiftId
			LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN D_RamadanPeriodEmployeeList WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OvertimeId
	WHERE	DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, S_Shifts.ShiftEndTime) >= Convert(DateTime,@SwipeDateTime)
	AND		DATEADD(MINUTE,-TA_RPGConfig.ReconShiftInEarly,S_Shifts.ShiftStartTime) <= Convert(DateTime,@SwipeDateTime)
	AND		(S_Shifts.ShiftBandId != S_Shifts.CombinationShiftId OR S_Shifts.CombinationShiftId IS NULL)
	AND		S_Shifts.EmployeeId	= @EmployeeId
	ORDER BY S_Shifts.ActualStartTime
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prTA_GetShiftsByClockOutTimeRange')
	DROP PROC prTA_GetShiftsByClockOutTimeRange
GO

CREATE PROCEDURE prTA_GetShiftsByClockOutTimeRange
(
	@EmployeeNumber			nVarchar(100),
	@OUId					BigInt,
	@ShiftBandId			BigInt,
	@RamadanEmployeeTypeId	Int,
	@ShiftStartDate			DateTime,
	@ShiftEndDate			DateTime,
	@OutTimeRangeFrom		DateTime,
	@OutTimeRangeTo			DateTime
)
AS
BEGIN	 
	SELECT	S_Shifts.ShiftId, 
			C_Employee.EmployeeId, 
			S_SHifts.ShiftBandId,
			S_Shifts.RoleId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			D_Roles.RoleName,
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime,
			S_Shifts.InTime,
			S_Shifts.OutTime,
			S_Shifts.Reconciled,
			S_SHifts.ReconTime ReconDateTime
	FROM	S_Shifts WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_SHifts.RoleId
			LEFT OUTER JOIN D_RamadanPeriodEmployeeList WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = C_Employee.EmployeeId
	WHERE	S_Shifts.OUId	=	@OUId
	AND		Convert(Date,ActualStartTime)		>=	Convert(Date,@ShiftStartDate)
	AND		Convert(Date,ActualStartTime)		<=	Convert(Date,@ShiftEndDate)
	AND		Convert(Time,OutTime)				>=	Convert(Time,@OutTimeRangeFrom)
	AND		Convert(Time,OutTime)				<=	Convert(Time,@OutTimeRangeTo)
	AND		S_Shifts.ShiftBandId				=	@ShiftBandId
	AND		S_Shifts.Reconciled					=	1
	AND		(D_RamadanPeriodEmployeeList.TypeId	=	@RamadanEmployeeTypeId OR @RamadanEmployeeTypeId = 0)
	AND		(C_Employee.EmployeeNumber LIKE ('%' + @EmployeeNumber + '%') 
	OR		 C_Employee.DisplayName LIKE ('%' + @EmployeeNumber + '%') )
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prTA_GetShiftsToReProcess')
	DROP PROC prTA_GetShiftsToReProcess
GO

CREATE PROCEDURE prTA_GetShiftsToReProcess
(
	@EmployeeIds	nVarchar(Max),
	@OUId			BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
	-- Retrieve List Of Shifts Between Start And End Of Schedule Period Dates By OU And Selected Employee Ids
	--WITH SchedulePeriodDates (StartDate, EndDate) AS
	--(
	--	SELECT	Min(StartDate) StartDate, 
	--			Max(EndDate) EndDate 
	--	FROM	S_SchedulePeriod
	--	WHERE	Convert(Date, EndDate)		> Convert(Date,@StartDate)
	--	AND		Convert(Date, StartDate)	< Convert(Date,@EndDate)
	--	AND		OUID = @OUId 
	--)
	SELECT	S_Shifts.ActualStartTime ShiftActualStart, 
			S_Shifts.ActualEndTime ShiftActualEnd, 
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime,
			S_Shifts.ShiftId, 
			TA_RPGOU.OUId, 
			S_Shifts.EmployeeId,
			S_Shifts.OnCallShift, 
			TA_RPGRoles.RoleId, 
			S_SHIFTS.ShiftBandId, 
			TA_RPGConfig.RPGId,
			TA_RPGConfig.ClockingIdentificationMethod,
			IsNull(S_EmployeeLeaves.LeaveId,0) LeaveId,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftInEarly,S_Shifts.OTStartTime) ReconShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate, S_Shifts.OTStartTime) ReconShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftOutEarly, S_Shifts.OTEndTime) ReconShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, S_Shifts.OTEndTime) ReconShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftInEarly,S_Shifts.OTStartTime) ReconGranularShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate, S_Shifts.OTStartTime) ReconGranularShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftOutEarly, S_Shifts.OTEndTime) ReconGranularShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate, S_Shifts.OTEndTime) ReconGranularShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftInEarly,S_Shifts.OTStartTime) ReconToPlanShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,S_Shifts.OTStartTime) ReconToPlanShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftOutEarly,S_Shifts.OTEndTime) ReconToPlanShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,S_Shifts.OTEndTime) ReconToPlanShiftOutLate,
			TA_RPGConfig.ReconGranularShiftInEarly GranularityInEarlyMin,
			TA_RPGConfig.ReconGranularShiftInLate GranularityInLateMin,
			TA_RPGConfig.ReconGranularShiftOutEarly GranularityOutEarlyMin,
			TA_RPGConfig.ReconGranularShiftOutLate GranularityOutLateMin,
			C_Employee.OvertimeId, Convert(float,C_Employee.HourlyRate) HourlyRate,
			IsNull(S_PublicholidayEmployeeList.TypeId,0) PublicHolidayTypeId,
			IsNull(D_RamadanPeriodEmployeeList.TypeId,0) RamadanPeriodTypeId,
			C_Employee.PayGroupId,
			Convert(bit, IsNull(P_OvertimeSettings.ApprovalRequired,0)) OverTimeApprovalRequired,
			IsNull(S_Shifts.ReconStatusId,0) ReconciliationStatusId
	FROM	S_Shifts WITH (NOLOCK) INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN TA_RPGRoles WITH (NOLOCK) ON S_Shifts.RoleId = TA_RPGRoles.RoleId 
			INNER JOIN TA_RPGConfig WITH (NOLOCK) ON TA_RPGConfig.RPGId = TA_RPGRoles.RPGId
			INNER JOIN TA_RPGOU WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId AND S_Shifts.OUId = TA_RPGOU.OUId
			LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_Shifts.ShiftId = S_EmployeeLeaves.ShiftId
			LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN D_RamadanPeriodEmployeeList WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OvertimeId
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date, @StartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date, @EndDate)
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND		S_SHifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeIds))	

END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawclockingByEmployeeNoSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawclockingByEmployeeNoSel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_RawclockingByEmployeeNoSel]    Script Date: 8/8/2018 5:20:51 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prTA_RawclockingByEmployeeNoSel]   
(
	@EmployeeNo	 BigInt  
	
)
AS
BEGIN	 
	SELECT  	TA_Rawclocking.ClockingId,
			    TA_Rawclocking.TypeId	, 
				TA_Rawclocking.CardNo,
				TA_Rawclocking. TerminalName,
				--TA_Rawclocking.SwipeDateTime, 
				convert(nvarchar,SwipeDateTime) as ConSwipeDateTime,
				TA_Rawclocking.EmployeeNo ,				 
				TA_Rawclocking.EmployeeId ,
				TA_Rawclocking.CollectionDateTime ,
				TA_Rawclocking.Allocated, 
				TA_Rawclocking.ReconDate,
				TA_Rawclocking.ReconBy,
				TA_Rawclocking.CreatedBy,
				TA_Rawclocking.CreatedDate
	    FROM	TA_Rawclocking 		 
	WHERE	(EmployeeId = @EmployeeNo)	 
	Order By SwipeDateTime desc
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawClockingDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawClockingDel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_RawClockingDel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_RawClockingDel]    
(
	@ClockingId				BigInt
)
AS
BEGIN
	
	DELETE FROM TA_Rawclocking
	WHERE	ClockingId			=	@ClockingId

	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawclockingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawclockingIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 

Create PROCEDURE [dbo].[prTA_RawclockingIns]    
(
	@TypeId					int,
	@CardNo					nvarchar(50),
	@TerminalName			nVarchar(50),
	@SwipeDateTime			datetime,
	@EmployeeNo				nvarchar(50),
	@EmployeeId				bigint,
	@Allocated				bit,
	@ReconDate				datetime ,
	@ShiftId				BigInt, -- Shift ID To Update Shift Start / End Time Based on @Allocated Status And @Type
	@ShiftBandStartDateTime	DateTime,
	@ShiftBandEndDateTime	DateTime,
	@ReconBy				nvarchar(50),
	@CreatedBy				nvarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	TA_Rawclocking WITH (NOLOCK)
	WHERE	TypeId = @TypeId and EmployeeId=@EmployeeId and SwipeDateTime = @SwipeDateTime

	If (@ValidateDuplicate = 0)
	BEGIN
	SELECT	@EmployeeNo =  EmployeeNumber
	FROM	C_Employee WITH (NOLOCK)
	WHERE	EmployeeId  =@EmployeeId 

		INSERT INTO TA_Rawclocking
		(TypeId, CardNo, TerminalName, SwipeDateTime, EmployeeNo, EmployeeId, 
		 Allocated, ReconDate,ReconBy,CreatedBy,CreatedDate)
		VALUES
		(
			@TypeId, @CardNo, @TerminalName, @SwipeDateTime, @EmployeeNo, @EmployeeId, 
			@Allocated, @ReconDate,@ReconBy ,@CreatedBy,GETDATE()
		)

		If (@Allocated = 1 AND @ShiftId != 0)
		BEGIN

			-- Update RawClocking Allocated To Shift Value to False for All In And Out by type
			UPDATE	TA_Rawclocking
			SET		Allocated		=	0
			WHERE	TypeId			=	@TypeId 
			AND		EmployeeId		=	@EmployeeId 
			AND		SwipeDateTime	>=	@ShiftBandStartDateTime
			AND		SwipeDateTime	<=	@ShiftBandEndDateTime
			AND		SwipeDateTime	!=	@SwipeDateTime

			If (@TypeId = 1)
			BEGIN
				UPDATE	S_Shifts 
				SET		--ShiftStartTime				=	@SwipeDateTime,
						ActualStartTime				=	@SwipeDateTime,
						InTime						=	@SwipeDateTime,
						InStatus					=	9,
						ReconStatusId				=	1,
						ReconFailureReasonId		=	NULL,
						ReconFailureReasonDetail	=	NULL
				WHERE	ShiftId						=	@ShiftId
			END
			Else If (@TypeId = 2)
			BEGIN
				UPDATE	S_Shifts 
				SET		--ShiftEndTime				=	@SwipeDateTime,
						ActualEndTime				=	@SwipeDateTime,
						OutTime						=	@SwipeDateTime,
						OutStatus					=	9,
						ReconStatusId				=	1,
						ReconFailureReasonId		=	NULL,
						ReconFailureReasonDetail	=	NULL
				WHERE	ShiftId						=	@ShiftId
			END
		END

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawClockingRangeSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawClockingRangeSel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_RawClockingRangeSel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_RawClockingRangeSel]    
(
	@EmployeeId		BIGINT,
	@StartDateTime	DATETIME,
	@EndDateTime	DATETIME,
	@OUId			BigInt = NULL
)
AS
BEGIN
	SELECT	ClockingId,
			TypeId,
			CardNo,
			TerminalName,
			SwipeDateTime,
			--Convert(nVarchar,SwipeDateTime) ConSwipeDateTime,
			EmployeeNo,
			EmployeeId,
			CollectionDateTime,
			Allocated,
			ReconDate,
			ReconBy,
			CreatedBy,
	        CreatedDate
	FROM	TA_Rawclocking WITH (NOLOCK)
	WHERE	Convert(Date,SwipeDateTime)  >= Convert(Date,@StartDateTime)
	AND 	Convert(Date,SwipeDateTime)  <= Convert(Date,@EndDateTime)
	AND		(EmployeeId = @EmployeeId OR @EmployeeId = 0)
	ORDER BY SwipeDateTime
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawclockingSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawclockingSel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_RawclockingSel]    Script Date: 8/8/2018 5:23:56 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prTA_RawclockingSel]   
(
	@EmployeeNo		BigInt,
	@SwipeDateTime	datetime,
	@OUId			BigInt
)
AS
BEGIN	 
	SELECT  TA_Rawclocking.ClockingId,
			TA_Rawclocking.TypeId	, 
			TA_Rawclocking.CardNo,
			TA_Rawclocking. TerminalName,
			TA_Rawclocking.SwipeDateTime,
			--convert(nvarchar,SwipeDateTime) as ConSwipeDateTime, 
			TA_Rawclocking.EmployeeNo ,				 
			TA_Rawclocking.EmployeeId ,
			TA_Rawclocking.CollectionDateTime ,
			TA_Rawclocking.Allocated, 
			TA_Rawclocking.ReconDate,
			TA_Rawclocking.ReconBy,
			TA_Rawclocking.CreatedBy,
			TA_Rawclocking.CreatedDate
	FROM	TA_Rawclocking WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = TA_Rawclocking.EmployeeId		 
	WHERE	(TA_Rawclocking.EmployeeId = @EmployeeNo OR @EmployeeNo = 0) 
	And		CONVERT(DATE,TA_Rawclocking.SwipeDateTime)	=	CONVERT(DATE,@SwipeDateTime)
	AND		C_Employee.OUId		=	@OUId
	Order By SwipeDateTime desc
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_RawClockingUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_RawClockingUpd]
GO

/****** Object:  StoredProcedure [dbo].[prTA_RawClockingUpd]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_RawClockingUpd]    
(
	@ClockingId					BigInt,
	@TypeId						Int,
	@CardNo						nVarchar(50),
	@TerminalName				nVarchar(50),
	@SwipeDateTime				DateTime,
	@Allocated					Bit,
	@ShiftBandStartDateTime		DateTime,
	@ShiftBandEndDateTime		DateTime,
	@EmployeeId					BigInt,
	@ShiftId					BigInt
)
AS
BEGIN


	If (@Allocated = 1)
	BEGIN
		UPDATE	TA_Rawclocking	
		SET		Allocated		=	0
		WHERE	SwipeDateTime	>=	@ShiftBandStartDateTime 
		AND		SwipeDateTime	<=	@ShiftBandEndDateTime
		AND		TypeId			=	@TypeId
		AND		EmployeeId		=	@EmployeeId

		If (@TypeId = 1)
			BEGIN
				UPDATE	S_Shifts 
				SET		ShiftStartTime				=	@SwipeDateTime,
						ActualStartTime				=	@SwipeDateTime,
						InTime						=	@SwipeDateTime,
						InStatus					=	9,
						ReconStatusId				=	1,
						ReconFailureReasonId		=	NULL,
						ReconFailureReasonDetail	=	NULL
				WHERE	ShiftId						=	@ShiftId
			END
			Else If (@TypeId = 2)
			BEGIN
				UPDATE	S_Shifts 
				SET		ShiftEndTime				=	@SwipeDateTime,
						ActualEndTime				=	@SwipeDateTime,
						OutTime						=	@SwipeDateTime,
						OutStatus					=	9,
						ReconStatusId				=	1,
						ReconFailureReasonId		=	NULL,
						ReconFailureReasonDetail	=	NULL
				WHERE	ShiftId						=	@ShiftId
			END
	END
	
	UPDATE	TA_Rawclocking
	SET		TypeId				=	@TypeId,
			CardNo				=	@CardNo,
			TerminalName		=	@TerminalName,
			SwipeDateTime		=	SwipeDateTime,
			Allocated			=	@Allocated,
			ReconBy				=	NULL,
			ReconDate			=	NULL
	WHERE	ClockingId			=	@ClockingId

	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciledRawClockingUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciledRawClockingUpd]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciledRawClockingUpd]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciledRawClockingUpd]    
(
	@ClockingId				BigInt,
	@ReconDate				DateTime,
	@ReconBy				nVarchar(50),
	@Allocated				Bit
)
AS
BEGIN
	
	UPDATE	TA_Rawclocking
	SET		Allocated			=	@Allocated,
			ReconBy				=	@ReconBy,
			ReconDate			=	@ReconDate
	WHERE	ClockingId			=	@ClockingId

	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamDel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamDel]    Script Date: 17/7/2018 10:15:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prTA_ReconciliationParamDel]
(
	@RPGId				BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	TA_RPGConfig
	SET		ActiveStatus			=	0,
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GetDate()
	WHERE	RPGId	=	@RPGId

	SELECT 1
END 
Go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamIns]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamIns]    Script Date: 7/17/2018 9:42:02 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prTA_ReconciliationParamIns]    
(	
	@RPGName						nVarchar(500),
	@ReconcilDesc					nVarchar(1000),
	@ReconShiftInEarly				Int,
	@ReconShiftInLate				int,
	@ReconShiftOutEarly				int,
	@ReconShiftOutLate				int,
	@ReconGranularShiftInEarly		int,
	@ReconGranularShiftInLate		int,
	@ReconGranularShiftOutEarly		int,
	@ReconGranularShiftOutLate		int,
	@ReconToPlanShiftInEarly		int,
	@ReconToPlanShiftInLate			int,
	@ReconToPlanShiftOutEarly		int,
	@ReconToPlanShiftOutLate		int,
	@ClockingIdentificationMethod	int,
	@IsActive						bit,
	@CreatedBy						nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	TA_RPGConfig WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RPGName))) = LTrim(RTrim(Upper(@RPGName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO TA_RPGConfig
		(RPGName, Description, ReconShiftInEarly, ReconShiftInLate,ReconShiftOutEarly,ReconShiftOutLate,ReconGranularShiftInEarly,ReconGranularShiftInLate,
		ReconGranularShiftOutEarly,ReconGranularShiftOutLate,ReconToPlanShiftInEarly,ReconToPlanShiftInLate,ReconToPlanShiftOutEarly,
		ReconToPlanShiftOutLate,ActiveStatus,ClockingIdentificationMethod, CreatedBy,CreatedDate)
		VALUES(@RPGName, @ReconcilDesc, @ReconShiftInEarly, @ReconShiftInLate,@ReconShiftOutEarly,@ReconShiftOutLate,
		@ReconGranularShiftInEarly,@ReconGranularShiftInLate,@ReconGranularShiftOutEarly,@ReconGranularShiftOutLate,
		@ReconToPlanShiftInEarly,@ReconToPlanShiftInLate,@ReconToPlanShiftOutEarly,@ReconToPlanShiftOutLate,
		@ClockingIdentificationMethod, @IsActive,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamOUDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamOUDel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamOUDel]    Script Date: 17/7/2018 10:42:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prTA_ReconciliationParamOUDel]    
(	
	@RPGId			BigInt,
	@OUID			BigInt
)
AS
BEGIN
	DELETE FROM TA_RPGOU
	WHERE	OUId = @OUID
	AND		RPGId = @RPGId
	SELECT 1
	 
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamOUIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamOUIns]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamOUIns]    Script Date: 17/7/2018 10:36:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[prTA_ReconciliationParamOUIns]    
(
	@RPGId				BigInt,
	@OUId				BigInt,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @RPGOUId BigInt = 0;
BEGIN

	SELECT	@RPGOUId = IsNull(RPGOUId,0)
	FROM	TA_RPGOU WITH (NOLOCK)
	WHERE	RPGId	=	@RPGId
	AND		OUId	=	@OUId

	If (@RPGOUId = 0)
	BEGIN
		INSERT INTO TA_RPGOU
		(RPGId, OUId, CreatedBy, CreatedDate)
		VALUES(@RPGId, @OUId, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else 
	BEGIN
		SELECT -1; 
	END
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamOUSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamOUSel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamOUSel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciliationParamOUSel]    
(
	@RPGId	BigInt
)
AS
BEGIN
	SELECT	TA_RPGOU.RPGOUId,
			TA_RPGConfig.RPGId,
			TA_RPGOU.OUId,
			TA_RPGOU.CreatedBy, 
			TA_RPGOU.CreatedDate,
			orgNode.OUName, orgNode.ParentOUId ParentOUId
	FROM	TA_RPGOU WITH (NOLOCK) 
			INNER JOIN TA_RPGConfig WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId
			INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON OrgNode.OUId = TA_RPGOU.OUId  
	WHERE	(TA_RPGOU.RPGId		=	@RPGId OR @RPGId = 0)
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamRolesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamRolesDel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamRolesDel]    Script Date: 7/14/2018 4:41:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prTA_ReconciliationParamRolesDel]    
(
	@RPGId		BigInt,
	@RoleId		BigInt
)
AS
BEGIN
	DELETE	FROM TA_RPGRoles
	WHERE	RoleId	=	@RoleId 
	AND		RPGId	=	@RPGId

	SELECT 1;
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamRolesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamRolesIns]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamRolesIns]    Script Date: 7/14/2018 4:41:12 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 

CREATE PROCEDURE [dbo].[prTA_ReconciliationParamRolesIns]    
(
	@RPGId		BigInt,
	@RoleId		BigInt,
	@CreatedBy	nVarchar(50)
)
AS
BEGIN
	INSERT INTO TA_RPGRoles
	(RPGId, RoleId,CreatedBy, CreatedDate)
	VALUES(@RPGId, @RoleId, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamRolesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamRolesSel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamRolesSel]    Script Date: 7/17/2018 10:22:35 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prTA_ReconciliationParamRolesSel]    
(
	@RPGId				Numeric(18,0)
)
AS
BEGIN
	SELECT	TA_RPGRoles.RPGId,
			TA_RPGRoles.RPGRoleId,
			TA_RPGRoles.RoleId,
			D_Roles.RoleName,
			D_ROLES.RoleDesc RoleDescription
	FROM	TA_RPGRoles 
			INNER JOIN TA_RPGConfig ON TA_RPGRoles.RPGId = TA_RPGConfig.RPGId
			INNER JOIN D_Roles ON TA_RPGRoles.RoleId = D_ROLES.RoleId
	WHERE	(TA_RPGRoles.RPGId = @RPGId OR @RPGId = 0)
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamSel]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamSel]    Script Date: 7/17/2018 10:22:35 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prTA_ReconciliationParamSel]    
(
	@RPGId				Numeric(18,0),
	@OUID				BigInt
)
AS
DECLARE @CurrentDate DATETIME = Convert(Date,GETDATE())
BEGIN
	SELECT	TA_RPGConfig.RPGId,
			TA_RPGConfig.RPGName,
			TA_RPGConfig.Description,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInEarly,@CurrentDate) ReconShiftInEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate,@CurrentDate) ReconShiftInLateTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutEarly,@CurrentDate) ReconShiftOutEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate,@CurrentDate) ReconShiftOutLateTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInEarly,@CurrentDate) ReconGranularShiftInEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate,@CurrentDate) ReconGranularShiftInLateTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutEarly,@CurrentDate) ReconGranularShiftOutEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate,@CurrentDate) ReconGranularShiftOutLateTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInEarly,@CurrentDate) ReconToPlanShiftInEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,@CurrentDate) ReconToPlanShiftInLateTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutEarly,@CurrentDate) ReconToPlanShiftOutEarlyTime,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,@CurrentDate) ReconToPlanShiftOutLateTime,
			ClockingIdentificationMethod,
			TA_RPGConfig.ActiveStatus,
			TA_RPGConfig.CreatedBy, 
			TA_RPGConfig.CreatedDate,
			TA_RPGConfig.UpdatedBy,
			TA_RPGConfig.UpdatedDate
	FROM	TA_RPGConfig	  WITH (NOLOCK)
			INNER JOIN TA_RPGOU WITH (NOLOCK)  ON TA_RPGConfig.RPGId  = TA_RPGOU.RPGId
			INNER JOIN C_OrganizationNode with (NOLOCK) ON TA_RPGOU.OUId = C_OrganizationNode.OUId
	WHERE	(TA_RPGConfig.RPGId = @RPGId OR @RPGId = 0)
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
	ORDER BY TA_RPGConfig.RPGName
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationParamUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationParamUpd]
GO
/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationParamUpd]    Script Date: 7/17/2018 10:00:01 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciliationParamUpd]    
(
	@RPGId							BigInt,
	@RPGName						nVarchar(50),
	@ReconcilDesc					nVarchar(500),
	@ReconShiftInEarly				Int,
	@ReconShiftInLate				Int,
	@ReconShiftOutEarly				int,
	@ReconShiftOutLate				int,
	@ReconGranularShiftInEarly		int,
	@ReconGranularShiftInLate		int,
	@ReconGranularShiftOutEarly		int,
	@ReconGranularShiftOutLate		int,
	@ReconToPlanShiftInEarly		int,
	@ReconToPlanShiftInLate			int,
	@ReconToPlanShiftOutEarly		int,
	@ReconToPlanShiftOutLate		int,	
	@ClockingIdentificationMethod	int,
	@IsActive						Bit,
	@UpdatedBy						nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	TA_RPGConfig WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RPGId))) = LTrim(RTrim(Upper(@RPGId)))
	AND		RPGId	!=	@RPGId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	TA_RPGConfig
		SET		RPGName							=	@RPGName, 
				Description						=	@ReconcilDesc, 
				ReconShiftInEarly				=	@ReconShiftInEarly,
				ReconShiftInLate				=	@ReconShiftInLate,
				ReconShiftOutEarly				=	@ReconShiftOutEarly,
				ReconShiftOutLate				=	@ReconShiftOutLate,
				ReconGranularShiftInEarly		=	@ReconGranularShiftInEarly,
				ReconGranularShiftInLate		=	@ReconGranularShiftInLate,
				ReconGranularShiftOutEarly		=	@ReconGranularShiftOutEarly,
				ReconGranularShiftOutLate		=	@ReconGranularShiftOutLate,
				ReconToPlanShiftInEarly			=	@ReconToPlanShiftInEarly,
				ReconToPlanShiftInLate			=	@ReconToPlanShiftInLate,
				ReconToPlanShiftOutEarly		=	@ReconToPlanShiftOutEarly,
				ReconToPlanShiftOutLate			=	@ReconToPlanShiftOutLate,
				ClockingIdentificationMethod 	=	@ClockingIdentificationMethod,
				ActiveStatus					=	@IsActive, 
				UpdatedBy						=	@UpdatedBy,
				UpdatedDate						=	GETDATE()				
		WHERE	RPGId							=	@RPGId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
Go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationProcessShiftExceptions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationProcessShiftExceptions]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationProcessShiftExceptions]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciliationProcessShiftExceptions]    
(
	@ShiftId	BigInt
)
AS
BEGIN
	DECLARE @ReconProcessBuffer INT  = 0

	SELECT  @ReconProcessBuffer = Convert(INT,ParamValue)
	FROM	D_SystemParams 
	WHERE	ParamName	= 'ReconProcessBufferMinutes'

	
	SELECT	S_ShiftExceptions.ShiftExceptionId,
			S_ShiftExceptions.ShiftId,
			S_ShiftExceptions.ExceptionCodeId,
			S_ShiftExceptions.StartTime,
			S_ShiftExceptions.EndTime,
			S_ShiftExceptions.Remarks 
	FROM	S_ShiftExceptions WITH (NOLOCK) 
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_ShiftExceptions.ShiftId = S_Shifts.ShiftId
	WHERE	(S_Shifts.ShiftId = @ShiftId 
			OR (@ShiftId = 0 AND S_Shifts.Reconciled = 0 
			AND S_Shifts.ActualEndTime <= DATEADD(MINUTE,-@ReconProcessBuffer,GETDATE())))
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationProcessShiftSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationProcessShiftSel]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationProcessShiftSel]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciliationProcessShiftSel]    
(
	@ShiftId	BigInt
)
AS
BEGIN
	DECLARE @ReconProcessBuffer INT  = 0

	SELECT  @ReconProcessBuffer = Convert(INT,ParamValue)
	FROM	D_SystemParams 
	WHERE	ParamName	= 'ReconProcessBufferMinutes'

	
	SELECT	S_Shifts.ActualStartTime ShiftActualStart, 
			S_Shifts.ActualEndTime ShiftActualEnd, 
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime,
			S_Shifts.ShiftId, 
			TA_RPGOU.OUId, 
			S_Shifts.EmployeeId,
			S_Shifts.OnCallShift, 
			TA_RPGRoles.RoleId, 
			S_SHIFTS.ShiftBandId, 
			TA_RPGConfig.RPGId,
			TA_RPGConfig.ClockingIdentificationMethod,
			IsNull(S_EmployeeLeaves.LeaveId,0) LeaveId,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftInEarly,S_Shifts.ActualStartTime) ReconShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate, S_Shifts.ActualStartTime) ReconShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftOutEarly, S_Shifts.ActualEndTime) ReconShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, S_Shifts.ActualEndTime) ReconShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftInEarly,S_Shifts.ActualStartTime) ReconGranularShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate, S_Shifts.ActualStartTime) ReconGranularShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftOutEarly, S_Shifts.ActualEndTime) ReconGranularShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate, S_Shifts.ActualEndTime) ReconGranularShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftInEarly,S_Shifts.ActualStartTime) ReconToPlanShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,S_Shifts.ActualStartTime) ReconToPlanShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftOutEarly,S_Shifts.ActualEndTime) ReconToPlanShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,S_Shifts.ActualEndTime) ReconToPlanShiftOutLate,
			TA_RPGConfig.ReconGranularShiftInEarly GranularityInEarlyMin,
			TA_RPGConfig.ReconGranularShiftInLate GranularityInLateMin,
			TA_RPGConfig.ReconGranularShiftOutEarly GranularityOutEarlyMin,
			TA_RPGConfig.ReconGranularShiftOutLate GranularityOutLateMin,
			C_Employee.OvertimeId, Convert(float,C_Employee.HourlyRate) HourlyRate,
			IsNull(S_PublicholidayEmployeeList.TypeId,0) PublicHolidayTypeId,
			IsNull(D_RamadanPeriodEmployeeList.TypeId,0) RamadanPeriodTypeId,
			C_Employee.PayGroupId,
			Convert(bit, IsNull(P_OvertimeSettings.ApprovalRequired,0)) OverTimeApprovalRequired,
			S_Shifts.ReconStatusId ReconciliationStatusId
	FROM	S_Shifts WITH (NOLOCK) INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN TA_RPGRoles WITH (NOLOCK) ON S_Shifts.RoleId = TA_RPGRoles.RoleId 
			INNER JOIN TA_RPGConfig WITH (NOLOCK) ON TA_RPGConfig.RPGId = TA_RPGRoles.RPGId
			INNER JOIN TA_RPGOU WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId AND S_Shifts.OUId = TA_RPGOU.OUId
			LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_Shifts.ShiftId = S_EmployeeLeaves.ShiftId
			LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN D_RamadanPeriodEmployeeList WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = S_Shifts.EmployeeId
			LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OvertimeId
	WHERE	(S_Shifts.ShiftId = @ShiftId 
			OR (@ShiftId = 0 AND S_Shifts.Reconciled = 0 
			AND S_Shifts.ActualEndTime <= DATEADD(MINUTE,-@ReconProcessBuffer,GETDATE())))
			--AND S_Shifts.ActualEndTime = Convert(DateTime,'2020-01-01 00:00:00')))
	AND		(ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	ORDER BY S_Shifts.ActualStartTime
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prTA_ReconciliationProcessShiftUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prTA_ReconciliationProcessShiftUpd]
GO

/****** Object:  StoredProcedure [dbo].[prTA_ReconciliationProcessShiftUpd]    Script Date: 20/6/2018 10:07:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prTA_ReconciliationProcessShiftUpd]    
(
	@ShiftId				BigInt,
	@ShiftStartTime			DateTime,
	@ShiftEndTime			DateTime,
	@ActualStartTime		DateTime,
	@ActualEndTime			DateTime,
	@ReconTime				DateTime,
	@ReconStatusId			Int,
	@RPGId					Int,
	@ReconFailReasonId		Int,
	@ReconFailReasonDetail	nVarchar(1000),
	@Reconciled				Bit,
	@InTime					DateTime,
	@OutTime				DateTime,
	@InStatus				Int,
	@OutStatus				Int,
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	
	UPDATE	S_Shifts
	SET		--ShiftStartTime				=	@ShiftStartTime,
			--ShiftEndTime				=	@ShiftEndTime,
			ActualStartTime				=	@ActualStartTime,
			ActualEndTime				=	@ActualEndTime,
			ReconTime					=	@ReconTime,
			ReconStatusId				=	@ReconStatusId,
			RPGId						=	@RPGId,
			ReconFailureReasonId		=	@ReconFailReasonId,
			ReconFailureReasonDetail	=	@ReconFailReasonDetail,
			Reconciled					=	@Reconciled,
			InTime						=	@InTime,
			OutTime						=	@OutTime,
			InStatus					=	@InStatus,
			OutStatus					=	@OutStatus,
			UpdatedBy					=	@UpdatedBy,
			UpdatedDate					=	GETDATE()
	WHERE	ShiftId						=	@ShiftId

	SELECT 1
END
GO

/****** Object:  StoredProcedure [dbo].[prT_DeleteAttachment]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_DeleteAttachment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_DeleteAttachment]
GO

/****** Object:  StoredProcedure [dbo].[prT_DeleteAttachment]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_DeleteAttachment]    
(
	@AttachmentId	BigInt
)
AS
BEGIN

	DELETE FROM T_Attachments
	WHERE	AttachmentId = @AttachmentId

	SELECT 1;
END

GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_GetAttachmentsBySourceId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_GetAttachmentsBySourceId]
GO


CREATE PROCEDURE [dbo].[prT_GetAttachmentsBySourceId]    
(
	@AttachmentSourceId	BigInt
)
AS
BEGIN

	SELECT	AttachmentId,
			AttachmentSourceId, 
			EmployeeId, 
			AttachmentContents, 
			AttachmentName, 
			AttachmentSavedAs, 
			AttachmentType, 
			ModuleName, 
			CreatedBy, 
			CreatedDate
	FROM	T_Attachments
	WHERE	(AttachmentSourceId = @AttachmentSourceId OR @AttachmentSourceId = 0)
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_GetSystemTaskScheduleBySystemTaskId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_GetSystemTaskScheduleBySystemTaskId]
GO
/****** Object:  StoredProcedure [dbo].[prT_GetSystemTaskScheduleBySystemTaskId]    Script Date: 7/23/2018 5:42:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prT_GetSystemTaskScheduleBySystemTaskId]   
(
	@SystemTaskId	 BigInt 
	
)
AS
BEGIN	 
	SELECT  	T_SystemTaskSchedule.SystemTaskScheduleId,
				T_SystemTask.SystemTaskId,
				T_SystemTask.SystemTaskName,
				T_SystemTaskSchedule.TaskType,
				T_SystemTaskSchedule.TaskInterval,
				T_SystemTaskSchedule.TaskFrequency,
				T_SystemTaskSchedule.ScheduledMinute,
				T_SystemTaskSchedule.ScheduledHour,
				T_SystemTaskSchedule.ScheduledTime,
				T_SystemTaskSchedule.CronExpression,
				T_SystemTaskSchedule.StartDate,
				T_SystemTaskSchedule.EndDate,
				T_SystemTaskSchedule.CreatedBy,
				T_SystemTaskSchedule.CreatedDate,
				T_SystemTaskSchedule.UpdatedBy,
				T_SystemTaskSchedule.UpdatedDate
	FROM		T_SystemTaskSchedule WITH (NOLOCK) 
				INNER JOIN T_SystemTask WITH (NOLOCK) ON T_SystemTaskSchedule.SystemTaskId = T_SystemTask.SystemTaskId 		 
	WHERE		(T_SystemTask.SystemTaskId = @SystemTaskId OR @SystemTaskId = 0)
	 
	Order By T_SystemTask.SystemTaskName
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_GetSystemTasksTaskSchedules]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_GetSystemTasksTaskSchedules]
GO
/****** Object:  StoredProcedure [dbo].[prT_GetSystemTasksTaskSchedules]    Script Date: 7/23/2018 5:42:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prT_GetSystemTasksTaskSchedules]   
(
	@SystemTaskId	 BigInt 
)
AS
BEGIN	 
	SELECT  T_SystemTask.SystemTaskId,
			T_SystemTask.SystemTaskName	, 
			T_SystemTask.SystemTaskTypeId,
			IsNull(T_SystemTask.InterfaceId,0) InterfaceId,
			T_SystemTask.Description, 
			T_SystemTask.ActiveStatus ,				 
			T_SystemTask.CreatedBy ,
			T_SystemTask.CreatedDate ,
			T_SystemTask.UpdatedBy,
			T_SystemTask.UpdatedDate
	FROM	T_SystemTask WITH (NOLOCK)
	WHERE	(SystemTaskId = @SystemTaskId OR @SystemTaskId = 0) 
	Order By T_SystemTask.SystemTaskName

	SELECT  	T_SystemTaskSchedule.SystemTaskScheduleId,
				T_SystemTask.SystemTaskId,
				T_SystemTask.SystemTaskName,
				T_SystemTaskSchedule.TaskType,
				T_SystemTaskSchedule.TaskInterval,
				T_SystemTaskSchedule.TaskFrequency,
				T_SystemTaskSchedule.ScheduledMinute,
				T_SystemTaskSchedule.ScheduledHour,
				T_SystemTaskSchedule.ScheduledTime,
				T_SystemTaskSchedule.CronExpression,
				T_SystemTaskSchedule.StartDate,
				T_SystemTaskSchedule.EndDate,
				T_SystemTaskSchedule.CreatedBy,
				T_SystemTaskSchedule.CreatedDate,
				T_SystemTaskSchedule.UpdatedBy,
				T_SystemTaskSchedule.UpdatedDate
	FROM		T_SystemTaskSchedule WITH (NOLOCK) 
				INNER JOIN T_SystemTask WITH (NOLOCK) ON T_SystemTaskSchedule.SystemTaskId = T_SystemTask.SystemTaskId 		 
	WHERE		(T_SystemTask.SystemTaskId = @SystemTaskId OR @SystemTaskId = 0)	 
	Order By T_SystemTask.SystemTaskName
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_SystemTask]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_SystemTask]
GO
/****** Object:  StoredProcedure [dbo].[prT_SystemTask]    Script Date: 7/23/2018 5:42:16 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prT_SystemTask]   
(
	@SystemTaskId	 bigInt 
	
)
AS
BEGIN	 
	SELECT  	T_SystemTask.SystemTaskId,
			    T_SystemTask.SystemTaskName	, 
				T_SystemTask.SystemTaskTypeId,
				T_SystemTask. InterfaceId,
				T_SystemTask.Description, 
				T_SystemTask.ActiveStatus ,				 
				T_SystemTask.CreatedBy ,
				T_SystemTask.CreatedDate ,
				T_SystemTask.UpdatedBy,
				T_SystemTask.UpdatedDate
	    FROM	T_SystemTask WITH (NOLOCK)		 
	WHERE	(SystemTaskId = @SystemTaskId OR @SystemTaskId = 0)
	 
	Order By T_SystemTask.SystemTaskName
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prWF_GetNextLevelApprovers')
	DROP PROC prWF_GetNextLevelApprovers
GO

CREATE PROC prWF_GetNextLevelApprovers
	@ApprovalModuleId	Int,
	@ApplicantId		BigInt,
	@TransRouteId		BigInt,
	@RouteLevelNo		Int
AS
BEGIN
	
	SELECT	W_TRN_Approvals.TranId TransId,
			W_TRN_Approvals.TransRouteID,
			W_TRN_Approvals.ApprovalModuleID,
			W_TRN_Approvals.RequestTransID,
			W_TRN_Approvals.RouteID,
			W_TRN_Approvals.ApplicantId,
			W_TRN_Approvals.ApproverId,
			W_TRN_Approvals.RouteLevel,
			W_TRN_Approvals.ApprovalRequirement,
			W_TRN_Approvals.AppliedDate,
			W_TRN_Approvals.AppliedEmployeeId,
			W_TRN_Approvals.CreatedBy,
			W_TRN_Approvals.CreatedDate,
			C_Employee.EmployeeNumber ApproverEmployeeNumber,
			C_Employee.DisplayName ApproverEmployeeName,
			C_Employee.EmailAddress ApproverEmailId
	FROM	W_TRN_Approvals WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = W_TRN_Approvals.ApproverId
	where	ApprovalModuleID	=	@ApprovalModuleId
	AND		ApplicantId			=	@ApplicantId
	AND		TransRouteID		=	@TransRouteId
	AND		RouteLevel			=	@RouteLevelNo
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prWF_UpdateAllApproversActionByRouteLevelAndRouteId')
	DROP PROC prWF_UpdateAllApproversActionByRouteLevelAndRouteId
GO

CREATE PROC prWF_UpdateAllApproversActionByRouteLevelAndRouteId
	@TransRouteId		BigInt,
	@RouteLevelNo		Int,
	@ApprovalTransId	BigInt,
	@UpdatedBy			nVarchar(50)
AS
BEGIN
	UPDATE	W_TRN_Approval_RouteDetails
	SET		UserAction			=	0,
			ActionDate			=	NULL,
			Remarks				=	NULL,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	where	TransRouteID		=	@TransRouteId
	AND		RouteLevel			=	@RouteLevelNo
	AND		ApprovalTransID		!=	@ApprovalTransId
	AND		UserAction	IS NULL

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_AddTRN_ApprovalRoute')
	DROP PROC prW_AddTRN_ApprovalRoute
GO

----------------------------------------------------------------------------
-- Insert a single record into W_TRN_ApprovalRoute
----------------------------------------------------------------------------
CREATE PROC prW_AddTRN_ApprovalRoute
	@ApprovalModuleID int = NULL,
	@RouteID bigint = NULL,
	@RequestTransId	BigInt = NULL,
	@ApplicantId bigint = NULL,
	@AppliedEmployeeId bigint = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT W_TRN_ApprovalRoute(ApprovalModuleID, RouteID, RequestTransId, ApplicantId, AppliedEmployeeId, CreatedBy, CreatedDate)
VALUES (@ApprovalModuleID, @RouteID, @RequestTransId, @ApplicantId, @AppliedEmployeeId, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_AddTRN_Approvals')
	DROP PROC prW_AddTRN_Approvals
GO

----------------------------------------------------------------------------
-- Insert a single record into W_TRN_Approvals
----------------------------------------------------------------------------
CREATE PROC prW_AddTRN_Approvals
	@TransRouteID bigint = NULL,
	@ApprovalModuleID int = NULL,
	@RequestTransID bigint = NULL,
	@RouteID bigint = NULL,
	@ApplicantId bigint = NULL,
	@ApproverId bigint = NULL,
	@RouteLevel int = NULL,
	@ApprovalRequirement int = NULL,
	@AppliedDate datetime = NULL,
	@AppliedEmployeeId bigint = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT W_TRN_Approvals(TransRouteID, ApprovalModuleID, RequestTransID, RouteID, ApplicantId, ApproverId, RouteLevel, ApprovalRequirement, AppliedDate, AppliedEmployeeId, CreatedBy, CreatedDate)
VALUES (@TransRouteID, @ApprovalModuleID, @RequestTransID, @RouteID, @ApplicantId, @ApproverId, @RouteLevel, @ApprovalRequirement, @AppliedDate, @AppliedEmployeeId, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_AddTRN_Approval_RouteDetails')
	DROP PROC prW_AddTRN_Approval_RouteDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into W_TRN_Approval_RouteDetails
----------------------------------------------------------------------------
CREATE PROC prW_AddTRN_Approval_RouteDetails
	@TransRouteId	BigInt = NULL,
	@ApprovalTransId bigint = NULL,
	@ApplicantId bigint = NULL,
	@AppliedDate datetime = NULL,
	@ApproverId bigint = NULL,
	@RouteLevel int = NULL,
	@ApprovalRequirement int = NULL,
	@UserAction	Int = Null,
	@ActionDate	DateTime = NULL,
	@Remarks	nVarchar(1000) = NULL,
	@CreatedBy nvarchar(100) = NULL
AS

INSERT W_TRN_Approval_RouteDetails
(TransRouteId, ApprovalTransID, ApplicantId, AppliedDate, ApproverId, RouteLevel, ApprovalRequirement, 
 UserAction, ActionDate, CreatedBy, CreatedDate)
VALUES (@TransRouteId, @ApprovalTransId, @ApplicantId, @AppliedDate, @ApproverId, @RouteLevel, @ApprovalRequirement, 
	 	@UserAction, @ActionDate, @CreatedBy, GETDATE())

SELECT  CAST(@@Identity AS INTEGER) 

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_GetApprovalStatus')
	DROP PROC prW_GetApprovalStatus
GO

CREATE PROC prW_GetApprovalStatus
AS
BEGIN
	SELECT	ApprovalStatusId,
			ApprovalStatus,
			ApprovalStatusDesc
	FROM	W_ApprovalStatus WITH (NOLOCK)
	ORDER BY ApprovalStatus
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_GetEmployeesByWorkflowRouteId]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prW_GetEmployeesByWorkflowRouteId]
GO

CREATE PROCEDURE [dbo].[prW_GetEmployeesByWorkflowRouteId]    
(
	@WorkflowRouteId		BigInt
)
AS
BEGIN
	SELECT	DISTINCT C_EmployeeWorkflow.EmployeeId, C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName, 
			C_OrganizationNode.OUName, C_Employee.OUId
	FROM	C_EmployeeWorkflow WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_EmployeeWorkflow.EmployeeId		= C_Employee.EmployeeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId	= C_Employee.OUId
	WHERE	RouteId		=	@WorkflowRouteId
	ORDER BY C_Employee.EmployeeNumber
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_GetWorkflowRouteDetailsByEmployeeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_GetWorkflowRouteDetailsByEmployeeId]
GO
/****** Object:  StoredProcedure [dbo].[prW_GetWorkflowRouteDetailsByEmployeeId]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prW_GetWorkflowRouteDetailsByEmployeeId]    
(
	@EmployeeId		BigInt,
	@ModuleId		Int,
	@RouteId		BigInt
)
AS
BEGIN
	SELECT	RouteDetId,
			W_WorkflowRoute.RouteId,
			W_WorkflowRoute.RouteName,
			W_WorkflowRoute.RouteDesc RouteDescription,
			W_WorkflowRouteDetails.EmployeeId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			W_WorkflowRouteDetails.RouteLevel,
			C_EmployeeWorkflow.StartDate,
			C_EmployeeWorkflow.EndDate,
			C_EmployeeWorkflow.ModuleId,
			W_WorkflowRouteDetails.ApprovalRequirement
	FROM	W_WorkflowRouteDetails 
			INNER JOIN W_WorkflowRoute ON W_WorkflowRouteDetails.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_EmployeeWorkflow ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
			INNER JOIN C_Employee ON C_Employee.EmployeeId = C_EmployeeWorkflow.EmployeeId
	WHERE	C_EmployeeWorkflow.EmployeeId = @EmployeeId 
	AND		(C_EmployeeWorkflow.ModuleId = @ModuleId OR @ModuleId = 0)
	AND		(C_EmployeeWorkflow.RouteId = @RouteId OR @RouteId = 0)
END
go
 IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_ModulesSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_ModulesSel]
GO
/****** Object:  StoredProcedure [dbo].[prW_ModulesSel]    Script Date: 8/2/2018 10:11:20 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[prW_ModulesSel]   
(
	@ModuleId	 bigInt 
	
)
AS
BEGIN	 
	SELECT  	W_Modules.ModuleId,
			    W_Modules.ModuleName	, 
				W_Modules.ModuleDesc,
				W_Modules. TableName,
				W_Modules.TransIdName, 
				W_Modules.ViewURL ,				 
				W_Modules.ActiveStatus ,
				W_Modules.CreatedBy ,
				W_Modules.CreatedDate 
	    FROM	W_Modules 		 
	WHERE	(ModuleId = @ModuleId OR @ModuleId = 0)
	Order By W_Modules.ModuleName
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_WorkflowRouteByRouteId')
	DROP PROC prW_WorkflowRouteByRouteId
GO

CREATE PROCEDURE [dbo].[prW_WorkflowRouteByRouteId]    
(
	@RouteId	BigInt
)
AS
BEGIN
	SELECT	W_WorkflowRoute.RouteId,
			W_WorkflowRoute.OUId,
			W_WorkflowRoute.RouteName,
			W_WorkflowRoute.RouteDesc,
			W_WorkflowRoute.ActiveStatus,
			W_WorkflowRoute.CreatedBy,
			W_WorkflowRoute.CreatedDate,
			W_WorkflowRoute.UpdatedBy,
			W_WorkflowRoute.UpdatedDate
	FROM	W_WorkflowRoute 
	WHERE	W_WorkflowRoute.RouteId = @RouteId 	
	
END

GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteDel]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prW_WorkflowRouteDel]    
(
	@RouteId		BigInt,
	@UpdatedBy	nVarchar(50)
)
AS
BEGIN
	UPDATE	W_WorkflowRoute
	SET		ActiveStatus	=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GetDate()
	WHERE	RouteId			=	@RouteId

	SELECT 1
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteDetailsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteDetailsDel]
GO
/****** Object:  StoredProcedure [dbo].[prW_WorkflowRouteDetailsDel]    Script Date: 8/2/2018 10:15:03 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prW_WorkflowRouteDetailsDel]    
(	
	@RouteId	BigInt,
	@EmployeeId				BigInt,
	@RouteLevel  int
)
AS
BEGIN
	DELETE FROM W_WorkflowRouteDetails
	WHERE	RouteId = @RouteId
	AND		EmployeeId = @EmployeeId and RouteLevel=@RouteLevel
	SELECT 1
	 
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteDetailsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteDetailsIns]
GO
/****** Object:  StoredProcedure [dbo].[prW_WorkflowRouteDetailsIns]    Script Date: 8/2/2018 10:15:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prW_WorkflowRouteDetailsIns]    
(
	@RouteId				bigint,
	@EmployeeId				bigint,
	@RouteLevel				bigint,
	@ApprovalRequirement	int,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	W_WorkflowRouteDetails WITH (NOLOCK)
	WHERE	 RouteId= @RouteId and EmployeeId=@EmployeeId and RouteLevel=@RouteLevel

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO W_WorkflowRouteDetails
		(RouteId, EmployeeId, RouteLevel, ApprovalRequirement, CreatedBy, CreatedDate)
		VALUES(@RouteId, @EmployeeId, @RouteLevel, @ApprovalRequirement, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteDetailsSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteDetailsSel]
GO
/****** Object:  StoredProcedure [dbo].[prW_WorkflowRouteDetailsSel]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 
Create PROCEDURE [dbo].[prW_WorkflowRouteDetailsSel]    
(
	@RouteId	BigInt 
)
AS
BEGIN
	SELECT	W_WorkflowRouteDetails.RouteDetId,
			W_WorkflowRouteDetails.RouteId,
			W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.RouteLevel,
			W_WorkflowRouteDetails.ApprovalRequirement,
			W_WorkflowRouteDetails.CreatedBy,
			W_WorkflowRouteDetails.CreatedDate			 
	FROM	W_WorkflowRouteDetails WITH (NOLOCK)  
	WHERE	(W_WorkflowRouteDetails.RouteId = @RouteId ) order by RouteLevel asc
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteIns]
GO
 
Create PROCEDURE [dbo].[prW_WorkflowRouteIns]    
(
	@OUId				bigint,
	@RouteName			nvarchar(500),
	@RouteDesc			nvarchar(1000),
	@ActiveStatus		bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	W_WorkflowRoute WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RouteName))) = LTrim(RTrim(Upper(@RouteName)))
	AND		ActiveStatus = 1

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO W_WorkflowRoute
		(OUId, RouteName, RouteDesc, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@OUId, @RouteName, @RouteDesc, @ActiveStatus, @CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteLevelDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteLevelDel]
GO
/****** Object:  StoredProcedure [dbo].[prW_WorkflowRouteLevelDel]    Script Date: 8/2/2018 10:18:05 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[prW_WorkflowRouteLevelDel] 
(
	@RouteId		BigInt,
	@RouteLevel		BigInt
)
AS
BEGIN
     
	 Delete from W_WorkflowRouteDetails where RouteId = @RouteId and RouteLevel =@RouteLevel 
    
	UPDATE	W_WorkflowRouteDetails
	SET		RouteLevel	=	RouteLevel-1
	WHERE	RouteId		= @RouteId and RouteLevel > @RouteLevel

	SELECT 1
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prW_WorkflowRouteSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prW_WorkflowRouteSel]
GO
/****** Object:  StoredProcedure [dbo].[prW_WorkflowRouteSel]    Script Date: 8/2/2018 10:18:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prW_WorkflowRouteSel]    
(
	@RouteId	BigInt,
	@OUId		BigInt
)
AS
BEGIN
	SELECT	W_WorkflowRoute.RouteId,
			W_WorkflowRoute.OUId,
			W_WorkflowRoute.RouteName,
			W_WorkflowRoute.RouteDesc,
			W_WorkflowRoute.ActiveStatus,
			W_WorkflowRoute.CreatedBy,
			W_WorkflowRoute.CreatedDate,
			W_WorkflowRoute.UpdatedBy,
			W_WorkflowRoute.UpdatedDate
	FROM	W_WorkflowRoute WITH (NOLOCK) --INNER JOIN C_OrganizationNode with (NOLOCK) ON W_WorkflowRoute.OUId = C_OrganizationNode.OUId
	WHERE	(W_WorkflowRoute.RouteId = @RouteId OR @RouteId = 0)
	--AND		(C_OrganizationNode.OUId = @OUId)
	ORDER BY W_WorkflowRoute.RouteName
END

go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_WorkflowRouteUpd')
	DROP PROCEDURE prW_WorkflowRouteUpd
GO
 
Create PROCEDURE prW_WorkflowRouteUpd    
(
	@RouteId			BigInt,
	@OUId				bigint,
	@RouteName			nvarchar(500),
	@RouteDesc			nvarchar(1000),
	@ActiveStatus		bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	W_WorkflowRoute WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(RouteName))) = LTrim(RTrim(Upper(@RouteName)))
	AND		RouteId	!= @RouteId
	AND		ActiveStatus = 1

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	W_WorkflowRoute
		SET		RouteName		=	LTrim(RTrim(@RouteName)), 
				RouteDesc		=	LTrim(RTrim(@RouteDesc)), 
				ActiveStatus	=	@ActiveStatus, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	RouteId			=	@RouteId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_DeleteResourceSetByResourceSetId')
	DROP PROC pr_DeleteResourceSetByResourceSetId
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC pr_DeleteResourceSetByResourceSetId
	@ResourceSetId bigint
AS

DELETE	M_ResourceSet
WHERE 	ResourceSetId = @ResourceSetId

select 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_DeleteResourceSetDetailsByResourceSetDetId')
	DROP PROC pr_DeleteResourceSetDetailsByResourceSetDetId
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC pr_DeleteResourceSetDetailsByResourceSetDetId
	@ResourceSetDetId bigint
AS

DELETE	M_ResourceSetDetails
WHERE 	ResourceSetDetId = @ResourceSetDetId

SELECT 1

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_DeleteResourceSetDetailsByResourceSetId')
	DROP PROC pr_DeleteResourceSetDetailsByResourceSetId
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC pr_DeleteResourceSetDetailsByResourceSetId
	@ResourceSetId bigint
AS

DELETE	M_ResourceSetDetails
WHERE 	ResourceSetId = @ResourceSetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetResourceSetByOUId')
	DROP PROC pr_GetResourceSetByOUId
GO

----------------------------------------------------------------------------
-- Select a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC pr_GetResourceSetByOUId
	@OUId bigint
AS

SELECT	ResourceSetId,
	OUId,
	SetName,
	SetDesc,
	ActiveStatus,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_ResourceSet
WHERE 	OUId = @OUId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetResourceSetByResourceSetId')
	DROP PROC pr_GetResourceSetByResourceSetId
GO

----------------------------------------------------------------------------
-- Select a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC pr_GetResourceSetByResourceSetId
	@ResourceSetId bigint
AS

SELECT	ResourceSetId,
	OUId,
	SetName,
	SetDesc,
	ActiveStatus,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	M_ResourceSet
WHERE 	ResourceSetId = @ResourceSetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_UpdateResourceSetByResourceSetId')
	DROP PROC pr_UpdateResourceSetByResourceSetId
GO

----------------------------------------------------------------------------
-- Update a single record in M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC pr_UpdateResourceSetByResourceSetId
	@ResourceSetId bigint,
	@OUId bigint = NULL,
	@SetName nvarchar(1000) = NULL,
	@SetDesc nvarchar(2000) = NULL,
	@ActiveStatus bit = NULL,
	@UpdatedBy nvarchar(100) = NULL
AS

UPDATE	M_ResourceSet
SET	OUId = @OUId,
	SetName = @SetName,
	SetDesc = @SetDesc,
	ActiveStatus = @ActiveStatus,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	ResourceSetId = @ResourceSetId

select @ResourceSetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_UpdateResourceSetDetailsByResourceSetDetId')
	DROP PROC pr_UpdateResourceSetDetailsByResourceSetDetId
GO

----------------------------------------------------------------------------
-- Update a single record in M_ResourceSetDetails
----------------------------------------------------------------------------
CREATE PROC pr_UpdateResourceSetDetailsByResourceSetDetId
	@ResourceSetDetId bigint,
	@ResourceSetId bigint = NULL,
	@SkillId bigint = NULL,
	@Requirement int = NULL,
	@LocationId bigint = NULL,
	@UpdatedBy nvarchar(100) = NULL
	
AS

UPDATE	M_ResourceSetDetails
SET	ResourceSetId = @ResourceSetId,
	SkillId = @SkillId,
	Requirement = @Requirement,
	LocationId = @LocationId,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE()
WHERE 	ResourceSetDetId = @ResourceSetDetId

select @ResourceSetDetId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'psE_EquipMatrixEquipTypeByIdAndCranes')
	DROP PROC psE_EquipMatrixEquipTypeByIdAndCranes
GO

----------------------------------------------------------------------------
-- Select a single record from psE_EquipMatrixEquipTypeByIdAndCranes
----------------------------------------------------------------------------

 
create PROCEDURE [dbo].[psE_EquipMatrixEquipTypeByIdAndCranes]   
(	
	@EquipmentMatrixTemplateId	BigInt,
	@CraneCount					Int	
)
AS
BEGIN	 
	
	SELECT  EquipmentType.EquipmentTypeValue,
			EquipmentType.EquipmentTypeId,
			M_EquipmentType.EquipmentType,
			E_EquipmentMatrix.MatrixId,
			EquipmentType.MatrixScheduleId,
			MatrixSchedule.ScheduledValue
	FROM	E_EquipmentMatrix 
			INNER JOIN E_EqipmentMatrix_Schedule MatrixSchedule ON E_EquipmentMatrix.MatrixId = MatrixSchedule.MatrixId
			INNER JOIN E_EquipmentMatrix_EquipmentType EquipmentType ON E_EquipmentMatrix.MatrixId = EquipmentType.MatrixId 
			AND EquipmentType.MatrixScheduleId = MatrixSchedule.MatrixScheduleId
			INNER JOIN M_EquipmentType ON M_EquipmentType.EquipmentTypeId = EquipmentType.EquipmentTypeId
	WHERE	E_EquipmentMatrix.MatrixId = @EquipmentMatrixTemplateId 
	AND		(MatrixSchedule.ScheduledValue = @CraneCount OR @CraneCount = 0)

END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'SPC_GetUserSecurityRolesByUserSecurityRoleId')
	DROP PROC SPC_GetUserSecurityRolesByUserSecurityRoleId
GO

----------------------------------------------------------------------------
-- Select a single record from C_UserSecurityRoles
----------------------------------------------------------------------------
CREATE PROC SPC_GetUserSecurityRolesByUserSecurityRoleId
	@UserSecurityRoleId bigint
AS

SELECT	UserSecurityRoleId,
	UserId,
	SecurityRoleId,
	StartDate,
	EndDate,
	CreatedBy,
	CreatedDate,
	UpdatedBy,
	UpdatedDate
FROM	C_UserSecurityRoles
WHERE 	(SecurityRoleId = @UserSecurityRoleId OR @UserSecurityRoleId = 0)

GO
/****** Object:  StoredProcedure [dbo].[prT_AddAttachment]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_AddAttachment]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_AddAttachment]
GO

/****** Object:  StoredProcedure [dbo].[prT_AddAttachment]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_AddAttachment]    
(
	@AttachmentSourceId	BigInt,
	@EmployeeId			BigInt,
	@AttachmentContents	nVarchar(max),
	@AttachmentName		nVarchar(255),
	@AttachmentSavedAs	nVarchar(255),
	@AttachmentType		nVarchar(100),
	@ModuleName			nVarchar(50),
	@CreatedBy			nVarchar(50)
)
AS
BEGIN

	INSERT INTO T_Attachments
	(AttachmentSourceId, EmployeeId, AttachmentContents, AttachmentName, AttachmentSavedAs, AttachmentType, ModuleName, CreatedBy, CreatedDate)
	VALUES(@AttachmentSourceId, @EmployeeId, @AttachmentContents, @AttachmentName, @AttachmentSavedAs, @AttachmentType, 
		   @ModuleName, @CreatedBy, GETDATE()) 

	SELECT SCOPE_IDENTITY();
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'V_THPHours')
	DROP View V_THPHours

/****** Object:  View [dbo].[V_THPHours]    Script Date: 7/11/2019 8:54:17 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE VIEW [dbo].[V_THPHours]
AS
SELECT        dbo.C_Employee.EmployeeNumber, dbo.C_Employee.DisplayName, dbo.S_THPEmployeeDetails.ShiftDate, dbo.S_THPEmployeeDetails.ShiftCounter, dbo.S_THPEmployeeDetails.ActivityCounter, 
                         dbo.S_THPEmployeeDetails.LeaveCounter, dbo.S_THPEmployeeDetails.NormalHour, dbo.S_THPEmployeeDetails.OTHour
FROM            dbo.S_THPEmployeeDetails INNER JOIN
                         dbo.C_Employee ON dbo.C_Employee.EmployeeId = dbo.S_THPEmployeeDetails.EmployeeId

GO

Anon7 - 2022
AnonSec Team