Dre4m Shell
Server IP : 103.6.199.200  /  Your IP : 18.217.4.250
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/4.22.10.119/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME SHELL ]     

Current File : C:/Domains/jivisol1/build/4.22.10.119/MergeScripts.sql
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.AN4_Audit') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[AN4_Audit](
		[InterfaceAuditId] [bigint] IDENTITY(1,1) NOT NULL,
		[InterfaceId] [bigint] NOT NULL,
		[RequestedOUId] [bigint] NOT NULL,
		[RequestedParameters] [nvarchar](max) NOT NULL,
		[ResponseData] [nvarchar](max) NOT NULL,
		[RequestedDate] [datetime] NOT NULL,
		[RequestedBy] [nvarchar](100) NOT NULL,
		[ProcessStartedAt] [datetime] NOT NULL,
		[ProcessEndAt] [datetime] NOT NULL,
	 CONSTRAINT [PK_AN4_Audit] PRIMARY KEY CLUSTERED 
	(
		[InterfaceAuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

END
ELSE  Print 'AN4_Audit Table Exist'
GO

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


	CREATE TABLE [dbo].[A_Employee](
	[AuditId] [bigint] IDENTITY(1,1) NOT NULL,
	[ActionDate] [datetime] NOT NULL,
	[ProcessName] [nvarchar](255) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[OUName] [nvarchar](255) NULL,
	[RosterGroupName] [nvarchar](255) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[BadgeNumber] [nvarchar](50) NULL,
	[FirstName] [nvarchar](500) NULL,
	[MiddleName] [nvarchar](500) NULL,
	[LastName] [nvarchar](500) NULL,
	[DisplayName] [nvarchar](500) NULL,
	[EmploymentBasis] [nvarchar](255) NULL,
	[IsTerminated] [bit] NULL,
	[Position] [nvarchar](500) NULL,
	[Title] [nvarchar](50) NULL,
	[ScheduleRuleName] [nvarchar](255) NULL,
	[PayGroupName] [nvarchar](255) NULL,
	[OvertimeName] [nvarchar](255) NULL,
	[HourlyRate] [decimal](18, 4) NULL,
	[ContractedHours] [decimal](18, 2) NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	[RamadanPeriodType] [nvarchar](255) NULL,
	[PublicHolidayType] [nvarchar](255) NULL,
	[PrimaryRole] [nvarchar](255) NULL,
	[More] [nvarchar](max) NULL,
	[Roles] [nvarchar](max) NULL,
	[Skills] [nvarchar](max) NULL,
	[Disciplinary] [nvarchar](max) NULL,
	[Workflow] [nvarchar](max) NULL,
	[UserSecurityRoles] [nvarchar](max) NULL,
	[SharedOrganizationUnits] [nvarchar](max) NULL,
	[LeaveProfiles] [nvarchar](max) NULL,
	 CONSTRAINT [PK_A_Employee] PRIMARY KEY CLUSTERED 
	(
		[AuditId] 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_Employee Table Exist'
 
 GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.A_Operations') AND type in ('U'))
BEGIN	
	CREATE TABLE [dbo].[A_Operations](
		[AuditId] [bigint] IDENTITY(1,1) NOT NULL,
		[OUId] [bigint] NOT NULL,
		[ShiftId] [bigint] NULL,
		[StartTime] [datetime] NULL,
		[EndTime] [datetime] NULL,
		[Action] [int] NOT NULL,
		[ActionType] [int] NOT NULL,
		[ActionDetails] [nvarchar](max) NOT NULL,
		[Remarks] [nvarchar](1000) NULL,
		[ActionDate] [datetime] NOT NULL,
		[ActionBy] [nvarchar](100) NOT NULL,
	 CONSTRAINT [PK_A_Operations] PRIMARY KEY CLUSTERED 
	(
		[AuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
ELSE 
 Print 'A_Operations Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.A_RawClocking') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[A_RawClocking](
		[AuditId] [bigint] IDENTITY(1,1) NOT NULL,
		[ClockingId] [bigint] NOT NULL,
		[TypeId] [int] NOT NULL,
		[CardNo] [nvarchar](50) NULL,
		[TerminalName] [nvarchar](50) NULL,
		[SwipeDateTime] [datetime] NULL,
		[EmployeeNumber] [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,
		[Action] [nvarchar](100) NULL,
		[ActionDate] [datetime] NULL,
		[ActionBy] [nvarchar](100) NULL,
	 CONSTRAINT [PK_A_RawClocking] PRIMARY KEY CLUSTERED 
	(
		[AuditId] 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 'A_RawClocking Table Exist'
GO




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.A_ShiftCosts') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[A_ShiftCosts](
	[AuditId] [bigint] IDENTITY(1,1) NOT NULL,
	[ShiftCostId] [bigint] NOT NULL,
	[ShiftId] [bigint] NOT NULL,
	[PayCodeId] [bigint] NOT NULL,
	[PayCodeDescription] [nVarchar](255) NULL,
	[StartTime] [datetime] NOT NULL,
	[EndTime] [datetime] NOT NULL,
	[ActualHour] [float] NULL,
	[ShiftCost] [float] NULL,
	[AdjustmentCost] [float] NULL,
	[TotalCost] [float] NULL,
	[ApprovalStatus] [int] NULL,
	[ApprovedHours] [float] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	[Action] [nvarchar](100) NOT NULL,
	[ActionDate] [datetime] NOT NULL,
	[ActionBy] [nvarchar](50) NOT NULL,
	CONSTRAINT [PK_A_ShiftCosts] PRIMARY KEY CLUSTERED 
	(
		[AuditId] 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 'A_ShiftCosts Table Exist'
GO




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.A_UserPasswords') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[A_UserPasswords](
	[PasswordAuditId] [bigint] IDENTITY(1,1) NOT NULL,
	[UserId] [bigint] NOT NULL,
	[PasswordHash] [nvarchar](max) NOT NULL,
	[PasswordSalt] [nvarchar](200) NOT NULL,
	[CreatedBy] [nvarchar](100) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_A_UserPasswords] PRIMARY KEY CLUSTERED 
	(
		[PasswordAuditId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'A_UserPasswords 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_EmployeeMessages') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_EmployeeMessages](
	[EmployeeMessageId] [bigint] IDENTITY(1,1) NOT NULL,
	[MessageSecurityRoleId] [bigint] NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[MessageId] [bigint] NOT NULL,
	[EnableMessages] [bit] NOT NULL,
	[EnableEmails] [bit] NOT NULL,
	[EnablePushNotifications] [bit] NOT NULL,
	[IsMessagesDisabledByUser] [bit] NOT NULL,
	[MessagesDisabledDate] [datetime] NULL,
	[IsEmailDisabledByUser] [bit] NOT NULL,
	[EmailDisabledDate] [datetime] NULL,
	[IsPushNotificationsDisabledByUser] [bit] NOT NULL,
	[PushNotificationsDisabledDate] [datetime] NULL,
	[ActiveStatus] [bit] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeeMessages] PRIMARY KEY CLUSTERED 
	(
		[EmployeeMessageId] 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_EmployeeMessages Table Exist'
GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_EmployeeMiscellaneous') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_EmployeeMiscellaneous](
		[EmployeeId] [bigint] NOT NULL,
		[MiscValues] [text] NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL
	) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
END
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_EmployeeNotifications') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_EmployeeNotifications](
	[EmployeeNotificationId] [bigint] IDENTITY(1,1) NOT NULL,
	[MessageId] [bigint] NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[WebAppHeader] [nvarchar](max) NULL,
	[WebAppMessage] [nvarchar](max) NULL,
	[MobileAppHeader] [nvarchar](max) NULL,
	[MobileAppMessage] [nvarchar](max) NULL,
	[MessageStatus] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[ViewedDate] [datetime] NULL,
	[ReadDate] [datetime] NULL,
	[HideDate] [datetime] NULL,
	[DeletedDate] [datetime] NULL,
	[ClickedDate] [datetime] NULL,
	[LastStatusUpdatedDate] [datetime] NULL,
	[IsDeleted] [bit] NOT NULL,
	[DeletedBy] [nvarchar](50) NULL,
	[IsWebNotification] [bit] NOT NULL,
	[IsMobileNotification] [bit] NOT NULL,
	[IsActionRequired] [bit] NOT NULL,
	 CONSTRAINT [PK_C_EmployeeNotifications] PRIMARY KEY CLUSTERED 
	(
		[EmployeeNotificationId] 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_EmployeeNotifications 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_EmployeePanelClinics') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[C_EmployeePanelClinics](
	[EmployeePanelClinicId] [int] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NULL,
	[PanelClinicId] [int] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_EmployeePanelClinics] PRIMARY KEY CLUSTERED 
	(
		[EmployeePanelClinicId] 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_EmployeePanelClinics Table Exist'
 
GO
 IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_EmployeePerformanceRating') AND type in ('U'))
DROP TABLE J_EmployeePerformanceRating
GO

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

		CREATE TABLE [dbo].[C_EmployeePerformanceRating](
		[Id] [bigint] IDENTITY(1,1) NOT NULL,
		[Month] [bigint] NOT NULL,
		[Year] [bigint] NOT NULL,
		[EmployeeId] [BigInt] NOT NULL,
		[SelfRating] [nVarchar](10) NULL,		
		[AppraisalByUpperManager] [nVarchar](10) NULL,
		[ApprovedByGM] [nVarchar](10) NULL,
		[ReasonForRating] [nVarchar](max) NULL,
		[CreatedBy] nvarchar(100) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] nvarchar(100) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_EmployeePerformanceRating] PRIMARY KEY CLUSTERED
	(
		[Id] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE Print 'C_EmployeePerformanceRating Table Exist'
 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_InterfaceMaster') AND type in ('U'))
begin

	CREATE TABLE [dbo].[C_InterfaceMaster](
	[InterfaceMasterId] [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,
	[FileFormat] [text] NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_C_InterfaceMaster] PRIMARY KEY CLUSTERED 
	(
		[InterfaceMasterId] 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_InterfaceMaster 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_MenuFunctions') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_MenuFunctions](
	[MenuFunctionId] [bigint] NOT NULL,
	[MenuId] [bigint] NOT NULL,
	[FunctionName] [nvarchar](max) NOT NULL,
	[FunctionView] [nvarchar](max) NULL,
	[DisplayOrder] [Int] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_C_MenuFunctions] PRIMARY KEY CLUSTERED 
	(
		[MenuFunctionId] 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_MenuFunctions Already Exists...'

GO

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

	CREATE TABLE [dbo].[C_MiscellaneousColumns](
		[MiscellaneousColumnId] [bigint] IDENTITY(1,1) NOT NULL,
		[ModuleId] [int] NOT NULL,
		[LabelName] [nvarchar](500) NOT NULL,
		[DataType] [int] NOT NULL,
		[DefaultValue] [nvarchar](500) NULL,
		[IsMandatory] [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_MiscellaneousColumns] PRIMARY KEY CLUSTERED 
	(
		[MiscellaneousColumnId] 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 = Employee' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_MiscellaneousColumns', @level2type=N'COLUMN',@level2name=N'ModuleId'
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'1 = Boolean (CheckBox), 2 = String, 3 = Text Area, 4 = Number, 5 = Decimal, 6 = Date, 7 = Dropdown (Single Value), 8 = ListBox (Multi Select)' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'C_MiscellaneousColumns', @level2type=N'COLUMN',@level2name=N'DataType'
END
GO



IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.C_MiscellaneousColumnsValues') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_MiscellaneousColumnsValues](
		[ValueId] [bigint] IDENTITY(1,1) NOT NULL,
		[MiscellaneousColumnId] [bigint] NOT NULL,
		[ColumnValue] [text] 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_MiscellaneousColumnsValues] PRIMARY KEY CLUSTERED 
	(
		[ValueId] 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
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_SecurityRoleMenuFunctionPermissions') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_SecurityRoleMenuFunctionPermissions](
	[SecurityRoleMenuFunctionPermissionId] [bigint] IDENTITY(1,1) NOT NULL,
	[SecurityRoleId] [bigint] NOT NULL,
	[MenuFunctionId] [bigint] NOT NULL,
	[PermissionTypeId] [int] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_SecurityRoleMenuFunctionPermissions] PRIMARY KEY CLUSTERED 
	(
		[SecurityRoleMenuFunctionPermissionId] 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_SecurityRoleMenuFunctionPermissions Already Exists...'

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_UserDeviceTokens') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[C_UserDeviceTokens](
		[UserDeviceTokenId] [bigint] IDENTITY(1,1) NOT NULL,
		[UserId] [bigint] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[DeviceToken] [nvarchar](max) NOT NULL,
		[DeviceName] [nvarchar](100) NOT NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nchar](10) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_C_UserDeviceTokens] PRIMARY KEY CLUSTERED 
	(
		[UserDeviceTokenId] 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_UserDeviceTokens 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_Messages') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_Messages](
		[MessageId] [bigint] IDENTITY(1,1) NOT NULL,
		[MessageCode] [nvarchar](50) NOT NULL,
		[MessageName] [nvarchar](500) NULL,
		[MessageModuleId] [int] NOT NULL,
		[MessageModuleName] [nvarchar](500) NOT NULL,
		[LanguageId] [int] NULL,
		[EmailTemplateId] [bigint] NULL,
		[PushMessageHeader] [nvarchar](max) NULL,
		[PushMessageDetails] [nvarchar](max) NULL,
		[PushMessageIcon] [nvarchar](max) NULL,
		[NotificationHeader] [nvarchar](max) NULL,
		[NotificationDetails] [nvarchar](max) NULL,
		[NotificationIcon] [nvarchar](max) NULL,
		[NavigationUrlWeb] [nvarchar](1000) NULL,
		[NavigationUrlMobile] [nvarchar](1000) NULL,
		[ActiveStatus] [bit] NULL,
		[IsEmail] [bit] NULL,
		[IsMobileNotification] [bit] NULL,
		[IsWebNotification] [bit] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_Messages] PRIMARY KEY CLUSTERED 
	(
		[MessageId] 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_Messages Table Exist'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_MessageSecurityRole') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_MessageSecurityRole](
	[MessageSecurityRoleId] [bigint] IDENTITY(1,1) NOT NULL,
	[SecurityRoleId] [bigint] NOT NULL,
	[MessageId] [bigint] NOT NULL,
	[StartDate] [datetime] NOT NULL,
	[EndDate] [datetime] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_D_MessageSecurityRole] PRIMARY KEY CLUSTERED 
	(
		[MessageSecurityRoleId] 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_MessageSecurityRole Table Exist'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_MessageSkill') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[D_MessageSkill](
	[MessageSkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[MessageId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[ActiveStatus] [bit] NOT NULL,
	[CreatedBy] [nvarchar](100) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](100) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_MessageSkill] PRIMARY KEY CLUSTERED 
	(
		[MessageSkillId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]
END
ELSE 
 Print 'D_MessageSkill Table Exist'
GO

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

	CREATE TABLE [dbo].[D_PanelClinics](
	[PanelClinicId] [int] IDENTITY(1,1) NOT NULL,
	[PanelClinicName] [nvarchar](255) NULL,
	[Address] [nvarchar](1000) NULL,
	[State] [nvarchar](255) NULL,
	[ContactPerson] [nvarchar](1000) NULL,
	[ContactNumber] [nvarchar](50) NULL,
	[Remarks] [nvarchar](500) NULL,
	[ActiveStatus] [bit] NULL,
	CONSTRAINT [PK_D_PanelClinics] PRIMARY KEY CLUSTERED 
	(
		[PanelClinicId] 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_PanelClinics Table Exist'
 
GO
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.D_PasswordPolicy') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[D_PasswordPolicy](
	[PolicyId] [bigint] IDENTITY(1,1) NOT NULL,
	[PolicyDescription] [nvarchar](3000) NOT NULL,
	[PolicyValue] [int] NOT NULL,
	[ActiveStatus] [bit] NOT NULL,
	[CreatedBy] [nvarchar](100) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](100) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_D_PasswordPolicy] PRIMARY KEY CLUSTERED 
	(
		[PolicyId] 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_PasswordPolicy 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_PaycodeType') AND type in ('U'))
begin

	CREATE TABLE [dbo].[D_PaycodeType](
	[PaycodeTypeId] [BigInt] IDENTITY(1,1) NOT NULL,
	[PaycodeType] [nVarchar](50) NOT NULL,
	[Description] [nvarchar](200) NULL,
	[ActiveStatus] [Bit] NOT NULL,
	[PaycodeTypeValue] [Int]  NOT NULL,
	[SkillName] [nvarchar] (500) NULL,
	[CreatedBy] [nvarchar] (50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar] (50) NULL,
	[UpdatedDate] [datetime] NULL
	CONSTRAINT [PK_D_PaycodeType] PRIMARY KEY CLUSTERED 
	(
		[PaycodeTypeId] 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_PaycodeType 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]
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 EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS  WHERE TABLE_NAME = 'E_EqipmentMatrixGroupTemplates' AND COLUMN_NAME = 'TemplateGroupId' AND DATA_TYPE = 'int')
BEGIN
	
	DROP TABLE E_EqipmentMatrixGroupTemplates
END
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EqipmentMatrixGroupTemplates') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[E_EqipmentMatrixGroupTemplates](
		[TemplateGroupId] [bigint] IDENTITY(1,1) NOT NULL,
		[TemplateGroupName] [nvarchar](50) NULL,
		[OUId] [bigint] NULL,
		[TemplateGroupDesc] [text] NULL,
		[IsActive] [bit] NULL,
		[CreatedDate] [datetime] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](50) NULL,
	 CONSTRAINT [PK_D_EqipmentMatroxGroupTemplates] PRIMARY KEY CLUSTERED 
	(
		[TemplateGroupId] 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 'E_EqipmentMatrixGroupTemplates Table Exist' 
GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS  WHERE TABLE_NAME = 'E_EqipmentMatrixGroupTemplDet' AND COLUMN_NAME = 'TemplateGroupDetId' AND DATA_TYPE = 'int')
BEGIN
	DROP TABLE E_EqipmentMatrixGroupTemplDet
END 
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.E_EqipmentMatrixGroupTemplDet') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[E_EqipmentMatrixGroupTemplDet](
		[TemplateGroupDetId] [bigint] IDENTITY(1,1) NOT NULL,
		[TemplateGroupId] [int] NULL,
		[MatrixId] [int] NULL,
		[OUId] [bigint] NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_E_EqipmentMatrixGroupTemplDet] PRIMARY KEY CLUSTERED 
	(
		[TemplateGroupDetId] 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_EqipmentMatrixGroupTemplDet 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.IE_ClientMaster') AND type in ('U'))
begin

	CREATE TABLE [dbo].[IE_ClientMaster](
	[ClientKeyId] [bigint] IDENTITY(1,1) NOT NULL,
	[ClientId] [nvarchar](500) NULL,
	[ClientSecret] [nvarchar](500) NULL,
	[ClientName] [nvarchar](100) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_IE_ClientMaster] PRIMARY KEY CLUSTERED 
	(
		[ClientKeyId] 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 'IE_ClientMaster Table Exist'
 GO

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

	CREATE TABLE [dbo].[IE_EmployeeAbsents](
	[LeaveBalanceId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] not NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[AttendanceCode] [nvarchar](50) NULL,
	[ShiftDate] [datetime] NULL,
	[AsAtDate] [datetime] NULL,
	[ProcessDate] [datetime] NULL,
	[ProcessBy] [nvarchar](50) NULL,
	[RunningSeq] [bigint] not NULL,
	[InterfaceFlag] [bigint] not NULL,
	[ExportedDate] [datetime] NULL,
	[ExportedBy] [nvarchar](50) NULL,
	[Response] [nvarchar] (max) null,
	CONSTRAINT [PK_IE_EmployeeAbsents] PRIMARY KEY CLUSTERED 
	(
		[LeaveBalanceId] 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 'IE_EmployeeAbsents Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.IE_EmployeeOvertime') AND type in ('U'))
begin

	CREATE TABLE [dbo].[IE_EmployeeOvertime](
	[LeaveBalanceId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] not NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[Paycode] [nvarchar](50) NULL,
	[HRMSPaycode] [nvarchar](50) NULL,
	[ShiftDate] [datetime] NULL,
	[OTHours] [int] Not NULL,
	[AsAtDate] [datetime] NULL,
	[ProcessDate] [datetime] NULL,
	[ProcessBy] [nvarchar](50) NULL,
	[RunningSeq] [bigint] not NULL,
	[InterfaceFlag] [bigint] not NULL,
	[ExportedDate] [datetime] NULL,
	[ExportedBy] [nvarchar](50) NULL,
	[Response] [nvarchar] (max) null,
	CONSTRAINT [PK_IE_EmployeeOvertime] PRIMARY KEY CLUSTERED 
	(
		[LeaveBalanceId] 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 'IE_EmployeeOvertime Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.IE_EquipmentClocking') AND type in ('U'))
begin

	CREATE TABLE [dbo].[IE_EquipmentClocking](
	[ClockingId] [int] IDENTITY(1,1) NOT NULL,
	[EquipmentName] [nvarchar](50) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[ClockingDateTime] [datetime] NULL,
	[TypeId] [int] NULL,
	[PickupPoint] [nvarchar](50) NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_IE_EquipmentClocking] 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]


end
else 
 Print 'IE_EquipmentClocking Table Exist'
 GO

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

	CREATE TABLE [dbo].[IE_ExportFileConfig](
	[ConfigId] [bigint] IDENTITY(1,1) NOT NULL,
	[FileId] [Int] NOT NULL,
	[FileName] [nvarchar](500) NULL,
	[SortSequence] [Int] NOT NULL,
	[ColumnName] [nvarchar](100) NOT NULL,
	[DefaultValue] [nvarchar](100)  NULL,
	[DataType] [nvarchar](100) NOT NULL,
	[JiViColumn] [nvarchar] (100) NULL,
	[MappingData] [nvarchar] (max) NULL,
	[CreatedBy] [nvarchar] (50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar] (50) NULL,
	[UpdatedDate] [datetime] NULL
	CONSTRAINT [PK_IE_ExportFileConfig] PRIMARY KEY CLUSTERED 
	(
		[ConfigId] 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 'IE_ExportFileConfig Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[IE_LeaveBalance](
	[LeaveBalanceId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] not NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[LeaveCode] [nvarchar](50) NULL,
	[LeaveBalance] [decimal] (18,2) NULL,
	[AsAtDate] [datetime] NULL,
	[ProcessDate] [datetime] NULL,
	[ProcessBy] [nvarchar](50) NULL,
	[RunningSeq] [bigint] not NULL,
	[InterfaceFlag] [bigint] not NULL,
	[ExportedDate] [datetime] NULL,
	[ExportedBy] [nvarchar](50) NULL,
	[Response] [nvarchar] (max) null,
	CONSTRAINT [PK_IE_LeaveBalance] PRIMARY KEY CLUSTERED 
	(
		[LeaveBalanceId] 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 'IE_LeaveBalance Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[IE_LeaveTransactions](
	[LeaveBalanceId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] not NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[LeaveCode] [nvarchar](50) NULL,
	[LeaveDate] [datetime] NULL,
	[AppliedDate] [datetime] NULL,
	[ApprovedDate] [datetime] NULL,
	[ApprovedBy] [nvarchar](50) NULL,
	[ApprovalStatus] [nvarchar](100) NULL,
	[AsAtDate] [datetime] NULL,
	[ProcessDate] [datetime] NULL,
	[ProcessBy] [nvarchar](50) NULL,
	[RunningSeq] [bigint] not NULL,
	[InterfaceFlag] [bigint] not NULL,
	[ExportedDate] [datetime] NULL,
	[ExportedBy] [nvarchar](50) NULL,
	[Response] [nvarchar] (max) null,
	CONSTRAINT [PK_IE_LeaveTransactions] PRIMARY KEY CLUSTERED 
	(
		[LeaveBalanceId] 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 'IE_LeaveTransactions Table Exist'
 
 GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.IE_PoS_Interfaces') AND type in ('U'))
begin

	CREATE TABLE [dbo].[IE_PoS_Interfaces](
	[InterfaceRunId] [bigint] IDENTITY(1,1) NOT NULL,
	[ActionDate] [datetime] NULL,
	[ActionBy] [nvarchar](50) NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[InterfaceList] [nvarchar](max) NULL,
	[HistoryStartDate] [datetime] NULL,
	[HistoryEndDate] [datetime] NULL,
	[InterfaceStatus] [nvarchar](max) NULL,
	CONSTRAINT [PK_IE_PoS_Interfaces] PRIMARY KEY CLUSTERED 
	(
		[InterfaceRunId] 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 'IE_PoS_Interfaces 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] [BigInt] NULL,
	[AllocationNo] [BigInt] 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_EmployeeRBR') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[J_EmployeeRBR](
	[RBRId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[RBRRank] [nvarchar](2) NOT NULL,
	[Remarks] [nvarchar](500) NULL,
	[UpdatedBy] [nvarchar](50) NOT NULL,
	[UpdatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_J_EmployeeRBR] PRIMARY KEY CLUSTERED 
	(
		[RBRId] 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_EmployeeRBR Already Exists...'

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.J_EmployeeShiftRBR') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[J_EmployeeShiftRBR](
	[RBRHisId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[RBRRank] [nvarchar](2) NOT NULL,
	[ShiftId] [bigint] NOT NULL,
	[ShiftDate] [datetime] NOT NULL,
	[Remarks] [nvarchar](500) NULL,
	[UpdatedBy] [nvarchar](50) NOT NULL,
	[UpdatedDate] [datetime] NOT NULL,
	 CONSTRAINT [PK_J_EmployeeShiftRBR] PRIMARY KEY CLUSTERED 
	(
		[RBRHisId] 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_EmployeeShiftRBR Already Exists...'

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_SlashedCranes') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[J_SlashedCranes](
		[SlashedCraneId] [bigint] IDENTITY(1,1) NOT NULL,
		[ShiftDate] [datetime] NOT NULL,
		[ShiftBandId] [bigint] NOT NULL,
		[SkillId] [bigint] NOT NULL,
		[WorkloadId] [BigInt] NOT NULL,
		[ActivityStart] [datetime] NOT NULL,
		[ActivityEnd] [datetime] NOT NULL,
		[CraneScheduleId] [bigint] NOT NULL,
		[GroupNumber] [bigint] NOT NULL,
		[CraneId] [bigint] NOT NULL,
		[IsSlashed] [bit] NOT NULL,
		[CreatedBy] [nvarchar](100) NOT NULL,
		[CreatedDate] [datetime] NOT NULL,
		[UpdatedBy] [nvarchar](100) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_J_SlashedCranes] PRIMARY KEY CLUSTERED 
	(
		[SlashedCraneId] 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_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.J_WorkloadType') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[J_WorkloadType](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[WorkLoadType] [nVarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_J_WorkloadType] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_WorkloadType 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_EmployeeLieuDates') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[L_EmployeeLieuDates](
		[LieuDateId] [bigint] IDENTITY(1,1) NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[LieuDate] [datetime] NOT NULL,
		[Utilized] [bit] NULL,
		[CreatedBy] [nvarchar](200) NOT NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] [nvarchar](200) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_EmployeeLieuDates] PRIMARY KEY CLUSTERED 
	(
		[LieuDateId] 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_EmployeeLieuDates 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_LeaveBalanceDiscrepancy') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[L_LeaveBalanceDiscrepancy](
		[LeaveBalanceDiscrepancyId] [bigint] IDENTITY(1,1) NOT NULL,
		[EmployeeLeaveProfileId] [bigint] NOT NULL,
		[UsedDaysFromMYERP] [decimal](18, 2) NULL,
		[LMSBalanceDays] [decimal](18, 2) NULL,
		[MYERPBalanceDays] [decimal](18, 2) NULL,
		[CreatedBy] [nvarchar](100) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_L_LeaveBalanceDiscrepancy] PRIMARY KEY CLUSTERED 
	(
		[LeaveBalanceDiscrepancyId] 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
PRINT 'L_LeaveBalanceDiscrepancy Table 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_UCL') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[L_UCL](
	[UCLID] [bigint] IDENTITY(1,1) NOT NULL,
	[ExceptionCodeId] [bigint] NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[UCLDate] [DateTime] NOT NULL,
	[ReferenceNo] [nvarchar] (50) NULL,
	[Remarks] [nVarchar] (max) NULL,
	[AppliedBy]  [nvarchar] (50) NULL,
	[AppliedDate] [datetime] NULL,
	[IsAttachedDocument] bit,
	[UploadAttachmentBy]  [nvarchar] (50) NULL,
	[UploadAttachmentDate] [datetime] NULL,
	[UploadedAttachmentName]  [nvarchar] (max) NULL,
	[LeaveId] [bigint] NULL,
	[Notes]  [nvarchar] (max) NULL,
	[CreatedBy] [nvarchar] (50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar] (50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_L_UCL] PRIMARY KEY CLUSTERED 
	(
		[UCLID] 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_UCL 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_ConeManPlan') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_ConeManPlan](
	[ConeManPlanId] [bigint] IDENTITY(1,1) NOT NULL,
	[PlannedDate] [datetime] NULL,
	[ShiftbandId] [bigint] NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_ConeManPlan] PRIMARY KEY CLUSTERED 
	(
		[ConeManPlanId] 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_ConeManPlan Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[M_ConeManPlanDetail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ConeManPlanId] [bigint]  NOT NULL,
	[CraneScheduleId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_ConeManPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_ConeManPlanDetail Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[M_CraneConditionDetails](
	[CraneConditionId] [bigint] IDENTITY(1,1) NOT NULL,
	[CraneId] [bigint] not NULL,
	[ConditionType] [bigint] not NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[Remarks] [nvarchar](max) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_CraneConditionDetails] PRIMARY KEY CLUSTERED 
	(
		[CraneConditionId] 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_CraneConditionDetails 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_EmployeeEquipmentBoxMovement') AND type in ('U'))
begin

	CREATE TABLE [dbo].[M_EmployeeEquipmentBoxMovement](
	[BoxMovementId] [int] IDENTITY(1,1) NOT NULL,
	[EquipmentName] [nvarchar](50) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[EquipmentType] [nVarchar](100) NULL,
	[LoginTime] [datetime] NULL,
	[LogoutTime] [DateTime] NULL,
	[NoOfMoves] [int] NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_EmployeeEquipmentBoxMovement] 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
ELSE Print 'M_EmployeeEquipmentBoxMovement Table Exist'
 GO


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

	CREATE TABLE [dbo].[M_EmployeeEquipmentLogin](
	[ClockingId] [int] IDENTITY(1,1) NOT NULL,
	[EquipmentName] [nvarchar](50) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[ClockInDateTime] [datetime] NULL,
	[ClockOutDateTime] [DateTime] NULL,
	[TypeId] [int] NULL,
	[PickupPoint] [nvarchar](50) NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[LastLocation] [nVarchar](200) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_EmployeeEquipmentLogin] 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]
END
ELSE Print 'M_EmployeeEquipmentLogin 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_LasherPlan') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_LasherPlan](
	[LasherPlanId] [bigint] IDENTITY(1,1) NOT NULL,
	[PlannedDate] [datetime] NULL,
	[ShiftbandId] [bigint] NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_LasherPlan] PRIMARY KEY CLUSTERED 
	(
		[LasherPlanId] 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_LasherPlan Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[M_LasherPlanDetail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[LasherPlanId] [bigint]  NOT NULL,
	[LocationId] [bigint] NOT NULL,
	[Requirement] [bigint] NOT NULL,
	[VesselName] [nvarchar] (500) null,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_LasherPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_LasherPlanDetail 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_PMPlanning') AND type in ('U'))
begin

	CREATE TABLE [dbo].[M_PMPlanning] (
	[PMPlanningId] [bigint] IDENTITY(1,1) NOT NULL,
	[PlanningDate] [datetime] NULL,
	[ShiftBandId] [nvarchar](100) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_PMPlanning] PRIMARY KEY CLUSTERED 
	(
		[PMPlanningId] 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_PMPlanning Table Exists'
 
 GO

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

	CREATE TABLE [dbo].[M_PMPlanningLocation] (
	[PMPlanningLocationId] [bigint] IDENTITY(1,1) NOT NULL,
	[PMPlanningId] [bigint] NOT NULL, 
	[LocationId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[Requirement] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [FK_M_PMPlanningLocation_M_PMPlanning_PMPlanningId] FOREIGN KEY  (PMPlanningId) REFERENCES M_PMPlanning(PMPlanningId),
	CONSTRAINT [PK_M_PMPlanningLocation] PRIMARY KEY CLUSTERED 
	(
		[PMPlanningLocationId] 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_PMPlanningLocation Table Exists'
 
 GO


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

	CREATE TABLE [dbo].[M_PMPlanningSkills] (
	[PMPlanningSkillId] [bigint] IDENTITY(1,1) NOT NULL,
	[PMPlanningId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[Requirement] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [FK_M_PMPlanning_PMPlanningId] FOREIGN KEY  (PMPlanningId) REFERENCES M_PMPlanning(PMPlanningId),
	CONSTRAINT [PK_M_PMPlanningSkills] PRIMARY KEY CLUSTERED 
	(
		[PMPlanningSkillId] 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_PMPlanningSkills Table Exists'
 
 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_ResourceSetShiftBands') AND type in ('U'))
BEGIN

	CREATE TABLE [dbo].[M_ResourceSetShiftBands](
		[ResourceSetShiftBandsId] [bigint] IDENTITY(1,1) NOT NULL,
		[ResourceSetId] [bigint] NOT NULL,
		[ShiftBandId] [bigint] NOT NULL,
		[ActiveStatus] [bit] NOT NULL,
		[CreatedBy] [nvarchar](50) NOT NULL,
		[CreatedDate] [date] NOT NULL,
		[UpdatedBy] [nvarchar](50) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_ResourceSetShiftBands] PRIMARY KEY CLUSTERED 
	(
		[ResourceSetShiftBandsId] 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_ResourceSetShiftBands Table Exist'
GO



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

	CREATE TABLE [dbo].[M_RTGPlan](
	[RTGPlanId] [bigint] NOT NULL Identity(1,1),
	[PlanDate] [datetime] NOT NULL,
	[ShiftBandId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_RTGPlan] PRIMARY KEY CLUSTERED 
	(
		[RTGPlanId] 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_RTGPlan Table Exist'
 
GO




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

	CREATE TABLE [dbo].[M_RTGPlanDetail](
	[RTGPlanDetailId] [bigint] NOT NULL Identity(1,1),
	[RTGPlanId] [bigint] NOT NULL,	
	[EquipmentId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_RTGPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[RTGPlanDetailId] 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_RTGPlanDetail Table Exist'
 
GO




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

	CREATE TABLE [dbo].[M_ScreenConfiguration](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[ConfigType] [bigInt] NULL,
	[ConfigScreen] [nvarchar](500) NULL,
	[ConfigName] [nvarchar](10) NULL,
	[ConfigValue] [nvarchar](1000) NULL,
	[ConfigAdditionalValue] [nvarchar](1000) NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_ScreenConfiguration] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_ScreenConfiguration Table Exist'
 
 GO


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

		CREATE TABLE [dbo].[M_ShiftAssemble_TemplateGroup](
		[ShiftAssembleId] [bigint] IDENTITY(1,1) NOT NULL,
		[PlanDate] [datetime] NULL,
		[ShiftBandId] [bigint] NULL,		
		[ResourceSetId] [bigint] NULL,
		[AllocationTemplateId] [bigint] NULL,
		[ReliefRuleId] [bigint] NULL,
		[SignOffStatus] [bit] NULL,
		[CreatedBy] nvarchar(100) NULL,
		[CreatedDate] [datetime] NULL,
		[UpdatedBy] nvarchar(100) NULL,
		[UpdatedDate] [datetime] NULL,
	 CONSTRAINT [PK_M_ShiftAssemble_TemplateGroup] PRIMARY KEY CLUSTERED
	(
		[ShiftAssembleId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE Print 'M_ShiftAssemble_TemplateGroup Table Exist'
 GO


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

	CREATE Table [dbo].[M_ShiftAssemble_TemplateGroupDetail](
	[ShiftAssembleDetId] [bigint] Identity(1,1) NOT NULL,	
	[ShiftAssembleId] [bigint] NOT NULL,	
	[TypeId] [BigInt] NULL,
	[EquipmentTypeId] [BigInt] NULL,
	[SkillId] [BigInt] NULL,
	[Requirement] [int] NULL,
	[LocationId] [BigInt] NULL,
	[CreatedBy] nvarchar(100) NULL,	
	[CreatedDate] [DateTime] NULL,
	[UpdatedBy] nvarchar(100) NULL,
	[UpdatedDate] [DateTime] NULL,
	 CONSTRAINT [PK_M_ShiftAssemble_TemplateGroupDetail] PRIMARY KEY CLUSTERED
	(
		[ShiftAssembleDetId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]


END
ELSE Print 'M_ShiftAssemble_TemplateGroupDetail 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_StackersPlan') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_StackersPlan](
	[StackersPlanId] [bigint] NOT NULL Identity(1,1),
	[PlanDate] [datetime] NOT NULL,
	[ShiftBandId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_StackersPlan] PRIMARY KEY CLUSTERED 
	(
		[StackersPlanId] 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_StackersPlan Table Exist'
 
GO

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

	CREATE TABLE [dbo].[M_StackersPlanDetail](
	[StackersPlanDetailId] [bigint] NOT NULL Identity(1,1),
	[StackersPlanId] [bigint] NOT NULL,	
	[EquipmentId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_StackersPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[StackersPlanDetailId] 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_StackersPlanDetail Table Exist'
 
GO




IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_TabReaderPlan') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_TabReaderPlan](
	[TabReaderPlanId] [bigint] IDENTITY(1,1) NOT NULL,
	[PlannedDate] [datetime] NULL,
	[ShiftbandId] [bigint] NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_TabReaderPlan] PRIMARY KEY CLUSTERED 
	(
		[TabReaderPlanId] 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_TabReaderPlan Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[M_TabReaderPlanDetail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[TabReaderPlanId] [bigint]  NOT NULL,
	[VesselScheduleId] [bigint] NOT NULL,
	[Requirement] [bigint] NOT NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_TabReaderPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_TabReaderPlanDetail Table Exist'
 
 GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_TopManPlan') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[M_TopManPlan](
	[TopManPlanId] [bigint] IDENTITY(1,1) NOT NULL,
	[PlannedDate] [datetime] NULL,
	[ShiftbandId] [bigint] NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_TopManPlan] PRIMARY KEY CLUSTERED 
	(
		[TopManPlanId] 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_TopManPlan Table Exist'
 
 GO


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

	CREATE TABLE [dbo].[M_TopManPlanDetail](
	[Id] [bigint] IDENTITY(1,1) NOT NULL,
	[TopManPlanId] [bigint]  NOT NULL,
	[CraneScheduleId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar] (50) null,
	[CreatedDate] [datetime] null
	CONSTRAINT [PK_M_TopManPlanDetail] PRIMARY KEY CLUSTERED 
	(
		[Id] 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_TopManPlanDetail Table Exist'
 
 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_VesselMiscellaneousColumns') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_VesselMiscellaneousColumns](
	[VesselScheduleId] [bigint] NOT NULL,
	[MiscValues] [text] NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_VesselMiscellaneousColumns] 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]

END
ELSE 
 Print 'M_VesselMiscellaneousColumns 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 NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_VesselScheduleResourceSet') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[M_VesselScheduleResourceSet](
	[VesselScheduleResourceSetId] [bigint] NOT NULL Identity(1,1),
	[VesselScheduleId] [bigint] NOT NULL,
	[ResourceSetId] [bigint] NOT NULL,
	[TypeId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[EquipmentTypeId] [bigint] NOT NULL,
	[Requirement] [int] NOT NULL,
	[LocationId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,
	[CreatedDate] [datetime] NOT NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
	CONSTRAINT [PK_M_VesselScheduleResourceSet] PRIMARY KEY CLUSTERED 
	(
		[VesselScheduleResourceSetId] 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_VesselScheduleResourceSet 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_THPEmployeeCraneConditionCounter') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPEmployeeCraneConditionCounter](
		[TransId] [bigint] IDENTITY(1,1) NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[CraneConditionTypeId] [bigint] NOT NULL,
		[THPPeriodId] [bigint] NOT NULL,
		[StartDate] [datetime] NOT NULL,
		[EndDate] [datetime] NOT NULL,
		[Occurrence] [int] NOT NULL,
	 CONSTRAINT [PK_S_THPEmployeeCraneConditionCounter] PRIMARY KEY CLUSTERED 
	(
		[TransId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'S_THPEmployeeCraneConditionCounter 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_THPEmployeeEquipmentDetails') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPEmployeeEquipmentDetails](
		[TranId] [bigint] IDENTITY(1,1) NOT NULL,
		[THPPeriodId] [bigint] NOT NULL,
		[EmployeeId] [bigint] NOT NULL,
		[ShiftId] [BigInt] NOT NULL,
		[ShiftDate] [datetime] NOT NULL,
		[EquipmentId] [bigint] NOT NULL,
		[ActivityCounter] [numeric](18, 0) NOT NULL,
		[THPProcessDate] [datetime] NOT NULL,
		[THPNotes] [nvarchar](500) NULL,
		[CreatedBy] [nvarchar](50) NULL,
		[CreatedDate] [datetime] NULL,
	 CONSTRAINT [PK_S_THPEmployeeEquipmentDetails] PRIMARY KEY CLUSTERED 
	(
		[TranId] ASC
	)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
	) ON [PRIMARY]

END
ELSE 
 Print 'S_THPEmployeeEquipmentDetails 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_THPEmployeeSkillDetails') AND type in ('U'))
BEGIN	

	CREATE TABLE [dbo].[S_THPEmployeeSkillDetails](
	[TranId] [bigint] IDENTITY(1,1) NOT NULL,
	[THPPeriodId] [bigint] NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[ShiftDate] [datetime] NOT NULL,
	[ShiftId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[ActivityCounter] [numeric](18, 0) NOT NULL,
	[THPProcessDate] [datetime] NOT NULL,
	[THPNotes] [nvarchar](500) NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_S_THPEmployeeSkillDetails] 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 'S_THPEmployeeSkillDetails 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.TT_EmployeeInitialLiveRank') AND type in ('U'))
BEGIN
	CREATE TABLE [dbo].[TT_EmployeeInitialLiveRank](
	[LiveRankId] [bigint] IDENTITY(1,1) NOT NULL,
	[EmployeeId] [bigint] NOT NULL,
	[RBRRank] [nvarchar](2) NOT NULL,
	[ActionDate] datetime NOT NULL,
	[ActionRemarks] [nvarchar](500) NULL,
	 CONSTRAINT [PK_TT_EmployeeInitialLiveRank] PRIMARY KEY CLUSTERED 
	( [LiveRankId] 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 'TT_EmployeeInitialLiveRank Already Exists...'

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_BackendProcessList') AND type in ('U'))
begin
	
	CREATE TABLE [dbo].[T_BackendProcessList](
	[BackendProcessId] [int] IDENTITY(1,1) NOT NULL,	
	[Type] [int] NULL,
	[Name] [nvarchar](500) NULL,
	[ModuleName] [nvarchar](100) NULL,
	[Method] [nvarchar](100) NULL,
	[Remarks] [nvarchar](1000) NULL,
	[FileFormat] [nvarchar](1000) NULL,
	[ActiveStatus] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	CONSTRAINT [PK_T_BackendProcessList] PRIMARY KEY CLUSTERED 
	(
		[BackendProcessId] 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 'T_BackendProcessList 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 Column [Miscellaneous] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_Employee') AND Name = N'Miscellaneous')
BEGIN
	ALTER TABLE [dbo].[A_Employee] ADD [Miscellaneous] nVarchar(1000)
	Print 'Column [Miscellaneous] Added Successfully...'
END	
GO


-- Add Column [Remarks] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_ShiftCosts') AND Name = N'Remarks')
BEGIN
	ALTER TABLE [dbo].[A_ShiftCosts] ADD [Remarks] nVarchar(1000)
	Print 'Column [Remarks] Added Successfully...'
END	
GO

-- Alter Column [CreatedBy] Column 
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_ShiftCosts') AND Name = N'CreatedBy' AND max_length = 100)
BEGIN
	ALTER TABLE [dbo].[A_ShiftCosts] Alter Column [CreatedBy] nVarchar(1000)
	Print 'Column [CreatedBy] Added Successfully...'
END	
GO

-- Alter Column [ActionBy] Column 
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_ShiftCosts') AND Name = N'ActionBy' AND max_length = 100)
BEGIN
	ALTER TABLE [dbo].[A_ShiftCosts] Alter Column [ActionBy] nVarchar(1000)
	Print 'Column [ActionBy] Added Successfully...'
END	
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

-- Add [RBRRank] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.A_Shifts') AND Name = N'RBRRank')
BEGIN
	ALTER TABLE [dbo].[A_Shifts] ADD [RBRRank] nVarchar(2) NULL 
END
ELSE
	Print 'Column [RBRRank] 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'

IF EXISTS (SELECT * FROM sys.columns  WHERE Name = N'Title' AND Object_ID = Object_ID(N'C_Employee'))
BEGIN
	ALTER TABLE [dbo].[C_Employee] 
	ALTER COLUMN Title nVarchar(500) NULL
END


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.columns  WHERE Name = N'ExcludeAccrualProcess' AND Object_ID = Object_ID(N'C_EmployeeDiciplinary'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeDiciplinary] 
	ADD [ExcludeAccrualProcess] Bit NULL

	Print 'Column [ExcludeAccrualProcess] Added To Table [C_EmployeeDiciplinary]'

END
GO

-- <JiraItem cref="E10-314">[Suspended Employees] Exclude Accrual Process</JiraItem>
-- Update Value as False if added first time
IF EXISTS (SELECT * FROM sys.columns  WHERE Name = N'ExcludeAccrualProcess' AND Object_ID = Object_ID(N'C_EmployeeDiciplinary'))
BEGIN
	UPDATE C_EmployeeDiciplinary SET ExcludeAccrualProcess = 0 Where ExcludeAccrualProcess IS NULL
END
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'
GO

IF NOT EXISTS (SELECT * FROM sys.columns  WHERE Name = N'TemplateId' AND Object_ID = Object_ID(N'C_EmployeeMovement'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeMovement] 
	ADD [TemplateId] BigInt NULL

	Print 'Column [TemplateId] Added To Table [C_EmployeeMovement]'
END
GO


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
-- ADD [EffectiveFrom] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.C_EmployeePanelClinics') AND Name = N'EffectiveFrom')
BEGIN
	ALTER TABLE [dbo].[C_EmployeePanelClinics] ADD [EffectiveFrom] DateTime 
END
ELSE 
 Print 'C_EmployeePanelClinics.EffectiveFrom Column Exist' 
GO

-- ADD [EffectiveTo] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.C_EmployeePanelClinics') AND Name = N'EffectiveTo')
BEGIN
	ALTER TABLE [dbo].[C_EmployeePanelClinics] ADD [EffectiveTo] DateTime
END
ELSE 
 Print 'C_EmployeePanelClinics.EffectiveTo Column Exist' 
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
 
 
 

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

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

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

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

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

-- Add [TemplateId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.C_Interfaces') AND Name = N'TemplateId')
BEGIN
	ALTER TABLE [dbo].C_interfaces ADD [TemplateId] [bigint] NULL 
END
ELSE
	Print 'Column [TemplateId] Already Exists'
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

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

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

	ALTER TABLE [dbo].[C_MiscellaneousColumnsValues] CHECK CONSTRAINT [FK_C_MiscellaneousColumnsValues_C_MiscellaneousColumns]
END
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.columns  WHERE Name = N'AvailableOptions' AND Object_ID = Object_ID(N'D_EmailTemplate'))
BEGIN
	ALTER TABLE [dbo].[D_EmailTemplate] ADD AvailableOptions nVarchar(max) NULL
END
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
 -- Add Weightage
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_MasterCodes') AND Name = N'Weightage')
BEGIN
	ALTER TABLE [dbo].[D_MasterCodes] ADD [Weightage] [int] DEFAULT(0)
END
ELSE
	Print 'Column [Weightage] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.DF_D_MessageSkill_ActiveStatus') AND type in ('D'))
BEGIN	
	ALTER TABLE [dbo].[D_MessageSkill] ADD  CONSTRAINT [DF_D_MessageSkill_ActiveStatus]  DEFAULT ((1)) FOR [ActiveStatus]
END
ELSE 
 Print 'D_ReliefRule Default Values Exist'
 
GO

-- ALTER [PanelClinicName] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'PanelClinicName' And system_type_id = 231)
BEGIN
	ALTER TABLE [dbo].[D_PanelClinics] ALTER COLUMN [PanelClinicName] nVarchar(255) NOT NULL 
END
GO

-- ALTER [Address] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'Address' And system_type_id = 231)
BEGIN
	ALTER TABLE [dbo].[D_PanelClinics] ALTER COLUMN [Address] nVarchar(2000) NULL 
END
GO

--Add PostCode Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'PostCode')
BEGIN	
	ALTER TABLE [dbo].[D_PanelClinics] ADD  [PostCode] nVarchar(20) NULL
END
ELSE 
 Print 'D_PanelClinics.PostCode Column Exist'
 
GO

-- ALTER [State] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'State' And system_type_id = 231)
BEGIN
	ALTER TABLE [dbo].[D_PanelClinics] ALTER COLUMN [State] nVarchar(1000) NULL 
END
GO

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

-- ALTER [Remarks] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'ContactPerson' And system_type_id = 231)
BEGIN
	ALTER TABLE [dbo].[D_PanelClinics] ALTER COLUMN [ContactPerson] nVarchar(1000) NULL 
END
GO

-- ALTER [Remarks] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'Remarks' And system_type_id = 231)
BEGIN
	ALTER TABLE [dbo].[D_PanelClinics] ALTER COLUMN [Remarks] nVarchar(1000) NULL 
END
GO

--Add ClinicCode Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'PanelClinicCode')
BEGIN	
	ALTER TABLE [dbo].[D_PanelClinics] ADD  [PanelClinicCode] nVarchar(50) NOT NULL DEFAULT ''
END
ELSE 
 Print 'D_PanelClinics.ClinicCode Column Exist' 
GO

--Delete Effective From Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'EffectiveDate')
BEGIN	
	ALTER TABLE [dbo].[D_PanelClinics] DROP COLUMN [EffectiveDate] 
END
GO

--Delete Effective From Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'EffectiveFrom')
BEGIN	
	ALTER TABLE [dbo].[D_PanelClinics] DROP COLUMN [EffectiveFrom] 
END
GO

--Delete Effective To Column
IF  EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PanelClinics') AND Name = N'EffectiveTo')
BEGIN	
	ALTER TABLE [dbo].[D_PanelClinics] DROP COLUMN  [EffectiveTo]
END 
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


 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);
	
	DECLARE @sql NVARCHAR(2048) = 'UPDATE D_PayCodes SET IsEditable = 1';
	EXEC sys.sp_executesql @query = @sql;
	
END
ELSE
	Print 'Column [IsEditable] Already Exists'
GO
-- Add Column [DefaultValue] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_PaycodeType') AND Name = N'DefaultValue')
BEGIN
	ALTER TABLE [dbo].[D_PaycodeType] ADD [DefaultValue] nVarchar(500)
	Print 'Column [DefaultValue] Added Successfully...'
END	
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_1') OR 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_IsShiftProcess1') OR 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 EXISTS (SELECT * FROM sys.columns  WHERE Name = N'OperatingHour' AND Object_ID = Object_ID(N'D_ReliefRuleSkill') ANd user_type_id = 56)
BEGIN
	ALTER TABLE [dbo].[D_ReliefRuleSKill] ALTER COLUMN OperatingHour decimal(18,2) NOT NULL
END
GO

IF NOT EXISTS (SELECT * FROM sys.columns  WHERE Name = N'MinRestHours' AND Object_ID = Object_ID(N'D_ReliefRuleSkill'))
BEGIN
	ALTER TABLE [dbo].[D_ReliefRuleSKill] ADD MinRestHours decimal(18,2) Default(1.5)

	DECLARE @sql NVARCHAR(2048) = 'UPDATE D_ReliefRuleSKill SET MinRestHours = 2';
	EXEC sys.sp_executesql @query = @sql;
END
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.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_ShiftBand') AND Name = N'ShiftCounter')
BEGIN
	ALTER TABLE [dbo].[D_ShiftBand] ADD [ShiftCounter] [decimal](18, 5) NULL
END
ELSE
	Print 'Column [ShiftCounter] Already Exists'
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
-- Add Fixed Ranking
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.D_Skill') AND Name = N'FixedRanking')
BEGIN
	ALTER TABLE [dbo].[D_Skill] ADD [FixedRanking] nVarchar(100)
END
ELSE
	Print 'Column [FixedRanking] Already Exists'
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_EqipmentMatrixGroupTemplates_C_OrganizationNode') AND type in ('F'))
BEGIN

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


	ALTER TABLE [dbo].[E_EqipmentMatrixGroupTemplates] CHECK CONSTRAINT [FK_E_EqipmentMatrixGroupTemplates_C_OrganizationNode]


END
ELSE 
 Print 'FK_E_EqipmentMatrixGroupTemplates_C_OrganizationNode Table Exist'
 
GO




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

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


	ALTER TABLE [dbo].[E_EqipmentMatrixGroupTemplDet] CHECK CONSTRAINT [FK_E_EqipmentMatrixGroupTemplDet_C_OrganizationNode]

END
ELSE 
 Print 'FK_E_EqipmentMatrixGroupTemplDet_C_OrganizationNode 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.columns WHERE Object_ID = OBJECT_ID(N'dbo.E_EquipmentMatrix ') AND Name = N'EquipmentTypeId')
BEGIN
	ALTER TABLE [dbo].[E_EquipmentMatrix] ADD [EquipmentTypeId] [int] DEFAULT(0)
END
ELSE
	Print 'Column [EquipmentTypeId] Already Exists'
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
 
 IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_C_EmployeeMiscellaneous_C_Employee') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[C_EmployeeMiscellaneous]  WITH CHECK ADD  CONSTRAINT [FK_C_EmployeeMiscellaneous_C_Employee] FOREIGN KEY([EmployeeId])
	REFERENCES [dbo].[C_Employee] ([EmployeeId])
	
	ALTER TABLE [dbo].[C_EmployeeMiscellaneous] CHECK CONSTRAINT [FK_C_EmployeeMiscellaneous_C_Employee]
END
GO
-- Add Column [ClockOutDateTime] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.IE_EquipmentClocking') AND Name = N'ClockOutDateTime')
BEGIN
	ALTER TABLE [dbo].[IE_EquipmentClocking] ADD [ClockOutDateTime] datetime
	Print 'Column [ClockOutDateTime] Added Successfully...'
END	
GO




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

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

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

-- Add [IE_EmployeeAbsents].[TransRefId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.IE_EmployeeAbsents') AND Name = N'TransRefId')
BEGIN
	ALTER TABLE [dbo].IE_EmployeeAbsents ADD [TransRefId] [nVarchar](500) NOT NULL DEFAULT NEWID()
END
ELSE
	Print 'Column [IE_EmployeeAbsents].[TransRefId] Already Exists'
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

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

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

--Alter Allocation Number From Int To BigInt
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_Activity') AND Name = N'AllocationNo' And system_type_id = 56)
BEGIN
	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_StartTime_CreatedBy' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_StartTime_CreatedBy ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_MaxGroup_Allocation_No' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_MaxGroup_Allocation_No ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_OUShiftBand' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_OUShiftBand ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_StartTime_CreatedBy' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_StartTime_CreatedBy ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_MaxGroup_Allocation_No' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_MaxGroup_Allocation_No ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_SkillShiftBandAllocationNo' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX NCIDX_J_Activity_SkillShiftBandAllocationNo ON  [dbo].[J_Activity] 

	IF EXISTS(SELECT * FROM sys.indexes WHERE name = 'CIDX_J_Activity_Operations' AND object_id = OBJECT_ID('J_Activity'))
		DROP INDEX CIDX_J_Activity_Operations ON  [dbo].[J_Activity]

	ALTER TABLE [dbo].[J_Activity] ALTER COLUMN [AllocationNo] BigInt NULL 
END
ELSE
	Print 'Column [J_Activity.AllocationNo] Already Exists'
GO

--Alter Group Number From Int To BigInt
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_Activity') AND Name = N'GroupNo' And system_type_id = 56)
BEGIN
	ALTER TABLE [dbo].[J_Activity] ALTER COLUMN [GroupNo] BigInt NULL 
END
ELSE
	Print 'Column [J_Activity.AllocationNo] Already Exists'
GO

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

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



-- Add [FactorType] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_AllocationFactor') AND Name = N'FactorType')
BEGIN
	ALTER TABLE [dbo].[J_AllocationFactor] ADD [FactorType] [Int] 
	CONSTRAINT DF_J_AllocationFactor_FactorType DEFAULT 0 WITH VALUES
	EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'0 - Employee Sorting, 2 - Activity Sorting 3 - Overriding Rule' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'J_AllocationFactor', @level2type=N'COLUMN',@level2name=N'FactorType'
END
ELSE Print 'Column [J_AllocationFactor.FactorType] 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.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_BroadcastDeployment') AND Name = N'ActivityId')
BEGIN
	ALTER TABLE [dbo].[J_BroadcastDeployment] ADD [ActivityId] BIGINT NULL
END
ELSE
	Print 'Column [ActivityId] Already Exists'
GO

-- ALTER [MaxHour] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_ManningRatio') AND Name = N'MaxHour' And system_type_id = 56)
BEGIN
	ALTER TABLE [dbo].[J_ManningRatio] ALTER COLUMN [MaxHour] Decimal(18,2) NULL 
END
ELSE
	Print 'Column [J_ManningRatio.MaxHour] Already Exists'
GO

-- ALTER [RBHour] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_ManningRatio') AND Name = N'RBHour' And system_type_id = 56)
BEGIN
	ALTER TABLE [dbo].[J_ManningRatio] ALTER COLUMN [RBHour] Decimal(18,2) NULL 
END
ELSE
	Print 'Column [J_ManningRatio.RBHour] Already Exists'
GO

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

-- Add Column [RatioName] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_ManningRatio') AND Name = N'RatioName')
BEGIN
	ALTER TABLE [dbo].[J_ManningRatio] ADD [RatioName] nVarchar(255) NULL 
END
ELSE
	Print 'Column [J_ManningRatio.RatioName] Already Exists'
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'
GO

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'
GO

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 [WorkloadId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.J_Workload') AND Name = N'LocationId')
BEGIN
	ALTER TABLE [dbo].[J_Workload] ADD [LocationId] [BigInt] NULL 
END
ELSE
	Print 'Column [J_Workload.LocationId] Already Exists'
GO
-- Add [LeaveId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_EmployeeLieuDates') AND Name = N'LeaveId')
BEGIN
	ALTER TABLE [dbo].L_EmployeeLieuDates ADD [LeaveId] [bigint] NULL 
END
ELSE
	Print 'Column [L_EmployeeLieuDates.LeaveId] Already Exists'
GO
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_LeaveProfiles') AND Name = N'IsHRApprovalRequired')
BEGIN
	ALTER TABLE [dbo].[L_LeaveProfiles]  ADD [IsHRApprovalRequired] BIT DEFAULT (0)
END
ELSE
	Print 'Column [IsHRApprovalRequired] Already Exists'
GO

UPDATE L_LeaveProfiles SET IsHRApprovalRequired = 0 WHERE IsHRApprovalRequired IS NULL
GO

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

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

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

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

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_LeaveProfiles') AND Name = N'IsBackDateAllowed')
BEGIN
	ALTER TABLE [dbo].[L_LeaveProfiles]  ADD [IsBackDateAllowed] BIT DEFAULT (0)
END
ELSE
	Print 'Column [IsBackDateAllowed] Already 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 [PanelClinicId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_Leaves') AND Name = N'PanelClinicId')
BEGIN
	ALTER TABLE [dbo].[L_Leaves] ADD [PanelClinicId] BigInt NULL 
END
ELSE
	Print 'Column [L_Leaves.PanelClinicId] Already Exists'
GO

-- Add [HalfDayType] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.L_Leaves') AND Name = N'HalfDayType')
BEGIN
	ALTER TABLE [dbo].[L_Leaves] ADD [HalfDayType] nVarchar(50) NULL 
END
ELSE
	Print 'Column [L_Leaves.HalfDayType] 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
 

-- Add [LocationId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_AuxiliaryWork') AND Name = N'LocationId')
BEGIN
	ALTER TABLE [dbo].[M_AuxiliaryWork] ADD [LocationId] BigInt NULL
END
ELSE
	Print 'Column [LocationId] Already Exists'
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
-- Add Crane Priority Id
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_CraneSchedule') AND Name = N'CranePriorityId')
BEGIN
	ALTER TABLE [dbo].[M_CraneSchedule] ADD [CranePriorityId] bigint
END
ELSE
	Print 'Column [CranePriorityId] Already Exists'
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
 
 
 -- Add Column [IsClockinPicked] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EmployeeEquipmentLogin') AND Name = N'IsClockInPicked')
BEGIN
	ALTER TABLE [dbo].[M_EmployeeEquipmentLogin] ADD [IsClockInPicked] BIT DEFAULT 0
	Print 'Column [IsClockInPicked] Added Successfully...'
END	
GO

-- Add Column [IsClockOutPicked] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EmployeeEquipmentLogin') AND Name = N'IsClockOutPicked')
BEGIN
	ALTER TABLE [dbo].[M_EmployeeEquipmentLogin] ADD [IsClockOutPicked] BIT DEFAULT 0
	Print 'Column [IsClockOutPicked] Added Successfully...'
END	
GO

-- Add Column [ActivityId] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EmployeeEquipmentLogin') AND Name = N'ActivityId')
BEGIN
	ALTER TABLE [dbo].[M_EmployeeEquipmentLogin] ADD [ActivityId] [BIGINT] NULL
	Print 'Column [ActivityId] Added Successfully...'
END	
GO

-- Add [LastLocation] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EmployeeEquipmentLogin') AND Name = N'LastLocation')
BEGIN
	ALTER TABLE [dbo].[M_EmployeeEquipmentLogin] ADD [LastLocation] [nVarchar](200) NULL 
END
ELSE
	Print 'Column [M_EmployeeEquipmentLogin.LastLocation] Already Exists'
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

 -- Add Column [IsCrane] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EquipmentMaintenance') AND Name = N'IsCrane')
BEGIN
	ALTER TABLE [dbo].[M_EquipmentMaintenance] ADD [IsCrane] Bit
	Print 'Column [IsCrane] Added Successfully...'
END	
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

-- Add [DayStartTime] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_EquipmentSchedule') AND Name = N'ShiftBandId')
BEGIN
	ALTER TABLE [dbo].[M_EquipmentSchedule] ADD [ShiftBandId] BigInt NULL
END
ELSE
	Print 'Column [ShiftBandId] Already Exists'
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 

-- Add Location Type Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_Locations') AND Name = N'LocationType')
BEGIN
	ALTER TABLE [dbo].M_Locations ADD [LocationType] bigint
END
ELSE
	Print 'Column [M_Locations].[LocationType] Already Exists'
GO
-- Add Activity Generation RuleId Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_PMPlanning') AND Name = N'ActivityGenerationRuleId')
BEGIN
	ALTER TABLE [dbo].M_PMPlanning ADD [ActivityGenerationRuleId] bigint
END
ELSE
	Print 'Column [M_PMPlanning].[ActivityGenerationRuleId] Already Exists'
GO

-- Add Allocation RuleId Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_PMPlanning') AND Name = N'AllocationRuleId')
BEGIN
	ALTER TABLE [dbo].M_PMPlanning ADD [AllocationRuleId] bigint
END
ELSE
	Print 'Column [M_PMPlanning].[AllocationRuleId] Already Exists'
GO

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

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


--Add Equipment Type Id Column

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ResourceSetDetails') AND Name = N'EquipmentTypeId')
BEGIN	
	ALTER TABLE [dbo].[M_ResourceSetDetails] ADD  [EquipmentTypeId] BigInt NULL 
END
ELSE 
 Print 'M_ResourceSetDetails EquipmentTypeId Column Exist'
 
GO

IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ScreenConfiguration') AND Name = N'ConfigName')
BEGIN
	ALTER TABLE [dbo].[M_ScreenConfiguration] ALTER COLUMN [ConfigName] [NVARCHAR](1000) NULL 
END

GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ScreenConfiguration') AND Name = N'UpdatedBy')
BEGIN
	ALTER TABLE [dbo].[M_ScreenConfiguration] ADD [UpdatedBy] [NVARCHAR](50) NULL 
END

GO


IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ScreenConfiguration') AND Name = N'UpdatedDate')
BEGIN
	ALTER TABLE [dbo].[M_ScreenConfiguration] ADD [UpdatedDate] [DateTime] NULL 
END

GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ScreenConfiguration') AND Name = N'FieldType')
BEGIN
	ALTER TABLE [dbo].[M_ScreenConfiguration] ADD [FieldType] [NVARCHAR](50) NULL 
END

IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ScreenConfiguration') AND Name = N'ConfigValue' And max_length != -1)
BEGIN
	ALTER TABLE [dbo].[M_ScreenConfiguration] ALTER COLUMN [ConfigValue] NVARCHAR(max) NULL 
END

GO

-- Add [Remarks] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftAssemble_TemplateGroupDetail') AND Name = N'Remarks')
BEGIN
	ALTER TABLE [dbo].[M_ShiftAssemble_TemplateGroupDetail] ADD [Remarks] [nVarchar](max)
END
ELSE
	Print 'Column [Remarks] Already Exists'
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.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'EquipmentTypes')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [EquipmentTypes] [nvarchar](500) NULL
END
ELSE
	Print 'Column [EquipmentTypes] Already Exists'
GO

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

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_ShiftSignOffStatus') AND Name = N'AllocationRuleId')
BEGIN
	ALTER TABLE [dbo].[M_ShiftSignOffStatus] ADD [AllocationRuleId] BigInt NULL
END
ELSE
	Print 'Column [AllocationRuleId] 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



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

IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_VesselMiscellaneousColumns') AND Name = N'MiscellaneousColumnsId')
BEGIN
	ALTER TABLE [dbo].[M_VesselMiscellaneousColumns] DROP Column [MiscellaneousColumnsId]
END

GO

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.M_VesselMiscellaneousColumns') AND Name = N'WorkloadTypeId')
BEGIN
	ALTER TABLE [dbo].[M_VesselMiscellaneousColumns] Add [WorkloadTypeId] BigInt
END

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

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

UPDATE P_OvertimeSettings SET ActiveStatus = 1 Where ActiveStatus IS NULL
GO

-- Alter [PeriodLength] Column
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_OvertimeSettings') AND Name = N'PeriodLength' AND precision =10)
BEGIN
	ALTER TABLE [dbo].[P_OvertimeSettings] Alter Column [PeriodLength] [decimal](18, 2) 
END

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
	--DELETE FROM SYS.default_constraints Where name like 'DF__P_ShiftCo%';
	DECLARE @shiftCostConstraints nVarchar(max) = '';
	SELECT  @shiftCostConstraints = STUFF(( SELECT ',' + u.name from SYS.default_constraints u where u.name = name  and name like 'DF__P_ShiftCo%' order by u.name for xml path('') ),1,1,'') 
	from SYS.default_constraints where name like 'DF__P_ShiftCo%'
	group by name

	if(Len(@shiftCostConstraints) >0) exec ('ALTER TABLE [dbo].[P_ShiftCosts] DROP CONSTRAINT ' + @shiftCostConstraints)
	
	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

-- Add Column [Remarks] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'Remarks')
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] ADD [Remarks] nVarchar(1000)
	Print 'Column [Remarks] Added Successfully...'
END	
GO

-- Alter Column [CreatedBy] Column 
IF EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.P_ShiftCosts') AND Name = N'CreatedBy' AND max_length = 100)
BEGIN
	ALTER TABLE [dbo].[P_ShiftCosts] Alter Column [CreatedBy] nVarchar(1000)
	Print 'Column [CreatedBy] Added Successfully...'
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
 
-- Add [ApprovalStatus] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_EmployeeLeaves') AND Name = N'ApprovalStatus')
BEGIN
	ALTER TABLE [dbo].[S_EmployeeLeaves] ADD [ApprovalStatus] nVarchar(50) NULL 
END
ELSE
	Print 'Column [S_EmployeeLeaves.ApprovalStatus] Already Exists'
GO

IF NOT EXISTS (SELECT * FROM sys.columns  WHERE Name = N'UpdatedBy' AND Object_ID = Object_ID(N'S_PublicholidayEmployeeList'))
BEGIN
	ALTER TABLE [dbo].[S_PublicholidayEmployeeList] 
	ADD [UpdatedBy] nVarchar(50) NULL

	Print 'Column [UpdatedBy] Added To Table [S_PublicholidayEmployeeList]'
END
ELSE Print 'Column [UpdatedBy] Exists In Table [S_PublicholidayEmployeeList]'
GO

IF NOT EXISTS (SELECT * FROM sys.columns  WHERE Name = N'UpdatedDate' AND Object_ID = Object_ID(N'S_PublicholidayEmployeeList'))
BEGIN
	ALTER TABLE [dbo].[S_PublicholidayEmployeeList] 
	ADD [UpdatedDate] DATETIME NULL

	Print 'Column [UpdatedDate] Added To Table [S_PublicholidayEmployeeList]'
END
ELSE Print 'Column [UpdatedDate] Exists In Table [S_PublicholidayEmployeeList]'
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'

IF NOT EXISTS (SELECT * FROM sys.columns  WHERE Name = N'TemplateId' AND Object_ID = Object_ID(N'S_RosterGroup'))
BEGIN
	ALTER TABLE [dbo].[S_RosterGroup] 
	ADD [TemplateId] BigInt NULL

	Print 'Column [TemplateId] Added To Table [S_RosterGroup]'
END
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

-- Add Column [IncludeLeave] Column 
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_ScheduleRules') AND Name = N'IncludeLeave')
BEGIN
	ALTER TABLE [dbo].[S_ScheduleRules] ADD [IncludeLeave] bit
END
ELSE
	Print 'Column [IncludeLeave] Added Successfully...'
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

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

-- Add [DeploymentNotes] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_Shifts') AND Name = N'DeploymentNotes')
BEGIN
	ALTER TABLE [dbo].[S_Shifts] ADD [DeploymentNotes] nVarchar(255) NULL 
END
ELSE
	Print 'Column [DeploymentNotes] 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_THPEmployeeCraneConditionCounter_C_Employee') AND type in ('F'))
BEGIN

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

	ALTER TABLE [dbo].[S_THPEmployeeCraneConditionCounter] CHECK CONSTRAINT [FK_S_THPEmployeeCraneConditionCounter_C_Employee]
END
ELSE 
 Print 'FK_S_THPEmployeeCraneConditionCounter_C_Employee Key Exist'
GO

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

	ALTER TABLE [dbo].[S_THPEmployeeCraneConditionCounter]  WITH CHECK ADD  CONSTRAINT [FK_S_THPEmployeeCraneConditionCounter_S_THPEmployeePeriods] FOREIGN KEY([THPPeriodId])
	REFERENCES [dbo].[S_THPEmployeePeriods] ([THPPeriodId])

	ALTER TABLE [dbo].[S_THPEmployeeCraneConditionCounter] CHECK CONSTRAINT [FK_S_THPEmployeeCraneConditionCounter_S_THPEmployeePeriods]
END
ELSE 
 Print 'FK_S_THPEmployeeCraneConditionCounter_S_THPEmployeePeriods Key Exist'
GO

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

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

	ALTER TABLE [dbo].[S_THPEmployeeEquipmentDetails] CHECK CONSTRAINT [FK_S_THPEmployeeEquipmentDetails_C_Employee]
END
ELSE 
 Print 'FK_S_THPEmployeeEquipmentDetails_C_Employee Key Exist'

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

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

	ALTER TABLE [dbo].[S_THPEmployeeEquipmentDetails] CHECK CONSTRAINT [FK_S_THPEmployeeEquipmentDetails_M_Equipments]
END
ELSE 
 Print 'FK_S_THPEmployeeEquipmentDetails_M_Equipments Key Exist'

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_THPEmployeeEquipmentDetails_S_THPEmployeePeriods') AND type in ('F'))
BEGIN
	ALTER TABLE S_THPEmployeeEquipmentDetails DROP CONSTRAINT [FK_S_THPEmployeeEquipmentDetails_S_THPEmployeePeriods]
END
ELSE 
 Print 'FK_S_THPEmployeeEquipmentDetails_S_THPEmployeePeriods Deleted'

GO


IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_THPEmployeeEquipmentDetails_S_Shifts') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[S_THPEmployeeEquipmentDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_THPEmployeeEquipmentDetails_S_Shifts] FOREIGN KEY([ShiftId])
	REFERENCES [dbo].[S_Shifts] ([ShiftId])
	
	ALTER TABLE [dbo].[S_THPEmployeeEquipmentDetails] CHECK CONSTRAINT [FK_S_THPEmployeeEquipmentDetails_S_Shifts]
END
ELSE PRINT 'FK_S_THPEmployeeEquipmentDetails_S_Shifts Key Exist'
GO

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

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

	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails] CHECK CONSTRAINT [FK_S_THPEmployeeSkillDetails_C_Employee]
END
ELSE 
 Print 'FK_S_THPEmployeeSkillDetails_C_Employee Table Exist'


IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_THPEmployeeSkillDetails_S_Shifts') AND type in ('F'))
BEGIN
	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails] DROP CONSTRAINT FK_S_THPEmployeeSkillDetails_S_Shifts
END
--IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.FK_S_THPEmployeeSkillDetails_S_Shifts') AND type in ('F'))
--BEGIN

--	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_THPEmployeeSkillDetails_S_Shifts] FOREIGN KEY([ShiftId])
--	REFERENCES [dbo].[S_Shifts] ([ShiftId])

--	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails] CHECK CONSTRAINT [FK_S_THPEmployeeSkillDetails_S_Shifts]
--END
--ELSE 
-- Print 'FK_S_THPEmployeeSkillDetails_S_Shifts Table Exist'

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

	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails]  WITH CHECK ADD  CONSTRAINT [FK_S_THPEmployeeSkillDetails_S_THPEmployeePeriods] FOREIGN KEY([THPPeriodId])
	REFERENCES [dbo].[S_THPEmployeePeriods] ([THPPeriodId])

	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails] CHECK CONSTRAINT [FK_S_THPEmployeeSkillDetails_S_THPEmployeePeriods]

END
ELSE 
 Print 'FK_S_THPEmployeeSkillDetails_S_THPEmployeePeriods Table Exist'

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

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

	ALTER TABLE [dbo].[S_THPEmployeeSkillDetails] CHECK CONSTRAINT [FK_S_THPEmployeeSkillDetails_S_THPEmployeeSkillDetails]
END
ELSE 
 Print 'FK_S_THPEmployeeSkillDetails_S_THPEmployeeSkillDetails 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.columns WHERE Object_ID = OBJECT_ID(N'dbo.S_THPSettings') AND Name = N'ActiveStatus')
BEGIN
	ALTER TABLE [dbo].[S_THPSettings] ADD [ActiveStatus] BIT DEFAULT (0)
END
ELSE
	Print 'Column [ActiveStatus] Already Exists'
GO

UPDATE S_THPSettings SET ActiveStatus = 1 WHere ActiveStatus IS NULL
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
-- Add [BackendProcessId] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.T_SystemTask') AND Name = N'BackendProcessId')
BEGIN
	ALTER TABLE [dbo].T_SystemTask ADD [BackendProcessId] [BigInt] NULL 
END
ELSE
	Print 'Column [BackendProcessId] Already Exists'
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

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

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

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

-- Add [DayOfWeek] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.T_SystemTaskSchedule') AND Name = N'DayOfWeek')
BEGIN
	ALTER TABLE [dbo].T_SystemTaskSchedule ADD [DayOfWeek] [nvarchar](20)	 NULL 
END
ELSE
	Print 'Column DayOfWeek Already Exists'
GO
-- ADD [EffectiveFrom] Column
IF NOT EXISTS (SELECT * FROM sys.columns WHERE Object_ID = OBJECT_ID(N'dbo.W_Modules') AND Name = N'LeaveCodes')
BEGIN
	ALTER TABLE [dbo].[W_Modules] ADD [LeaveCodes] nVarchar(Max)
END
ELSE 
 Print 'W_Modules.LeaveCodes Column 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'IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeePanelClinicsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeePanelClinicsIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UC_EmployeePanelClinics')
DROP TYPE  [UC_EmployeePanelClinics]
Go

CREATE TYPE [UC_EmployeePanelClinics] as table (
    [EmployeeId] [bigint] NULL,	
	[PanelClinicId] [BigInt] NULL,	
	[EffectiveFrom] [DateTime] NULL,
	[EffectiveTo] [DateTime] NULL,
	[CreatedBy] nVarchar(200) NULL,
	[UpdatedBy] nVarchar(200) NULL)	

 GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_EquipmentClockingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_EquipmentClockingIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UIE_EquipmentClocking')
DROP TYPE  [UIE_EquipmentClocking]
Go

CREATE TYPE [UIE_EquipmentClocking] as table (
   	[EquipmentName] [nvarchar](50) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[ClockingDateTime] [datetime] NULL,
	[ClockOutDateTime] [datetime] NULL,
	[TypeId] [int] NULL,
	[PickupPoint] [nvarchar](50) NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_SlashedCranesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_SlashedCranesIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UJ_SlashedCranes')
DROP TYPE  [UJ_SlashedCranes]
Go

CREATE TYPE [UJ_SlashedCranes] as table (
	[SlashedCraneId]	[BigInt] NOT NULL,
   	[ShiftDate]			[DateTime] NOT NULL,
	[ShiftBandId]		[BigInt] NOT NULL,
	[SkillId]			[BigInt] NOT NULL,
	[WorkloadId]		[BigInt] NOT NULL,
	[ActivityStart]		[DateTime] NOT NULL,
	[ActivityEnd]		[DateTime] NOT NULL,
	[CraneScheduleId]	[BigInt] NOT NULL,
	[GroupNumber]		[BigInt] NOT NULL,
	[CraneId]			[BigInt] NOT NULL,
	[IsSlashed]			[Bit] NOT NULL,
	[CreatedBy]			[nVarchar](100) NOT NULL
)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_EmployeeLeaveProfileCreateorUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_EmployeeLeaveProfileCreateorUpdate]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UL_EmployeeLeaveProfiles')
DROP TYPE  [UL_EmployeeLeaveProfiles]
Go

CREATE TYPE [UL_EmployeeLeaveProfiles] as table (
    [EmpProfileId] [bigint] NOT NULL,
   	[EmployeeId] [bigint] NULL,	
	[LeaveProfileId] [int] NULL,
	[StartDate] [datetime] NULL,
	[EndDate] [datetime] NULL,
	[LeaveYear] [int] NULL,
	[ExceptionId] [bigint] NULL,
	[EntitlementDays] [decimal] NULL,
	[CarryForwardDays] [decimal] NULL,
	[EarnedDays] [decimal] NULL,
	[DaysUsed] [decimal] NULL,
	[AdjustDays] [decimal] NULL,
	[DaysLieu] [decimal] NULL,
    [UsedDays] [decimal] NULL,
	[BalanceDays] [decimal] NULL,
    [EarnedDays_Cal] [decimal] NULL,
	[EarnedDays_Adj] [decimal] NULL,
	[EarnedMonth] [int] NULL,
	[AdjustmentRemakrs] [text] NULL,
    [CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
    [UpdatedBy] [nvarchar](50) NULL)	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_EmployeeLieuDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_EmployeeLieuDates]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UL_EmployeeLieuDates')
DROP TYPE  [UL_EmployeeLieuDates]
Go

CREATE TYPE [UL_EmployeeLieuDates] as table (
    [EmployeeId] [bigint] NULL,	
	[LieuDate] [datetime] NULL,
	[Utilized] [Bit] NULL,
	[CreatedBy] nVarchar(200) NULL,
	[UpdatedBy] nVarchar(200) NULL)	

 GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_AddLeaveBalanceDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_AddLeaveBalanceDiscrepancy]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UL_LeaveBalanceDiscrepancy')
DROP TYPE  [UL_LeaveBalanceDiscrepancy]
Go

CREATE TYPE [UL_LeaveBalanceDiscrepancy] as table (
	[LeaveBalanceDiscrepancyId] [BigInt] NOT NULL,
    [EmployeeLeaveProfileId] [bigint] NOT NULL,
   	[UsedDaysFromMYERP] [Decimal] NULL,	
	[LMSBalanceDays] [Decimal] NULL,
	[MYERPBalanceDays] [Decimal] NULL,
    [CreatedBy] [nvarchar](50) NULL
)	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentBoxMovementIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentBoxMovementIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UM_EmployeeEquipmentBoxMovement')
DROP TYPE  [UM_EmployeeEquipmentBoxMovement]
Go

CREATE TYPE [UM_EmployeeEquipmentBoxMovement] as table (
	[EmployeeNumber] [nvarchar](50) NULL,
	[EquipmentName] [nvarchar](50) NULL,
	[LoginTime] [datetime] NULL,
	[LogoutTime] [datetime] NULL,
	[NoOfMoves] [int] NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
	[EquipmentType] [nVarchar](100) NULL,
	[EmployeeId] [bigint] NULL)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginIns]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginIns]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginUpd]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginUpd]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UM_EmployeeEquipmentLogin')
DROP TYPE  [UM_EmployeeEquipmentLogin]
Go

CREATE TYPE [UM_EmployeeEquipmentLogin] as table (
   	[EquipmentName] [nvarchar](50) NULL,
	[EmployeeNumber] [nvarchar](50) NULL,
	[EmployeeId] [bigint] NULL,
	[ClockInDateTime] [datetime] NULL,
	[ClockOutDateTime] [datetime] NULL,
	[TypeId] [int] NULL,
	[PickupPoint] [nvarchar](50) NULL,
	[Remarks] [nvarchar](50) NULL,
	[Source] [nvarchar](50) NULL,
	[CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
	[LastLocation] [nVarchar](200) NULL
	)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_EmployeeLeaveCreateOrUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeaveCreateOrUpdate]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'US_EmployeeLeaves')
DROP TYPE  [US_EmployeeLeaves]
Go

CREATE TYPE [US_EmployeeLeaves] as table (
    [LeaveId] [bigint] 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,
	[ApprovalStatus]  [nvarchar](50) NULL )

 GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prA_ShiftCostIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prA_ShiftCostIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTA_ShiftCosts')
DROP TYPE  [UTA_ShiftCosts]
Go

CREATE TYPE [UTA_ShiftCosts] as table (  
	[ShiftCostId] [bigint] NOT NULL,
	[ShiftId] [bigint] NULL,
	[PayCodeId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[ActualHour] [float] NULL,
	[ShiftCost] [float] NULL,
	[AdjustmentCost] [float] NULL,
	[TotalCost] [float] NULL,
	[CreatedBy] [nvarchar](1000) NULL,	
	[ApprovalStatus] [int] NULL,
	[ApprovedHours] [float] NULL,	
	[Action] [nVarchar] (200) NOT NULL,
	[ActionBy] [nVarchar] (2000) NOT NULL,
	[PayCodeDescription] [nVarchar] (510) NULL,
	[Remarks] [nvarchar](1000) NULL)	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_EmployeePerformanceRatingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_EmployeePerformanceRatingIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTJ_EmployeePerformanceRating')
DROP TYPE  [UTJ_EmployeePerformanceRating]
Go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeePerformanceRatingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeePerformanceRatingIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTC_EmployeePerformanceRating')
DROP TYPE  [UTC_EmployeePerformanceRating]
Go


CREATE Type [UTC_EmployeePerformanceRating] as table (
		[Month] [bigint] NOT NULL,
		[Year] [bigint] NOT NULL,
		[EmployeeId] [BigInt] NOT NULL,
		[SelfRating] [nVarchar](10) NULL,		
		[AppraisalByUpperManager] [nVarchar](10) NULL,
		[ApprovedByGM] [nVarchar](10) NULL,
		[ReasonForRating] [nVarchar](max) NULL,
		[CreatedBy] nvarchar(100) NULL,		
		[UpdatedBy] nvarchar(100) NULL)
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_ActivityEquipmentNotesUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_ActivityEquipmentNotesUpdate]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTJ_ActivityEquipmentNotesUpdate')
DROP TYPE  [UTJ_ActivityEquipmentNotesUpdate]
Go


CREATE Type [UTJ_ActivityEquipmentNotesUpdate] as table (
[ActivityId] [bigint]  NOT NULL,
[EquipmentNotes] nVarchar(500) NOT NULL,
[UpdatedBy] [nvarchar](50) NOT NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_ActivityLocationUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_ActivityLocationUpdate]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTJ_ActivityLocationUpdate')
DROP TYPE  [UTJ_ActivityLocationUpdate]
Go


CREATE Type [UTJ_ActivityLocationUpdate] as table (
[ActivityId] [bigint]  NOT NULL,
[LocationId] [BigInt] NOT NULL)
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ConeManPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ConeManPlanDetailIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_ConeManPlanDetail')
DROP TYPE  [UTM_ConeManPlanDetail]
Go

CREATE Type [UTM_ConeManPlanDetail] as table (
[ConeManPlanId] [bigint]  NOT NULL,
[CraneScheduleId] [bigint] NOT NULL,
[CreatedBy] [nvarchar](50) NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginIns]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginUpd]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_EmployeeEquipmentLogin')
DROP TYPE  [UTM_EmployeeEquipmentLogin]
Go

CREATE TYPE [UTM_EmployeeEquipmentLogin] as table (
	[ClockingId] [int] NOT NULL,
   	[IsClockInPicked] [bit],
	[IsClockOutPicked] [bit],
	[ActivityId] [bigint] NULL
)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EquipmentScheduleBulkUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentScheduleBulkUpdate]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_EquipmentScheduleUpdate')
DROP TYPE  [UTM_EquipmentScheduleUpdate]
Go


CREATE Type [UTM_EquipmentScheduleUpdate] as table (
[EquipmentScheduleId] [bigint]  NOT NULL,
[EquipmentId] [bigint] NOT NULL,
[UpdatedBy] [nvarchar](50) NOT NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LasherPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LasherPlanDetailIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_LasherPlanDetail')
DROP TYPE  [UTM_LasherPlanDetail]
Go

CREATE Type [UTM_LasherPlanDetail] as table (
[LasherPlanId] [bigint]  NOT NULL,
[LocationId] [bigint] NOT NULL,
[Requirement] [bigint] NOT NULL,
[VesselName] [nvarchar] (500) null,
[CreatedBy] [nvarchar](50) NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningLocationIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningLocationIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_PMPlanningLocation')
DROP TYPE  [UTM_PMPlanningLocation]
Go

CREATE TYPE [UTM_PMPlanningLocation] as table (
[PMPlanningLocationId] [bigint] NOT NULL,
[PMPlanningId] [bigint] NOT NULL, 
[LocationId] [bigint] NOT NULL,
[SkillId] [bigint] NOT NULL,
[Requirement] [bigint] NOT NULL,
[CreatedBy] [nvarchar](50) NULL,
[UpdatedBy] [nvarchar](50) NULL)



GO




IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningSkillIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningSkillIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_PMPlanningSkills')
DROP TYPE  [UTM_PMPlanningSkills]
Go


CREATE Type [UTM_PMPlanningSkills] as table (
[PMPlanningSkillId] [bigint]  NOT NULL,
[PMPlanningId] [bigint] NOT NULL,
[SkillId] [bigint] NOT NULL,
[Requirement] [bigint] NOT NULL,
[CreatedBy] [nvarchar](50) NULL,
[UpdatedBy] [nvarchar](50) NULL)

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_RTGPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_RTGPlanDetailIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_RTGPlanDetail')
DROP TYPE  [UTM_RTGPlanDetail]
Go

CREATE TYPE [UTM_RTGPlanDetail] as table (
	[RTGPlanId] [bigint] NOT NULL,	
	[EquipmentId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL)	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ShiftAssemble_TemplateGroupDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupDetailIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_ShiftAssemble_TemplateGroupDetail')
DROP TYPE  [UTM_ShiftAssemble_TemplateGroupDetail]
Go

	CREATE Type [dbo].[UTM_ShiftAssemble_TemplateGroupDetail] AS Table(
	[ShiftAssembleDetId] [bigint] NOT NULL,	
	[ShiftAssembleId] [bigint] NOT NULL,	
	[TypeId] [BigInt] NULL,
	[EquipmentTypeId] [BigInt] NULL,
	[SkillId] [BigInt] NULL,
	[Requirement] [int] NULL,
	[LocationId] [BigInt] NULL,
	[CreatedBy] nvarchar(100) NULL,		
	[UpdatedBy] nvarchar(100) NULL,
	[Remarks] nVarchar(max) NULL)
	Go


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_StackersPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_StackersPlanDetailIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_StackersPlanDetail')
DROP TYPE  [UTM_StackersPlanDetail]
Go

CREATE TYPE [UTM_StackersPlanDetail] as table (	
	[StackersPlanId] [bigint] NOT NULL,	
	[EquipmentId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL)
	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TabReaderPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TabReaderPlanDetailIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_TabReaderPlanDetail')
DROP TYPE  [UTM_TabReaderPlanDetail]
Go

CREATE Type [UTM_TabReaderPlanDetail] as table (
[TabReaderPlanId] [bigint]  NOT NULL,
[VesselScheduleId] [bigint] NOT NULL,
[Requirement] [bigint] NOT NULL,
[CreatedBy] [nvarchar](50) NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TopManPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TopManPlanDetailIns]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_TopManPlanDetail')
DROP TYPE  [UTM_TopManPlanDetail]
Go

CREATE Type [UTM_TopManPlanDetail] as table (
[TopManPlanId] [bigint]  NOT NULL,
[CraneScheduleId] [bigint] NOT NULL,
[CreatedBy] [nvarchar](50) NULL)
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselMiscellaneousColumnsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselMiscellaneousColumnsIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_VesselMiscellaneousColumns')
DROP TYPE  [UTM_VesselMiscellaneousColumns]
Go

CREATE TYPE [UTM_VesselMiscellaneousColumns] as table (
	[VesselScheduleId] [bigint] NOT NULL,
	[MiscValues] [text] NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,	
	[UpdatedBy] [nvarchar](50) NULL,
	[WorkloadTypeId] [bigInt] Not Null)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleResourceSetIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleResourceSetIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTM_VesselScheduleResourceSet')
DROP TYPE  [UTM_VesselScheduleResourceSet]
Go

CREATE TYPE [UTM_VesselScheduleResourceSet] as table (
	[VesselScheduleResourceSetId] [bigint] NOT NULL,
	[VesselScheduleId] [bigint] NOT NULL,
	[ResourceSetId] [bigint] NOT NULL,
	[TypeId] [bigint] NOT NULL,
	[SkillId] [bigint] NOT NULL,
	[EquipmentTypeId] [bigint] NOT NULL,
	[Requirement] [int] NOT NULL,
	[LocationId] [bigint] NOT NULL,
	[CreatedBy] [nvarchar](50) NOT NULL,	
	[UpdatedBy] [nvarchar](50) NULL)

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_ShiftCostIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_ShiftCostIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UTP_ShiftCosts')
DROP TYPE  [UTP_ShiftCosts]
Go

CREATE TYPE [UTP_ShiftCosts] as table (  
	[ShiftId] [bigint] NULL,
	[PayCodeId] [bigint] NULL,
	[StartTime] [datetime] NULL,
	[EndTime] [datetime] NULL,
	[ActualHour] [float] NULL,
	[ShiftCost] [float] NULL,
	[AdjustmentCost] [float] NULL,
	[TotalCost] [float] NULL,
	[CreatedBy] [nvarchar](1000) NULL,	
	[ApprovalStatus] [int] NULL,
	[ApprovedHours] [float] NULL,	
	[Remarks] [nvarchar](1000) NULL)	

 GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_UpdateShiftNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_UpdateShiftNotes]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_UpdateShiftNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_UpdateShiftNotes]
GO

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UT_ShiftNotes')
DROP TYPE  [UT_ShiftNotes]
Go

IF EXISTS (SELECT * FROM sys.types WHERE name = N'UTS_ShiftNotes')
DROP TYPE  [UTS_ShiftNotes]
Go


CREATE TYPE [UTS_ShiftNotes] as table (
[ShiftId] [bigint] not NULL,
[Notes] [nvarchar](500) NULL,
[UpdatedBy] [nvarchar](50) NULL)



GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_LeaveTransactionsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_LeaveTransactionsIns]
GO

IF  EXISTS (SELECT * FROM sys.types WHERE name = N'UT_LeaveTransactions')
DROP TYPE  [UT_LeaveTransactions]
Go

CREATE TYPE [UT_LeaveTransactions] as table (
[EmployeeId] [bigint] not NULL,
[EmployeeNumber] [nvarchar](50) NULL,
[LeaveCode] [nvarchar](50) NULL,
[LeaveDate] [datetime] NULL,
[AppliedDate] [datetime] NULL,
[ApprovedDate] [datetime] NULL,
[ApprovedBy] [nvarchar](50) NULL,
[ApprovalStatus] [nvarchar](100) NULL,
[AsAtDate] [datetime] NULL,
[ProcessDate] [datetime] NULL,
[ProcessBy] [nvarchar](50) NULL)



 GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'fnStringToTable') AND type in (N'TF'))
DROP FUNCTION fnStringToTable
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[V_AnnualLeaveBalance]') AND type in (N'V'))
DROP View [dbo].[V_AnnualLeaveBalance]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE View [dbo].[V_AnnualLeaveBalance]  AS
	with AnnualLeaveBalance as(
	select L_LeaveBalanceAudit.LeaveAuditId,L_LeaveBalanceAudit.EmployeeId,C_Employee.EmployeeNumber,C_Employee.DisplayName EmployeeName,
	L_LeaveBalanceAudit.BalanceDays LeaveBalance,D_ExceptionCodes.ExcpetionCodeName LeaveCode,L_LeaveBalanceAudit.ActionDate,
	ROW_NUMBER()  over (partition by L_LeaveBalanceAudit.EmployeeId order by  L_LeaveBalanceAudit.ActionDate desc) rowid
	from L_LeaveBalanceAudit with (NoLock)  inner join C_Employee with (NoLock) on L_LeaveBalanceAudit.EmployeeId =C_Employee.EmployeeId
	inner join D_ExceptionCodes with (NoLock) on D_ExceptionCodes.ExceptionCodeId= L_LeaveBalanceAudit.ExceptionCodeId
	where L_LeaveBalanceAudit.ExceptionCodeId=1)

    select * from AnnualLeaveBalance where rowid=1

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[V_LeaveTransactions]') AND type in (N'V'))
DROP View [dbo].[V_LeaveTransactions]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE View [dbo].[V_LeaveTransactions]  AS

			--UL/SL Leave  Approved	
		select S_EmployeeLeaves.EmployeeId,C_Employee.EmployeeNumber,D_ExceptionCodes.ExcpetionCodeName LeaveCode,
		S_EmployeeLeaves.FromDate LeaveDate,L_Leaves.AppliedDate,L_Leaves.ApprovedDate,
		S_EmployeeLeaves.ApprovedBy,W_ApprovalStatus.ApprovalStatusDesc ApprovalStatus,S_EmployeeLeaves.ExceptionCodeId,
		S_EmployeeLeaves.UpdatedDate,S_EmployeeLeaves.UpdatedBy,L_Leaves.ApprovalStatusId,L_Leaves.LeaveStart,L_Leaves.LeaveEnd,Convert(int,L_Leaves.NoOfDays)NoOfDays
		from S_EmployeeLeaves With (NoLock)  inner join C_Employee With (NoLock) on S_EmployeeLeaves.EmployeeId =C_Employee.EmployeeId
		inner join L_Leaves   With (NoLock) on S_EmployeeLeaves.EmployeeId = L_Leaves.EmployeeId
		inner join D_ExceptionCodes With (NoLock) on D_ExceptionCodes.ExceptionCodeId= S_EmployeeLeaves.ExceptionCodeId
		inner join W_ApprovalStatus  With (NoLock) on W_ApprovalStatus.ApprovalStatusId=L_Leaves.ApprovalStatusId
		where S_EmployeeLeaves.FromDate between L_Leaves.LeaveStart and L_Leaves.LeaveEnd and S_EmployeeLeaves.ExceptionCodeId in(2,4)
		and L_Leaves.ApprovalStatusId in(1,5)
		union 
		--UL/SL Leave Approved cancelled or other status
		select L_Leaves.EmployeeId,C_Employee.EmployeeNumber,D_ExceptionCodes.ExcpetionCodeName LeaveCode, 
		L_Leaves.LeaveStart LeaveDate,L_Leaves.AppliedDate,L_Leaves.ApprovedDate,
		L_Leaves.ApprovedBy,W_ApprovalStatus.ApprovalStatusDesc ApprovalStatus,L_Leaves.ExceptionCodeId,
		L_Leaves.UpdatedDate,L_Leaves.UpdatedBy,L_Leaves.ApprovalStatusId,L_Leaves.LeaveStart,L_Leaves.LeaveEnd,Convert(int,L_Leaves.NoOfDays)NoOfDays
		from L_Leaves  inner join C_Employee on L_Leaves.EmployeeId =C_Employee.EmployeeId
		inner join D_ExceptionCodes on D_ExceptionCodes.ExceptionCodeId= L_Leaves.ExceptionCodeId
		inner join W_ApprovalStatus on W_ApprovalStatus.ApprovalStatusId=L_Leaves.ApprovalStatusId
		where L_Leaves.ExceptionCodeId in(2,4) and L_Leaves.ApprovalStatusId in(1,5)

GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentBrandNames') AND type in ('U'))
BEGIN
CREATE TABLE [dbo].[M_EquipmentBrandNames](
	[BrandNameId] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentTypeId] [bigint] NULL,
	[BrandName] [nvarchar](50) NULL,
	[BrandDesc] [nvarchar](50) NULL,
	[OUID] [bigint] NULL,
	[IsActive] [bit] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[CreatedDate] [datetime] NULL,
	[UpdatedBy] [nvarchar](50) NULL,
	[UpdatedDate] [datetime] NULL,
 CONSTRAINT [PK_M_EquipmentBrandNames] PRIMARY KEY CLUSTERED 
(
	[BrandNameId] 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_EquipmentBrandNames Table Exist'
 
GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.M_EquipmentBrands') AND type in ('U'))
BEGIN
CREATE TABLE [dbo].[M_EquipmentBrands](
	[EquipmentBrandId] [bigint] IDENTITY(1,1) NOT NULL,
	[EquipmentId] [bigint] NULL,
	[BrandNameId] [bigint] NOT NULL,
	[IsActive] [bit] NULL,
	[CreatedDate] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
 CONSTRAINT [PK_M_EquipmentBrands] PRIMARY KEY CLUSTERED 
(
	[EquipmentBrandId] 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_EquipmentBrands Table Exist'
 
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,
	@TypeId bigInt = NULL,
	@EquipmentTypeId bigInt = NULL

AS

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

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,
		--iif(M_ResourceSetDetails.SkillId = 0,M_ResourceSetDetails.EquipmentTypeId,M_ResourceSetDetails.SkillId)SkillId,
		M_ResourceSetDetails.SkillId,
		D_Skill.Skill SkillName,
		M_ResourceSetDetails.Requirement,
		M_ResourceSetDetails.LocationId,
		M_ResourceSetDetails.EquipmentTypeId,
		M_Locations.LocationName,
		M_ResourceSetDetails.CreatedBy,
		M_ResourceSetDetails.CreatedDate,
		M_ResourceSetDetails.UpdatedBy,
		M_ResourceSetDetails.UpdatedDate,
		M_ResourceSetDetails.TypeId		
FROM	M_ResourceSetDetails WITH (NOLOCK)
		LEFT OUTER JOIN D_Skill ON M_ResourceSetDetails.SkillId = D_Skill.SkillId
		LEFT OUTER JOIN M_EquipmentType ON M_ResourceSetDetails.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
		LEFT OUTER JOIN M_Locations ON M_ResourceSetDetails.LocationId = M_Locations.LocationId
WHERE 	ResourceSetId = @ResourceSetId

GO

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

CREATE PROCEDURE prA_AddEmployeeAudit
(
	@EmployeeId			BigInt,
	@AuditAction		nVarchar(500),
	@AuditActionId		Int,
	@AuditActionBy		nVarchar(50) = NULL,
	@More				nVarchar(max) = NULL,
	@Roles				nVarchar(max) = NULL,
	@Skills				nVarchar(max) = NULL,
	@ExcludedSkills		nVarchar(max) = NULL,
	@Contacts			nVarchar(max) = NULL,
	@Disciplinary		nVarchar(max) = NULL,
	@Workflow			nVarchar(max) = NULL,
	@UserSecurityRoles	nVarchar(max) = NULL,
	@SharedOrgUnit		nVarchar(max) = NULL,
	@LeaveProfiles		nVarchar(max) = NULL,
	@PrimaryRole		nVarchar(255) = NULL,
	@ProfileId			BigInt = 0
)
AS
BEGIN	

	--Employee Create / Updated/ Roster Group Assigned / Changed / Movement Transfer
	If (@AuditActionId = 1 OR @AuditActionId = 2 OR @AuditActionId = 3 OR @AuditActionId = 4 OR @AuditActionId = 5)
	BEGIN
		INSERT INTO A_Employee
		(ActionDate, ProcessName, EmployeeId, OUName, RosterGroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
		DisplayName, EmploymentBasis, IsTerminated, Position, Title, ScheduleRuleName, PayGroupName, OverTimeName, HourlyRate,
		ContractedHours, More, Roles, Skills, Disciplinary, Workflow, UserSecurityRoles, SharedOrganizationUnits, LeaveProfiles, 
		UpdatedBy, PrimaryRole, Miscellaneous)
		SELECT GETDATE(), @AuditAction, @EmployeeId, C_OrganizationNode.OUName, S_RosterGroup.GroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
				DisplayName, D_EmploymentBasis.EmploymentBasisCode, IsTerminated, Position, Title, S_ScheduleRules.Name, D_PayGroup.PayGroupCode, P_OvertimeSettings.OTName, HourlyRate,
				ContractedHours, @More, @Roles, @Skills, @Disciplinary, @Workflow, @UserSecurityRoles, @SharedOrgUnit, 
				@LeaveProfiles, @AuditActionBy, @PrimaryRole, C_EmployeeMiscellaneous.MiscValues
		FROM	C_Employee WITH (NOLOCK) 
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
				LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
				LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
				LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId
				LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OverTimeId
				LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
				LEFT OUTER JOIN C_EmployeeMiscellaneous WITH (NOLOCK) ON C_EmployeeMiscellaneous.EmployeeId = C_Employee.EmployeeId
		WHERE	C_Employee.EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint)  
	END
	Else If (@AuditActionId = 6 OR @AuditActionId = 7) -- Ramadan Type
	BEGIN
		INSERT INTO A_Employee
		(ActionDate, ProcessName, EmployeeId, OUName, RosterGroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
		DisplayName, EmploymentBasis, IsTerminated, Position, Title, ScheduleRuleName, PayGroupName, OverTimeName, HourlyRate,
		ContractedHours, RamadanPeriodType, UpdatedBy)
		SELECT GETDATE(), @AuditAction, @EmployeeId, C_OrganizationNode.OUName, S_RosterGroup.GroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
				DisplayName, D_EmploymentBasis.EmploymentBasisCode, IsTerminated, Position, Title, S_ScheduleRules.Name, D_PayGroup.PayGroupCode, P_OvertimeSettings.OTName, HourlyRate,
				ContractedHours,  @PrimaryRole, @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
				LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
				LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
				LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId
				LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OverTimeId
				LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
		WHERE	EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint)  
	END
	Else If (@AuditActionId = 8 OR @AuditActionId = 9) -- Public Holiday Type
	BEGIN
		INSERT INTO A_Employee
		(ActionDate, ProcessName, EmployeeId, OUName, RosterGroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
		DisplayName, EmploymentBasis, IsTerminated, Position, Title, ScheduleRuleName, PayGroupName, OverTimeName, HourlyRate,
		ContractedHours, PublicHolidayType, UpdatedBy)
		SELECT GETDATE(), @AuditAction, @EmployeeId, C_OrganizationNode.OUName, S_RosterGroup.GroupName, EmployeeNumber, BadgeNumber, FirstName, MiddleName, LastName, 
				DisplayName, D_EmploymentBasis.EmploymentBasisCode, IsTerminated, Position, Title, S_ScheduleRules.Name, D_PayGroup.PayGroupCode, P_OvertimeSettings.OTName, HourlyRate,
				ContractedHours,  @PrimaryRole, @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
				LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
				LEFT OUTER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
				LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId
				LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OverTimeId
				LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
		WHERE	EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint)  
	END
	Else If (@AuditActionId = 10)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, ScheduleRuleName, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, IsNull(S_ScheduleRules.Name,''), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON C_Employee.ScheduleRuleId = S_ScheduleRules.ScheduleRuleId
		WHERE	EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint) 
	END
	Else If (@AuditActionId = 11)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, OvertimeName, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, IsNull(P_OvertimeSettings.OTName,''), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON C_Employee.OvertimeId = P_OvertimeSettings.OvertimeId
		WHERE	EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint) 
	END
	Else If (@AuditActionId = 12)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, PayGroupName, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, IsNull(D_PayGroup.PayGroupCode,''), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON C_Employee.PayGroupId = D_PayGroup.PayGroupId
		WHERE	EmployeeId = @EmployeeId

		SELECT  CAST(@@Identity AS bigint) 
	END
	Else If (@AuditActionId = 13)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, LeaveProfiles, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber,L_LeaveProfileHeader.ProfileName+' '+ Convert(nvarchar,C_EmployeeLeaveProfile.StartDate,120)+' '+Convert(nvarchar,C_EmployeeLeaveProfile.EndDate,120), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
				LEFT OUTER JOIN C_EmployeeLeaveProfile  WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeLeaveProfile.EmployeeId
	            LEFT OUTER JOIN L_LeaveProfileHeader  WITH (NOLOCK) ON C_EmployeeLeaveProfile.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId		  
		WHERE	C_Employee.EmployeeId = @EmployeeId
		        AND C_EmployeeLeaveProfile.EmployeeLeaveProfileId = @ProfileId
		SELECT  CAST(@@Identity AS bigint) 
	END
		Else If (@AuditActionId = 14)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, Workflow, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, W_WorkflowRoute.RouteName+' '+ Convert(nvarchar,C_EmployeeWorkflow.StartDate,120)+' '+Convert(nvarchar,C_EmployeeWorkflow.EndDate,120), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
			    LEFT OUTER JOIN C_EmployeeWorkflow  WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeWorkflow.EmployeeId
	            LEFT OUTER JOIN W_WorkflowRoute  WITH (NOLOCK) ON C_EmployeeWorkflow.RouteId = W_WorkflowRoute.RouteId
		WHERE	C_Employee.EmployeeId = @EmployeeId
		        AND C_EmployeeWorkflow.EmployeeWorkflowId = @ProfileId
		SELECT  CAST(@@Identity AS bigint) 
	END
		Else If (@AuditActionId = 15)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, UserSecurityRoles, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, IsNull( C_SecurityRole.SecurityRoleCode,''), @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
			    LEFT OUTER JOIN C_User  WITH (NOLOCK) ON C_Employee.EmployeeId=C_User.EmployeeId
		        LEFT OUTER JOIN C_UserSecurityRole  WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
	            LEFT OUTER JOIN C_SecurityRole  WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
		WHERE	C_Employee.EmployeeId = @EmployeeId
		SELECT  CAST(@@Identity AS bigint) 
	END
		Else If (@AuditActionId = 16)
	BEGIN
		INSERT INTO A_Employee	 
		(ActionDate, ProcessName, EmployeeId, EmployeeNumber, UpdatedBy)
		SELECT	GETDATE(), @AuditAction, @EmployeeId, C_Employee.EmployeeNumber, @AuditActionBy
		FROM	C_Employee WITH (NOLOCK) 
			    LEFT OUTER JOIN C_EmployeePanelClinics  WITH (NOLOCK) ON C_Employee.EmployeeId=C_EmployeePanelClinics.EmployeeId
		        LEFT OUTER JOIN D_PanelClinics  WITH (NOLOCK) ON C_EmployeePanelClinics.PanelClinicId = D_PanelClinics.PanelClinicId
		WHERE	C_Employee.EmployeeId = @EmployeeId
		        
		SELECT  CAST(@@Identity AS bigint) 
	END
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prA_AddOperationsAudit')
	DROP PROCEDURE prA_AddOperationsAudit
GO

CREATE PROC prA_AddOperationsAudit
(
	@OUId			BigInt,
	@ShiftId		BigInt,
	@StartTime		DateTime = NULL,
	@EndTime		DateTime = NULL,
	@Action			Int,
	@ActionType		Int,
	@ActionDetails	nVarchar(Max),
	@Remarks		nVarchar(1000) = NULL,
	@ActionBy		nVarchar(100)
)
AS
BEGIN
	INSERT INTO A_Operations
	(OUId, ShiftId, StartTime, EndTime, [Action], ActionType, ActionDetails, Remarks, ActionDate, ActionBy)
	VALUES(@OUId, @ShiftId, @StartTime, @EndTime, @Action, @ActionType, @ActionDetails, @Remarks, GETDATE(), @ActionBy)

	SELECT SCOPE_IDENTITY();
END
GO

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

CREATE PROCEDURE prA_AddRawClockingById
(
	@ClockingId		BigInt = 0,
	@AuditActionId	Int = 0,
	@AuditAction	nVarchar(50),
	@ActionBy		nVarchar(100)
)
AS
BEGIN
	INSERT INTO A_Rawclocking
	(ClockingId, TypeId, CardNo, TerminalName, SwipeDateTime, EmployeeNumber, EmployeeId, CollectionDateTime, Allocated, ReconDate, ReconBy, CreatedBy, 
	 CreatedDate, Action, ActionDate, ActionBy)
	SELECT	@ClockingId, TypeId, CardNo, TerminalName, SwipeDateTime, EmployeeNo, EmployeeId, CollectionDateTime, Allocated, ReconDate, ReconBy, CreatedBy,
			CreatedDate, @AuditAction, GETDATE(), @ActionBy
	FROM	TA_Rawclocking WITH (NOLOCK) 
	WHERE	ClockingId	=	@ClockingId

	SELECT  CAST(@@Identity AS BigInt)  
END
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,
	@LeaveId			BigInt = 0,
	@EmployeeId			BigInt = 0,
	@LeaveDate			DateTime = NULL,
	@ExceptionCodeId	BigInt = 0
)
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 
		OR @AuditActionId = 20 OR @AuditActionId = 21 OR @AuditActionId = 24 OR @AuditActionId = 25 OR @AuditActionId = 30)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime, CreatedBy, CreatedDate, ActionBy, RBRRank)
		SELECT  @ShiftId, S_Shifts.EmployeeId, @AuditAction, GETDATE(), D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime, S_Shifts.ActualEndTime, S_Shifts.CreatedBy, S_Shifts.CreatedDate, @AuditActionBy, RBRRank
		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, RBRRank)
		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, RBRRank
		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, RBRRank)
		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, RBRRank
		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, RBRRank)
		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, RBRRank
		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
	-- Approved Or Updated Leave Application Audit By Shift
	Else If (@AuditActionId = 7 OR @AuditActionId = 25) 
	BEGIN

		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime, LeaveType, LeaveAppliedBy,
		 LeaveApprovedBy, LeaveAppliedDate, LeaveApprovedDate, ActionBy, RBRRank)
		 SELECT	S_EmployeeLeaves.ShiftId, S_EmployeeLeaves.EmployeeId, @AuditAction, GETDATE(), D_ShiftBand.ShiftBandCode, 
				S_Shifts.ShiftStartTime, S_Shifts.ShiftEndTime, D_ExceptionCodes.ExcpetionCodeName, C_Employee.EmployeeNumber,
				S_EmployeeLeaves.ApprovedBy, S_EmployeeLeaves.CreatedDate, S_EmployeeLeaves.CreatedDate, @AuditActionBy, S_Shifts.RBRRank
		 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 D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId
		WHERE	S_EmployeeLeaves.LeaveId	=	@LeaveId

		SELECT  IsNull(CAST(@@Identity AS bigint),1)
	END
	-- Leave Cancelled 
	Else If (@AuditActionId = 9)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime,ActionBy, RBRRank)
		 SELECT	S_EmployeeLeaves.ShiftId, S_EmployeeLeaves.EmployeeId, @AuditAction, GETDATE(), D_ShiftBand.ShiftBandCode, 
				S_Shifts.ShiftStartTime, S_Shifts.ShiftEndTime, @AuditActionBy, S_Shifts.RBRRank
		 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 D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId
		WHERE	S_EmployeeLeaves.EmployeeId					=	@EmployeeId
		AND		Convert(Date,S_EmployeeLeaves.FromDate)		=	Convert(Date,@LeaveDate)
		AND		S_EmployeeLeaves.ExceptionCodeId			=	@ExceptionCodeId

		SELECT  IsNull(CAST(@@Identity AS bigint),1)
	END
	-- Shift Costing Audit
	Else If (@AuditActionId = 15)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ActionBy, ShiftBandName, ShiftStartTime, ShiftEndTime, ClockIn, ClockOut,
		 InStatus, OutStatus, ShiftCost, RBRRank)
		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, ''), S_Shifts.RBRRank
				--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, S_Shifts.RBRRank

		SELECT  CAST(@@Identity AS bigint)
		--SELECT 1 
	END
	-- 22 = Deleted Shift Exception Audit, 23 = Create Shift Exception Audit
	Else If (@AuditActionId = 22 OR @AuditActionId = 23)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ActionBy, ShiftBandName, ShiftStartTime, ShiftEndTime, CreatedBy, CreatedDate, 
		 LeaveType, LeaveAppliedBy, LeaveApprovedBy, LeaveAppliedDate, LeaveApprovedDate)
		
		(SELECT	S_Shifts.ShiftId, S_Shifts.EmployeeId, @AuditAction, GETDATE(), @AuditActionBy, D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime StartTime, S_Shifts.ActualEndTime EndTime, S_Shifts.CreatedBy, S_Shifts.CreatedDate, 
				D_ExceptionCodes.ExcpetionCodeName, S_ShiftExceptions.CreatedBy AppliedBy,
				S_ShiftExceptions.CreatedBy ApprovedBy, S_ShiftExceptions.CreatedDate, S_ShiftExceptions.CreatedDate
		FROM	S_Shifts WITH (NOLOCK) 
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
				INNER JOIN S_ShiftExceptions WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		WHERE	S_Shifts.ShiftId = @ShiftId
		Union
				 SELECT	S_EmployeeLeaves.ShiftId, S_EmployeeLeaves.EmployeeId, @AuditAction, GETDATE(),@AuditActionBy, D_ShiftBand.ShiftBandCode, 
				S_Shifts.ShiftStartTime StartTime, S_Shifts.ShiftEndTime EndTime,  S_EmployeeLeaves.CreatedBy, S_EmployeeLeaves.CreatedDate,
				D_ExceptionCodes.ExcpetionCodeName, C_Employee.EmployeeNumber AppliedBy,S_EmployeeLeaves.ApprovedBy, S_EmployeeLeaves.CreatedDate,S_EmployeeLeaves.CreatedDate
		 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 D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId
		WHERE	S_Shifts.ShiftId = @ShiftId)

		SELECT  CAST(@@Identity AS bigint)
	END
    Else If (@AuditActionId = 28 OR @AuditActionId = 29)
	BEGIN
		INSERT INTO A_Shifts
		(ShiftId, EmployeeId, [Action], ActionDate, ActionBy, ShiftBandName, ShiftStartTime, ShiftEndTime, CreatedBy, CreatedDate
		 )
		SELECT	S_Shifts.ShiftId, S_Shifts.EmployeeId, @AuditAction, GETDATE(), @AuditActionBy, D_ShiftBand.ShiftBandCode,
				S_Shifts.ShiftStartTime, S_Shifts.ShiftEndTime, S_Shifts.CreatedBy, S_Shifts.CreatedDate				
		FROM	S_Shifts WITH (NOLOCK) 
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		WHERE	S_Shifts.ShiftId = @ShiftId

		SELECT  CAST(@@Identity AS bigint)
	END
	ELSE SELECT 1

END
GO

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

CREATE PROCEDURE prA_AddShiftCostsById
(
	@ShiftCostId		BigInt = 0,
	@AuditActionId		Int = 0,
	@AuditAction		nVarchar(50),
	@ActionBy			nVarchar(100)
)
AS
BEGIN
	INSERT INTO A_ShiftCosts
	(ShiftCostId, ShiftId, PayCodeId, PayCodeDescription, StartTime, EndTime, ActualHour, ShiftCost, AdjustmentCost, TotalCost, ApprovalStatus, ApprovedHours,
	 CreatedBy, CreatedDate, UpdatedBy, UpdatedDate, [Action], ActionDate, ActionBy, Remarks)
	SELECT	@ShiftCostId, P_ShiftCosts.Shiftid, P_ShiftCosts.PayCodeId, D_Paycodes.PayCodeDesc, StartTime, EndTime, ActualHour, 
			ShiftCost, AdjustmentCost, TotalCost, ApprovalStatus, ApprovedHours,
			P_ShiftCosts.CreatedBy, P_ShiftCosts.CreatedDate, P_ShiftCosts.UpdatedBy, P_ShiftCosts.UpdatedDate, 
			@AuditAction, GETDATE(), @ActionBy, Remarks
	FROM	P_ShiftCosts WITH (NOLOCK) 
			INNER JOIN D_PayCodes WITH (NOLOCK) ON P_ShiftCosts.PayCodeId = D_Paycodes.PayCodeId
	WHERE	P_ShiftCosts.ShiftCostId = @ShiftCostId

	--SELECT  CAST(@@Identity AS BigInt)  
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prA_GetLastExecutedN4InterfaceAudit')
	DROP PROCEDURE prA_GetLastExecutedN4InterfaceAudit
GO

CREATE PROC prA_GetLastExecutedN4InterfaceAudit
 (
	@InterfaceId	BigInt
)
AS
BEGIN
	---AN4 Interface Audit
	SELECT	TOP 1 AN4_Audit.InterfaceAuditId,
			AN4_Audit.InterfaceId,
			AN4_Audit.RequestedOUId,
			AN4_Audit.RequestedParameters,
			AN4_Audit.ResponseData,
			AN4_Audit.RequestedDate,
			AN4_Audit.RequestedBy,
			AN4_Audit.ProcessStartedAt,
			AN4_Audit.ProcessEndAt
	FROM	AN4_Audit WITH(NOLOCK)
	WHERE	InterfaceId	=	@InterfaceId
	ORDER BY InterfaceAuditId DESC
END
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prA_GetN4InterfaceDetail')
	DROP PROCEDURE prA_GetN4InterfaceDetail
GO

CREATE PROC prA_GetN4InterfaceDetail
 (
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS

 ---AN4 Interface Audit

 SELECT		AN4_Audit.InterfaceAuditId,
			AN4_Audit.InterfaceId,
			AN4_Audit.RequestedOUId,
			AN4_Audit.RequestedParameters,
			AN4_Audit.ResponseData,
			AN4_Audit.RequestedDate,
			AN4_Audit.RequestedBy,
			AN4_Audit.ProcessStartedAt,
			AN4_Audit.ProcessEndAt
 FROM		AN4_Audit WITH(NOLOCK)
			 WHERE		Convert(Date,AN4_Audit.ProcessStartedAt) >= @StartDate
 AND		Convert(Date,AN4_Audit.ProcessEndAt) <= @EndDate

 -- Interface Master
 SELECT	  C_InterfaceMaster.InterfaceMasterId,
		  C_InterfaceMaster.Name
 FROM	  C_InterfaceMaster  WITH(NOLOCK)

  -- Interface 
 SELECT	  C_Interfaces.InterfaceId,
		  C_Interfaces.Name
 FROM	  C_Interfaces  WITH(NOLOCK)

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_UserAudit.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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prA_ShiftCostIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prA_ShiftCostIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prA_ShiftCostIns]    
(
	@ShiftCost UTA_ShiftCosts readonly
)
AS
BEGIN
 
	--Insert P_ShiftCost Records
	Merge A_ShiftCosts as Target Using @ShiftCost as Source on(Target.ShiftCostId = Source.ShiftCostId and Target.ShiftId = Source.ShiftId and Target.PayCodeId=Source.PayCodeId )
	When Not Matched then
	Insert (ShiftCostId,ShiftId,PayCodeId,StartTime,EndTime,ActualHour,ShiftCost,AdjustmentCost,TotalCost,CreatedBy,CreatedDate,
	ApprovalStatus,ApprovedHours,Action,ActionDate,ActionBy,PayCodeDescription,Remarks) values(
	Source.ShiftCostId,Source.ShiftId,Source.PayCodeId,Source.StartTime,Source.EndTime,Source.ActualHour,Source.ShiftCost,Source.AdjustmentCost,
	Source.TotalCost,Source.CreatedBy,getdate(),Source.ApprovalStatus,Source.ApprovedHours,Source.Action,GetDate(),Source.ActionBy,Source.PayCodeDescription,Source.Remarks);

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,
	@TemplateId		BigInt,
	@OTSettingsId	BigInt,
	@ScheduleRuleId	BigInt,
	@MovementStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS

BEGIN
	
	INSERT INTO C_EmployeeMovement
	(EmployeeId, OUId, StartDate, EndDate, PrimaryRoleId, RosterGroupId, TemplateId, OTSettingsId, ScheduleRuleId, MovementStatus, 
	 ActiveStatus, CreatedBy, CreatedDate)
	VALUES(	@EmployeeId, @OUId, @StartDate, @EndDate, @PrimaryRoleId, @RosterGroupId, @TemplateId, @OTSettingsId, @ScheduleRuleId, 
			@MovementStatus, 1, @CreatedBy, GETDATE() )

	SELECT  CAST(@@Identity AS bigint) 
		
END
GO

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

----------------------------------------------------------------------------
-- Insert a single record into prC_AddEmployeeNotifications
----------------------------------------------------------------------------
CREATE PROCEDURE prC_AddEmployeeNotifications
(
	@MessageId				BigInt,
	@EmployeeId				BigInt,
	@WebAppHeader			nVarchar(max),
	@WebAppMessage			nVarchar(max),
	@MobileAppHeader		nVarchar(max),
	@MobileAppMessage		nVarchar(max),
	@MessageStatus			Int,
	@CreatedBy				nVarchar(50),
	@IsWebNotification		Bit,
	@IsMobileNotification	Bit,
	@IsActionRequired		Bit
)
AS
BEGIN
	INSERT INTO C_EmployeeNotifications
	(MessageId, EmployeeId, WebAppHeader, WebAppMessage, MobileAppHeader, MobileAppMessage, MessageStatus, CreatedBy, 
	CreatedDate, LastStatusUpdatedDate,  IsDeleted, IsActionRequired, IsWebNotification, IsMobileNotification)
	VALUES(	@MessageId, @EmployeeId, @WebAppHeader, @WebAppMessage, @MobileAppHeader, @MobileAppMessage, 
			@MessageStatus, @CreatedBy, GETDATE(), GETDATE(), 0,  @IsActionRequired, @IsWebNotification, @IsMobileNotification)

	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
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_AddSecurityRoleMenuFunctionPermission') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_AddSecurityRoleMenuFunctionPermission
GO
 
CREATE PROCEDURE prC_AddSecurityRoleMenuFunctionPermission
(
	@SecurityRoleId		BigInt = 0,
	@MenuFunctionId		BigInt = 0,
	@PermissionTypeId	int	= 0,
	@CreatedBy			nVarchar(50)
)
AS
BEGIN	 
	INSERT INTO C_SecurityRoleMenuFunctionPermissions
	(SecurityRoleId, MenuFunctionId, PermissionTypeId, CreatedBy, CreatedDate)
	VALUES(@SecurityRoleId, @MenuFunctionId, @PermissionTypeId, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS bigint)   
END
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 sys.objects WHERE object_id = OBJECT_ID(N'prC_AddUserDeviceToken') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_AddUserDeviceToken
GO
 
Create PROCEDURE prC_AddUserDeviceToken
(
	@UserId			BigInt,
	@EmployeeId		BigInt,
	@DeviceToken	nVarchar(max),
	@DeviceName		nVarchar(100),
	@ActiveStatus	Bit,
	@CreatedBy		nVarchar(50)
)
AS
BEGIN
	INSERT INTO C_UserDeviceTokens
	(UserId, EmployeeId, DeviceToken, DeviceName, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(@UserId, @EmployeeId, @DeviceToken, @DeviceName, @ActiveStatus, @CreatedBy, GETDATE())

	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 sys.objects WHERE object_id = OBJECT_ID(N'prC_DeleteUserDeviceToken') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_DeleteUserDeviceToken
GO
 
Create PROCEDURE prC_DeleteUserDeviceToken
(
	@DeviceToken		nVarchar(max) = ''
)
AS
BEGIN
	DELETE FROM C_UserDeviceTokens
	WHERE	LTrim(RTrim(DeviceToken))	=	LTrim(RTrim(@DeviceToken))

	SELECT 1
END
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,
			D_Roles.RoleName
	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 OR @OUID = 0)
	AND		C_Employee.ActiveStatus = 1 AND OrgNode.ActiveStatus = 1
	AND C_EmployeeRoles.IsPrimaryRole = 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),
	@ExcludeAccrualProcess		Bit
)
AS
BEGIN

	INSERT INTO C_EmployeeDiciplinary
	(EmployeeId, OUId, StatusId, StartDate, EndDate, Remarks, ActionDate, DisciplinaryActionStatus, ActiveStatus, CreatedBy, CreatedDate, ExcludeAccrualProcess)
	VALUES(@EmployeeId, @OUId, @StatusId, @StartDate, @EndDate, @Remarks, @ActionDate, @ActionStatus, @ActiveStatus, @CreatedBy, GETDATE(), @ExcludeAccrualProcess)

	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,
			C_EmployeeDiciplinary.ExcludeAccrualProcess
	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),
	@ExcludeAccrualProcess		Bit
)
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(),
			ExcludeAccrualProcess	=	ExcludeAccrualProcess
	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(500),
	@ProfilePhoto		nVarchar(max),
	@ScheduleRuleId     bigint,
	@PayGroupId         bigint,
	@OvertimeId			BigInt,
	@HourlyRate         decimal(18,4),
	@ContractedHours    decimal(18,4),
	@AlternatePhoto		nVarchar(max),
	@ProbationExpiry	DateTime,
	@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_EmployeeMiscellaneousColValues]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prC_EmployeeMiscellaneousColValues]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeMiscellaneousColValues]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeMiscellaneousColValues]    
(
	@EmployeeId		BigInt
)
AS

BEGIN
	SELECT	C_EmployeeMiscellaneous.EmployeeId ReferenceId,
			C_EmployeeMiscellaneous.MiscValues MiscValue,
			C_EmployeeMiscellaneous.CreatedBy,
			C_EmployeeMiscellaneous.UpdatedBy
	FROM	C_EmployeeMiscellaneous WITH (NOLOCK) 
	WHERE	EmployeeId	=	@EmployeeId
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeeMiscellaneousInsUpd]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prC_EmployeeMiscellaneousInsUpd]
GO
/****** Object:  StoredProcedure [dbo].[prC_EmployeeMiscellaneousInsUpd]    Script Date: 7/24/2018 6:11:34 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_EmployeeMiscellaneousInsUpd]    
(
	@EmployeeId		BigInt,
	@MiscValues		text,
	@CreatedBy		nVarchar(50),
	@UpdatedBy		nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate = COUNT(*) 
	FROM	C_EmployeeMiscellaneous WITH (NOLOCK)
	WHERE	EmployeeId		=	@EmployeeId

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO C_EmployeeMiscellaneous
		(EmployeeId, MiscValues, CreatedBy, CreatedDate)
		VALUES(@EmployeeId, @MiscValues, @CreatedBy, GETDATE())
	END
	ELSE
	BEGIN
		UPDATE	C_EmployeeMiscellaneous	
		SET		MiscValues		=	@MiscValues,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	EmployeeId		=	@EmployeeId
	END

	SELECT 1
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 WITH (NOLOCK)
	WHERE	EmployeeId		=	@EmployeeId
	AND		OUId			=	@OUId
	AND		ActiveStatus	=	1
	And		Convert(date,EndDate) > Convert(Date,@StartDate)
	And		Convert(date,StartDate) < Convert(Date,@EndDate)

	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
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeePanelClinicsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeePanelClinicsIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeePanelClinicsIns]  
(
  @EmployeePanelClinics UC_EmployeePanelClinics readonly
)
AS
BEGIN
    Merge C_EmployeePanelClinics as Target Using @EmployeePanelClinics as Source ON 
		  (Target.EmployeeId = Source.EmployeeId AND Target.PanelClinicId = Source.PanelClinicId	)
	When  Not Matched By Target Then
	Insert (EmployeeId, PanelClinicId, EffectiveFrom, EffectiveTo, CreatedBy, CreatedDate) 
	Values (Source.EmployeeId, Source.PanelClinicId, Source.EffectiveFrom, Source.EffectiveTo, Source.CreatedBy, GETDATE());
	--When Matched Then
	--Update Set  Target.EffectiveFrom		=	Source.EffectiveFrom,
	--			Target.EffectiveTo			=	Source.EffectiveTo,
	--			Target.UpdatedBy            =   Source.UpdatedBy,
	--    		Target.UpdatedDate		    =	GETDATE();
				
	SELECT 1
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_EmployeePerformanceRatingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_EmployeePerformanceRatingIns]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_EmployeePerformanceRatingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_EmployeePerformanceRatingIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prC_EmployeePerformanceRatingIns]    
(
	@EmployeePerformanceRating UTC_EmployeePerformanceRating readonly	
)
AS

BEGIN

	Merge C_EmployeePerformanceRating as Target Using @EmployeePerformanceRating as Source on(Target.Month =Source.Month AND Target.Year =Source.Year AND
	Target.EmployeeId =Source.EmployeeId)	
	When Not Matched By Target then
		Insert(Month,Year,EmployeeId,SelfRating,AppraisalByUpperManager,ApprovedByGM,ReasonForRating,CreatedBy,CreatedDate)
		values(Source.Month,Source.Year,Source.EmployeeId,Source.SelfRating,Source.AppraisalByUpperManager,Source.ApprovedByGM,Source.ReasonForRating,
		Source.CreatedBy,Getdate())
	When Matched then
		Update Set Target.SelfRating = Source.SelfRating,
				   Target.AppraisalByUpperManager = Source.AppraisalByUpperManager,
				   Target.ApprovedByGM = Source.ApprovedByGM,
				   Target.ReasonForRating =Source.ReasonForRating,
				   Target.UpdatedBy = Source.UpdatedBy,
				   Target.UpdatedDate = GetDate();
	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,
			D_Roles.RoleName,
			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,
			IsNull(D_Roles.PreparationTime, 0) PreparationMins,
			IsNull(D_Roles.DePreparationTime, 0) DePreparationMins,
			ISNULL(C_EmployeeLeaveProfile.LeaveProfileHeaderId,0)LeaveProfileHeaderId
	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
			LEFT OUTER JOIN C_EmployeeLeaveProfile   WITH (NOLOCK) ON C_EmployeeLeaveProfile.EmployeeId = Employee.EmployeeId
			AND Convert(Date, C_EmployeeLeaveProfile.EndDate) > Convert(Date,GETDATE())
			AND Convert(Date, C_EmployeeLeaveProfile.StartDate) < Convert(Date,GETDATE())
	WHERE	(Employee.EmployeeId = @EmployeeID	 OR @EmployeeID	= 0)
	AND		(OrgUnit.OUId = @OUID OR @OUID = 0)
	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(500),
	@ProfilePhoto		nVarchar(max),
	@ScheduleRuleId     bigint,
	@PayGroupId         bigint,
	@OverTimeId			BigInt,
	@HourlyRate         decimal(18,4),
	@ContractedHours    decimal(18,4),
	@AlternatePhoto		nVarchar(max),
	@ProbationExpiry	DateTime,
	@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
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetAllEmployeeRating]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetAllEmployeeRating]
GO

CREATE PROCEDURE [dbo].[prC_GetAllEmployeeRating]    
(
	@RatingSkill		nVarchar(max),
	@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,
			IsNull(D_Roles.PreparationTime, 0) PreparationMins,
			IsNull(D_Roles.DePreparationTime, 0) DePreparationMins
			--ISNULL(C_EmployeeLeaveProfile.LeaveProfileHeaderId,0)LeaveProfileHeaderId
	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
			--LEFT OUTER JOIN C_EmployeeLeaveProfile   WITH (NOLOCK) ON C_EmployeeLeaveProfile.EmployeeId = Employee.EmployeeId
	WHERE	(OrgUnit.OUId = @OUID OR @OUID = 0)
	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

	SELECT C_Employee.EmployeeId,
		   C_EmployeeSkills.SkillRating,
		   D_Skill.Skill SkillName
	FROM   C_Employee WITH (NOLOCK) 
		   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
	WHERE  (D_Skill.Skill IN (SELECT * FROM fnStringToTable(@RatingSkill)))
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,IsNull(HourlyRate,0)) HourlyRate, 
			ScheduleRuleId, 
			Position,
			D_EmploymentBasis.EmploymentBasisCode
	FROM	C_Employee WITH (NOLOCK) 
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
	WHERE	EmployeeId = @EmployeeId	
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetEmployeeMessages')
	DROP PROCEDURE prC_GetEmployeeMessages
GO

CREATE PROC prC_GetEmployeeMessages
 (
	@EmployeeId  bigint
)
AS
Select C_EmployeeMessages.EmployeeId,
       C_Employee.EmployeeNumber,
	   C_Employee.DisplayName,
	   C_SecurityRole.SecurityRoleCode,
	   D_MessageSecurityRole.SecurityRoleId,
	   C_EmployeeMessages.MessageId,
	   C_EmployeeMessages.EnableEmails,
	   C_EmployeeMessages.EnableMessages,
	   C_EmployeeMessages.EnablePushNotifications,
	   D_Messages.MessageCode
FROM   C_Employee
        INNER JOIN C_EmployeeMessages  WITH (NOLOCK)  on C_EmployeeMessages.EmployeeId = C_Employee.EmployeeId
		INNER JOIN D_MessageSecurityRole  WITH (NOLOCK)  on D_MessageSecurityRole.MessageSecurityRoleId = C_EmployeeMessages.MessageSecurityRoleId
		INNER JOIN C_SecurityRole  WITH (NOLOCK)  on C_SecurityRole.SecurityRoleID =D_MessageSecurityRole.SecurityRoleId
		INNER JOIN D_Messages WITH (NOLOCK) on D_Messages.MessageId = C_EmployeeMessages.MessageId 
WHERE  C_EmployeeMessages.EmployeeId = @EmployeeId
	
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,
			TemplateId
	FROM	C_EmployeeMovement WITH (NOLOCK)
	WHERE	Convert(Date,StartDate) <= Convert(Date,@MovementDate)
	AND		C_EmployeeMovement.MovementStatus = 0
END
GO

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

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

CREATE PROC prC_GetEmployeePerformanceRating
	@OUId				BigInt,
	@Month				BigInt,
	@Year				BigInt
AS
BEGIN
-- Employee Details
	SELECT  C_Employee.EmployeeId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName,
			C_Employee.Position,
			C_Employee.HiredDate,
			C_OrganizationNode.OUName
	FROM	C_Employee WITH (NOLOCK)
			INNER JOIN C_OrganizationNode  WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
	WHERE	C_Employee.OUId = @OUId 

	-- Employee Performance Detail
	SELECT	[Month],
			[Year],
			C_EmployeePerformanceRating.EmployeeId,
			SelfRating,
			AppraisalByUpperManager,
			ApprovedByGM,
			IsNull(ReasonForRating,'')ReasonForRating
	FROM	C_EmployeePerformanceRating  WITH (NOLOCK)
			INNER JOIN  C_Employee WITH (NOLOCK) ON C_EmployeePerformanceRating.EmployeeID = C_Employee.EmployeeId
	WHERE	[Month] = @Month 
	AND		[Year]  = @Year
	AND		C_Employee.OUId = @OUId
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_GetInterfaceByInterfaceMasterId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetInterfaceByInterfaceMasterId]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_GetInterfaceByInterfaceMasterId]   
(
	@InterfaceMasterId	 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,				
				-- Added below columns for E10-324
				C_Interfaces.InterfaceMasterId,
				C_Interfaces.Remarks,
				C_Interfaces.IsGlobal,
				C_Interfaces.OUSpecific
	FROM		C_Interfaces WITH (NOLOCK)		 
	WHERE		InterfaceMasterId = @InterfaceMasterId 
	
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetInterfaceConfig]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetInterfaceConfig]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_GetInterfaceConfig]    
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)
	ORDER BY C_InterfaceConfig.InterfaceConfigId
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_GetInterfaceMaster]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_GetInterfaceMaster]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [dbo].[prC_GetInterfaceMaster]    
AS
BEGIN
	SELECT	C_InterfaceMaster.InterfaceMasterId,
			C_InterfaceMaster.Type,
			C_InterfaceMaster.Name,
			C_InterfaceMaster.ModuleName,
			C_InterfaceMaster.Method,
			C_InterfaceMaster.FileType,
			C_InterfaceMaster.SoftwareName,
			C_InterfaceMaster.FileFormat,
			C_InterfaceMaster.ActiveStatus,
			C_InterfaceMaster.CreatedBy,
			C_InterfaceMaster.CreatedDate
	FROM	C_InterfaceMaster WITH (NOLOCK)
	ORDER BY C_InterfaceMaster.InterfaceMasterId
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.*, IsNull(C_SecurityRolePermissions.PermissionTypeId, 3 ) PermissionTypeId
	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


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetMenuPermissionsByUserId')
	DROP PROCEDURE prC_GetMenuPermissionsByUserId
GO

CREATE PROC prC_GetMenuPermissionsByUserId
(	
	@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_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
			AND C_SecurityRole.IsActive = 1
	WHERE   C_UserSecurityRole.UserId = @UserId	
	AND	   (C_Menu.ParentMenuID = @ParentMenuId OR @ParentMenuId = 0)
	AND		C_SecurityRolePermissions.PermissionTypeId <> 0
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prC_GetMiscellaneousColumnAndValues')
	DROP PROC prC_GetMiscellaneousColumnAndValues
GO
/****** Object:  StoredProcedure [dbo].[prC_GetMiscellaneousColumnAndValues]    Script Date: 02/07/2018 12:30:37 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
CREATE PROC prC_GetMiscellaneousColumnAndValues(
@ModuleId int)
AS
BEGIN
	SELECT	MiscellaneousColumnId,
			ModuleId,
			LabelName,
			DataType,
			DefaultValue,
			IsMandatory,
			ActiveStatus, 
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	C_MiscellaneousColumns WITH (NOLOCK)
	WHERE   (ModuleId = @ModuleId OR @ModuleId=0)

	SELECT	ValueId,
			MiscellaneousColumnId,
			ColumnValue,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	C_MiscellaneousColumnsValues WITH (NOLOCK)

END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_GetNotificationsByEmployeeId') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_GetNotificationsByEmployeeId
GO
 
Create PROCEDURE prC_GetNotificationsByEmployeeId
(
	@EmployeeId			BigInt	= 0,
	@MessageStatusId	Int = 0,
	--@NotificationTypeId	Int = 0,
	@MaxRows			Int = 10
)
AS
BEGIN
	--TOP (@MaxRows)	
	SELECT 
			C_EmployeeNotifications.EmployeeNotificationId,
			C_EmployeeNotifications.EmployeeId,
			D_Messages.MessageId,
			C_EmployeeNotifications.WebAppHeader,
			C_EmployeeNotifications.WebAppMessage,
			C_EmployeeNotifications.MobileAppHeader,
			C_EmployeeNotifications.MobileAppMessage,
			C_EmployeeNotifications.MessageStatus,
			C_EmployeeNotifications.CreatedBy,
			C_EmployeeNotifications.CreatedDate,
			C_EmployeeNotifications.ViewedDate,
			C_EmployeeNotifications.ReadDate,
			C_EmployeeNotifications.HideDate,
			C_EmployeeNotifications.DeletedDate,
			C_EmployeeNotifications.ClickedDate DateClicked,
			C_EmployeeNotifications.LastStatusUpdatedDate,
			C_EmployeeNotifications.IsDeleted,
			C_EmployeeNotifications.DeletedBy,
			D_Messages.NavigationUrlWeb,
			D_Messages.NavigationUrlMobile,
			D_Messages.NotificationIcon,
			D_Messages.PushMessageIcon,
			C_EmployeeNotifications.IsWebNotification,
			C_EmployeeNotifications.IsMobileNotification,
			C_EmployeeNotifications.IsActionRequired
	FROM	C_EmployeeNotifications WITH (NOLOCK) 
			INNER JOIN D_Messages WITH (NOLOCK) ON C_EmployeeNotifications.MessageId = D_Messages.MessageId
	WHERE	C_EmployeeNotifications.EmployeeId = @EmployeeId
	AND		(C_EmployeeNotifications.MessageStatus = @MessageStatusId OR @MessageStatusId = 0)
	AND		C_EmployeeNotifications.IsDeleted = 0
	--AND		(C_EmployeeNotifications.NotificationTypeId = @NotificationTypeId OR @NotificationTypeId = 0)
	ORDER BY C_EmployeeNotifications.CreatedDate DESC
END
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 sys.objects WHERE object_id = OBJECT_ID(N'prC_GetScreenFunctionPermissionById') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_GetScreenFunctionPermissionById
GO
 
CREATE PROCEDURE prC_GetScreenFunctionPermissionById
(
	@UserId				BigInt = 0,
	@OUId				BigInt = 0,
	@MenuId				BigInt = 0,
	@PermissionTypeId	Int = 0
)
AS
BEGIN	 
	--SELECT	C_SecurityRoleMenuFunctionPermissions.SecurityRoleMenuFunctionPermissionId,
	--		C_SecurityRoleMenuFunctionPermissions.MenuFunctionId,
	--		C_SecurityRoleMenuFunctionPermissions.PermissionTypeId
	--FROM	C_SecurityRoleMenuFunctionPermissions WITH (NOLOCK) 
	--		INNER JOIN C_MenuFunctions WITH (NOLOCK) ON C_MenuFunctions.MenuFunctionId = C_SecurityRoleMenuFunctionPermissions.MenuFunctionId
	--WHERE	C_SecurityRoleMenuFunctionPermissions.SecurityRoleId = @SecurityRoleId
	--And		C_MenuFunctions.MenuId = @MenuId

	SELECT	C_SecurityRoleMenuFunctionPermissions.SecurityRoleMenuFunctionPermissionId,
			C_SecurityRoleMenuFunctionPermissions.MenuFunctionId,
			C_SecurityRoleMenuFunctionPermissions.PermissionTypeId
	FROM	C_UserSecurityRole WITH (NOLOCK) 
			INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_SecurityRole.SecurityRoleID = C_UserSecurityRole.SecurityRoleId
			INNER JOIN C_UserSecurityRoleOU WITH (NOLOCK) ON C_UserSecurityRole.UserSecurityRoleId = C_UserSecurityRoleOU.UserSecurityRoleId
			INNER JOIN C_SecurityRoleMenuFunctionPermissions WITH (NOLOCK) ON C_SecurityRoleMenuFunctionPermissions.SecurityRoleId = C_UserSecurityRole.SecurityRoleId
			INNER JOIN C_MenuFunctions WITH (NOLOCK) ON C_MenuFunctions.MenuFunctionId = C_SecurityRoleMenuFunctionPermissions.MenuFunctionId 
	WHERE	C_UserSecurityRole.UserId	= @UserId
	AND		C_UserSecurityRoleOU.OUId	= @OUId
	AND		C_MenuFunctions.MenuId		= @MenuId
	AND		C_SecurityRoleMenuFunctionPermissions.PermissionTypeId = @PermissionTypeId

END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_GetScreenFunctions') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_GetScreenFunctions
GO
 
CREATE PROCEDURE prC_GetScreenFunctions
AS
BEGIN	 
	SELECT	C_MenuFunctions.MenuFunctionId,
			C_MenuFunctions.MenuId,
			C_MenuFunctions.FunctionName,
			C_MenuFunctions.FunctionView,
			C_MenuFunctions.DisplayOrder,
			C_Menu.MenuName
	FROM	C_MenuFunctions WITH (NOLOCK) INNER JOIN C_Menu WITH (NOLOCK) ON C_Menu.MenuID = C_MenuFunctions.MenuId
END
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, Y.DisplayOrder
		FROM   C_Menu AS y WITH (NOLOCK)
		WHERE  y.ParentMenuID IS NULL
			AND y.IsHorizontalMenuItem = 1 And y.IsActive = 1
		UNION ALL
		SELECT ChildMenu.MenuID, ChildMenu.MenuName, ChildMenu.ParentMenuID, ChildMenu.MenuLink, ChildMenu.Sequence, ChildMenu.DisplayOrder
		FROM   MenuItems AS ParentMenu
		JOIN   C_Menu AS ChildMenu WITH (NOLOCK)
		ON ChildMenu.ParentMenuID = ParentMenu.MenuID
		AND ChildMenu.IsHorizontalMenuItem = 0 And ChildMenu.IsActive = 1
	)
	SELECT	MenuItems.*,--, LTRIM(RTRIM(Convert(NVarchar(3),ROW_NUMBER() OVER(PARTITION BY MenuItems.ParentMenuId ORDER BY MenuItems.ParentMenuId ASC)) + Convert(nVarchar(10),ParentMenuId))),
			IsNull(C_SecurityRolePermissions.PermissionTypeId,0) PermissionTypeId,
			IsNull(C_SecurityRolePermissions.SecurityRolePermissionId,0) SecurityRolePermissionId,
			IsNull(C_SecurityRolePermissions.SecurityRoleId, 0) SecurityRoleId
	FROM	MenuItems WITH (NOLOCK) LEFT OUTER JOIN C_SecurityRolePermissions WITH (NOLOCK) ON MenuItems.MenuID = C_SecurityRolePermissions.MenuId
	where	ParentMenuID IS NOT NULL 
	AND		C_SecurityRolePermissions.SecurityRoleId = @SecurityRoleId
	ORDER BY MenuItems.DisplayOrder

	SELECT	IsNull(C_SecurityRoleMenuFunctionPermissions.SecurityRoleMenuFunctionPermissionId,0) SecurityRoleMenuFunctionPermissionId,
			C_MenuFunctions.MenuFunctionId,
			IsNull(C_SecurityRoleMenuFunctionPermissions.SecurityRoleId, 0) SecurityRoleId,
			C_MenuFunctions.FunctionName,
			C_MenuFunctions.FunctionView,
			C_Menu.MenuID MenuId,
			C_Menu.MenuName MenuName,
			IsNull(C_SecurityRoleMenuFunctionPermissions.PermissionTypeId,0) PermissionTypeId,
			IsNull(C_SecurityRoleMenuFunctionPermissions.CreatedBy,'') CreatedBy,
			IsNull(C_SecurityRoleMenuFunctionPermissions.CreatedDate,GETDATE()) CreatedDate,
			C_SecurityRoleMenuFunctionPermissions.UpdatedBy,
			C_SecurityRoleMenuFunctionPermissions.UpdatedDate
	FROM	C_MenuFunctions WITH (NOLOCK)
			INNER JOIN C_Menu WITH (NOLOCK) ON C_MenuFunctions.MenuId = C_Menu.MenuID AND C_Menu.IsActive = 1 -- List Only Active Menu Items
			LEFT OUTER JOIN C_SecurityRoleMenuFunctionPermissions WITH (NOLOCK) ON C_MenuFunctions.MenuFunctionId = C_SecurityRoleMenuFunctionPermissions.MenuFunctionId
			AND C_SecurityRoleMenuFunctionPermissions.SecurityRoleId = @SecurityRoleId
END
GO
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_GetSecurityRoleMenuFunctionPermission') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_GetSecurityRoleMenuFunctionPermission
GO
 
CREATE PROCEDURE prC_GetSecurityRoleMenuFunctionPermission
(
	@SecurityRoleId	BigInt = 0
)
AS
BEGIN	 
	SELECT	IsNull(C_SecurityRoleMenuFunctionPermissions.SecurityRoleMenuFunctionPermissionId,0) SecurityRoleMenuFunctionPermissionId,
			C_MenuFunctions.MenuFunctionId,
			IsNull(C_SecurityRoleMenuFunctionPermissions.SecurityRoleId, 0) SecurityRoleId,
			C_MenuFunctions.FunctionName,
			C_MenuFunctions.FunctionView,
			C_Menu.MenuID MenuId,
			C_Menu.MenuName MenuName,
			IsNull(C_SecurityRoleMenuFunctionPermissions.PermissionTypeId,0) PermissionTypeId,
			IsNull(C_SecurityRoleMenuFunctionPermissions.CreatedBy,'') CreatedBy,
			IsNull(C_SecurityRoleMenuFunctionPermissions.CreatedDate,GETDATE()) CreatedDate,
			C_SecurityRoleMenuFunctionPermissions.UpdatedBy,
			C_SecurityRoleMenuFunctionPermissions.UpdatedDate
	FROM	C_MenuFunctions WITH (NOLOCK)
			INNER JOIN C_Menu WITH (NOLOCK) ON C_MenuFunctions.MenuId = C_Menu.MenuID
			LEFT OUTER JOIN C_SecurityRoleMenuFunctionPermissions WITH (NOLOCK) ON C_MenuFunctions.MenuFunctionId = C_SecurityRoleMenuFunctionPermissions.MenuFunctionId
			AND C_SecurityRoleMenuFunctionPermissions.SecurityRoleId = @SecurityRoleId
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, y.DisplayOrder, y.IsActive  
		 FROM   C_Menu AS y WITH(NOLOCK)
		 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, ChildMenu.DisplayOrder, ChildMenu.IsActive
		 FROM   MenuItems AS ParentMenu 
		 JOIN   C_Menu AS ChildMenu WITH(NOLOCK)
		 ON ChildMenu.ParentMenuID = ParentMenu.MenuID
			AND ChildMenu.IsHorizontalMenuItem = 0 AND ChildMenu.IsActive = 1)
	SELECT *
	FROM   MenuItems where ParentMenuID IS NOT NULL order by DisplayOrder;
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 sys.objects WHERE object_id = OBJECT_ID(N'prC_GetUserDeviceTokensByUserId') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_GetUserDeviceTokensByUserId
GO
 
Create PROCEDURE prC_GetUserDeviceTokensByUserId
(
	@UserId		BigInt = 0,
	@EmployeeId	BigInt = 0
)
AS
BEGIN
	SELECT	UserDeviceTokenId,
			UserId,
			EmployeeId,
			DeviceToken,
			DeviceName,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	C_UserDeviceTokens WITH (NOLOCK)
	WHERE	(C_UserDeviceTokens.UserId		= @UserId		OR @UserId = 0)
	AND		(C_UserDeviceTokens.EmployeeId	= @EmployeeId	OR @EmployeeId = 0)
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


	-- 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_InterfaceConfigDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceConfigDel]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_InterfaceConfigDel] 
(
	@InterfaceConfigId  bigint,
	@InterfaceId		BigInt
)
AS

BEGIN

	
	BEGIN
			Delete from C_InterfaceConfig where InterfaceConfigId=@InterfaceConfigId and InterfaceId=@InterfaceId
			select 1
	END
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceConfigIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceConfigIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_InterfaceConfigIns] 
(
	@InterfaceConfigId  bigint,
	@InterfaceId		BigInt,
	@ConfigType			nvarchar(510),	
	@ConfigValue		nvarchar(max),	
	@ActiveStatus		bit,
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN


	BEGIN
				insert into C_InterfaceConfig(InterfaceId,ConfigType,ConfigValue,
				ActiveStatus,CreatedBy,CreatedDate)
				values(@InterfaceId,@ConfigType,@ConfigValue,@ActiveStatus,@CreatedBy,GETDATE())
		SELECT @@IDENTITY
	END
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfaceConfigUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfaceConfigUpd]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_InterfaceConfigUpd] 
(
	@InterfaceConfigId  bigint,
	@InterfaceId		BigInt,
	@ConfigType			nvarchar(510),	
	@ConfigValue		nvarchar(max),	
	@ActiveStatus		bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	
	BEGIN
			Update C_InterfaceConfig set ConfigType =@ConfigType, ConfigValue=@ConfigValue,ActiveStatus=@ActiveStatus,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE()
			where InterfaceConfigId=@InterfaceConfigId and InterfaceId=@InterfaceId 
			select 1
	END
	
END
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_InterfacesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfacesDel]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prC_InterfacesDel] 
(
	@InterfaceId		BigInt,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
update C_Interfaces set ActiveStatus=0,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE()  WHERE InterfaceId=@InterfaceId
	SELECT 1
END 
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prC_InterfacesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prC_InterfacesIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prC_InterfacesIns] 
(
	@InterfaceId	BigInt,
	@Type			nvarchar(100),	
	@Name			nvarchar(1000),	
	@ModuleName		nvarchar(100),
	@Method			nvarchar(100),
	@FileType		nvarchar(100),
	@SoftwareName   nvarchar(1000),
	@FileNamePrefix nvarchar(100),
	@FileLocation	nVarchar(2000),
	@FileFormat		nVarchar(max),
	@ActiveStatus   bit,
	@InterfaceMasterId bigint,
	@Remarks		nvarchar(2000),
	@IsGlobal		bit,
	@OUSpecific		nvarchar(200),
	@CreatedBy		nVarchar(50),
	@OnErrorNotify  nVarChar(1000),
	@TemplateId     bigint
)
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
				insert into C_Interfaces(Type,Name,ModuleName,Method,FileType,SoftwareName,FileNamePrefix,
				FileLocation,FileFormat,ActiveStatus,CreatedBy,CreatedDate,InterfaceMasterId,Remarks,IsGlobal,OUSpecific,
				OnErrorNotify,TemplateId)
				values(@Type,@Name,@ModuleName,@Method,@FileType,@SoftwareName,@FileNamePrefix,
				@FileLocation,@FileFormat,@ActiveStatus,@CreatedBy,GETDATE(),@InterfaceMasterId,@Remarks,@IsGlobal,@OUSpecific,
				@OnErrorNotify,@TemplateId)
		SELECT @@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_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,				
				-- Added below columns for E10-324
				C_Interfaces.InterfaceMasterId,
				C_Interfaces.Remarks,
				C_Interfaces.IsGlobal,
				C_Interfaces.OUSpecific,
				C_Interfaces.OnErrorNotify,
				C_Interfaces.TemplateId
	    FROM	C_Interfaces WITH (NOLOCK)		 
	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),
	--Added for interface 2.0 E10-324
	@FileNamePrefix			nvarchar(100),
	@ActiveStatus			bit,
	@Remarks				nvarchar(2000),
	@IsGlobal				bit,
	@OUSpecific				nvarchar(200),
	@UpdatedBy				nVarchar(50),
	@OnErrorNotify          nVarchar(1000),
	@TemplateId             bigint
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN



	BEGIN
		UPDATE	C_Interfaces 
		SET		FileLocation	=	@FileLocation,	
				--Added for interface 2.0 E10-324
				FileNamePrefix	=	@FileNamePrefix,	
				ActiveStatus	=	@ActiveStatus,
				Remarks			=	@Remarks,
				IsGlobal		=	@IsGlobal,
				OUSpecific		=	@OUSpecific,
				OnErrorNotify   =   @OnErrorNotify,
				TemplateId      =   @TemplateId,
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	InterfaceId		=	@InterfaceId

		SELECT @InterfaceId
	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 WITH (NOLOCK) 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 WITH (NOLOCK)
						INNER JOIN C_UserSecurityRole WITH (NOLOCK)
								ON C_UserSecurityRole.UserSecurityRoleId = C_UserSecurityRoleOU.UserSecurityRoleId
						INNER JOIN C_User WITH (NOLOCK) 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_UpdateEmployeeMessage')
	DROP PROC prC_UpdateEmployeeMessage
GO

CREATE PROC prC_UpdateEmployeeMessage
	@MessageId		  BigInt,
	@EmailNotification	bit,	
	@MessageNotification bit, 
	@PushNotification	bit
AS

	UPDATE	C_EmployeeMessages
	SET		EnableMessages          = @MessageNotification,
	        EnableEmails            = @EmailNotification,
			EnablePushNotifications = @PushNotification
	WHERE	MessageId			    = @MessageId

	SELECT 1

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_UpdateEmployeeNotifications')
	DROP PROC prC_UpdateEmployeeNotifications
GO

CREATE PROCEDURE prC_UpdateEmployeeNotifications
(
	@EmployeeNotificationId	BigInt,
	@MessageStatus			Int,
	@ActionBy				nVarchar(50)
)
AS
BEGIN

	If (@MessageStatus = 2)
		UPDATE	C_EmployeeNotifications
		SET		ViewedDate				=	GETDATE(),
				MessageStatus			=	@MessageStatus,
				LastStatusUpdatedDate	=	GETDATE()
		WHERE	EmployeeNotificationId	=	@EmployeeNotificationId
	Else if (@MessageStatus = 3)
		UPDATE	C_EmployeeNotifications
		SET		DeletedDate				=	GETDATE(),
				IsDeleted				=	1,
				DeletedBy				=	@ActionBy,
				MessageStatus			=	@MessageStatus,
				LastStatusUpdatedDate	=	GETDATE()
		WHERE	EmployeeNotificationId	=	@EmployeeNotificationId
	Else If (@MessageStatus = 4)
		UPDATE	C_EmployeeNotifications
		SET		ClickedDate				=	GETDATE(),
				MessageStatus			=	@MessageStatus,
				LastStatusUpdatedDate	=	GETDATE()
		WHERE	EmployeeNotificationId	=	@EmployeeNotificationId
	Else
		SELECT 0;

	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_User SET IsActive = 0 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
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_UpdateSecurityRoleMenuFunctionPermission') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_UpdateSecurityRoleMenuFunctionPermission
GO
 
CREATE PROCEDURE prC_UpdateSecurityRoleMenuFunctionPermission
(
	@SecurityRoleMenuFunctionPermissionId	BigInt = 0,
	@PermissionTypeId						int	= 0,
	@UpdatedBy								nVarchar(50)
)
AS
BEGIN	 
	UPDATE	C_SecurityRoleMenuFunctionPermissions
	SET		PermissionTypeId						=	@PermissionTypeId,
			UpdatedBy								=	@UpdatedBy,
			UpdatedDate								=	GETDATE()
	WHERE	SecurityRoleMenuFunctionPermissionId	=	@SecurityRoleMenuFunctionPermissionId

	SELECT 1
END
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


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prC_UpdateUserDeviceToken') AND type in (N'P', N'PC'))
DROP PROCEDURE prC_UpdateUserDeviceToken
GO
 
Create PROCEDURE prC_UpdateUserDeviceToken
(
	@UserDeviceTokenId	BigInt,
	@DeviceToken		nVarchar(max),
	@ActiveStatus		Bit,
	@UpdatedBy			nVarchar(50)
)
AS
BEGIN
	UPDATE	C_UserDeviceTokens
	SET		DeviceToken			=	@DeviceToken,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	UserDeviceTokenId	=	@UserDeviceTokenId

	SELECT 1
END
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
	
	-- Insert Data Into A_UserPasswords Table Before Updating C_User Password Column
	--INSERT INTO A_UserPasswords
	--(UserId, PasswordHash, PasswordSalt, CreatedBy, CreatedDate)
	--SELECT @UserId, PasswordHash, PasswordSalt, @UpdatedBy, GETDATE() 
	--FROM	C_User WITH (NOLOCK)
	--WHERE	UserID	=	@UserId
	--AND		C_User.PasswordSalt != @PasswordSalt

	UPDATE	C_User 
	SET		PasswordHash			=	@PasswordHash,
			PasswordSalt			=	@PasswordSalt,
			ChangePasswordOnLogin	=	0,
			UpdatedBy				=	@UpdatedBy,
			UpdatedDate				=	GETDATE()
	WHERE	UserID					=	@UserId

	-- Insert Into Password Audit
	-- Insert Data Into A_UserPasswords Table Before Updating C_User Password Column
	INSERT INTO A_UserPasswords
	(UserId, PasswordHash, PasswordSalt, CreatedBy, CreatedDate)
	VALUES (@UserId, @PasswordHash, @PasswordSalt, @UpdatedBy, GETDATE())

	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 @UserSecurityRoleId

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, EmployeeID, LastLoginDate, ChangePasswordOnLogin,
		 ResetPassword, IsActive, CreatedBy, CreatedDate)
		VALUES
		(
			@UserName, @PasswordHash, @PasswordSalt, @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, @IsApprover Bit = 0
BEGIN

	SELECT	TOP 1 
			@OUId = IsNull(C_Permissions.OUId,0), 
			@OUName = IsNull(C_OrganizationNode.OUName,'')
	FROM	C_User WITH (NOLOCK)
	        INNER JOIN  C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
			INNER JOIN C_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = 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	@IsApprover = IIF(Count(*) > 0 , 1, 0) 
	FROM	W_WorkflowRouteDetails WITH (NOLOCK) 
			INNER JOIN C_User WITH (NOLOCK) ON C_User.EmployeeID = W_WorkflowRouteDetails.EmployeeId
	WHERE	C_User.UserName = @UserName

	;WITH UserPasswordHistory 
	AS (
		SELECT	TOP 1 
				A_UserPasswords.UserId, 
				A_UserPasswords.PasswordSalt, 
				A_UserPasswords.CreatedBy, 
				A_UserPasswords.CreatedDate
		FROM	A_UserPasswords WITH (NOLOCK) 
				INNER JOIN C_User WITH (NOLOCK) ON C_User.UserID = A_UserPasswords.UserId
		WHERE	LTRIM(RTRIM(C_User.UserName)) = LTRIM(RTRIM(@UserName))
		ORDER BY A_UserPasswords.CreatedDate DESC
	)
	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,
			@IsApprover IsApprover,
			C_Employee.EmailAddress LoginUserEmailAddress,
			IsNull(UserPasswordHistory.CreatedDate,GETDATE()) PasswordCreatedDate
	FROM	C_User WITH (NOLOCK) 
	        LEFT OUTER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
			LEFT OUTER JOIN C_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = 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
			LEFT OUTER JOIN UserPasswordHistory WITH (NOLOCK) ON C_User.UserID = UserPasswordHistory.UserId
	WHERE	(C_User.UserName = @UserName OR @UserName = '')
	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_UserSecurityRole.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_UserSecurityRole.UserSecurityRoleId,0) UserSecurityRoleId
	FROM	C_User WITH (NOLOCK) 
	        LEFT OUTER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
			LEFT OUTER JOIN C_SecurityRole WITH (NOLOCK) ON C_UserSecurityRole.SecurityRoleId = C_SecurityRole.SecurityRoleID
			LEFT OUTER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId			
	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 != '*')
		BEGIN
			-- Insert Into Password Audit
			-- Insert Data Into A_UserPasswords Table Before Updating C_User Password Column
			--INSERT INTO A_UserPasswords
			--(UserId, PasswordHash, PasswordSalt, CreatedBy, CreatedDate)
			--SELECT @UserId, PasswordHash, PasswordSalt, @UpdatedBy, GETDATE() 
			--FROM	C_User WITH (NOLOCK)
			--WHERE	UserID	=	@UserId
			--AND		C_User.PasswordSalt != @PasswordSalt

			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

			-- Insert Into Password Audit
			-- Insert Data Into A_UserPasswords Table Before Updating C_User Password Column
			--INSERT INTO A_UserPasswords
			--(UserId, PasswordHash, PasswordSalt, CreatedBy, CreatedDate)
			--VALUES (@UserId, @PasswordHash, @PasswordSalt, @UpdatedBy, GETDATE())
		END
		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 WITH (NOLOCK) LEFT OUTER JOIN C_UserRole WITH (NOLOCK) 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 sysobjects WHERE name = 'prDash_GetEmployeeLeaveProfileByEmployeeId')
	DROP PROC prDash_GetEmployeeLeaveProfileByEmployeeId
GO

CREATE PROCEDURE prDash_GetEmployeeLeaveProfileByEmployeeId
(
	@EmployeeId	BigInt = 0
)
AS
BEGIN
	DECLARE @FilterExceptionCodes nVarchar(1000) = ''

	SELECT  @FilterExceptionCodes = IsNull(ParamValue,'')
	FROM	D_SystemParams WITH (NOLOCK) 
	WHERE	D_SystemParams.ParamName = 'DisplayEmployeeLeaveCodes'

	-- Employee Leave Profile 
	SELECT	L_LeaveProfileHeader.ProfileName,
			C_EmployeeLeaveProfile.StartDate,
			C_EmployeeLeaveProfile.EndDate
	FROM	C_EmployeeLeaveProfile WITH (NOLOCK)
			INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) 
				ON C_EmployeeLeaveProfile.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId
	WHERE	EmployeeId	=	@EmployeeId
	AND		Convert(Date,C_EmployeeLeaveProfile.EndDate) >= Convert(Date,GETDATE())
	AND		Convert(Date,C_EmployeeLeaveProfile.StartDate) <= Convert(Date,GETDATE())


	-- Employee Leave Balance
	SELECT	D_ExceptionCodes.ExcpetionCodeName LeaveCode,
			D_ExceptionCodes.ExceptionCodeDesc LeaveDescription,
			L_EmployeeLeaveProfiles.EntitlementDays,
			L_EmployeeLeaveProfiles.CarryForwardDays,
			L_EmployeeLeaveProfiles.EarnedDays,
			L_EmployeeLeaveProfiles.AdjustDays,
			L_EmployeeLeaveProfiles.DaysUsed,
			L_EmployeeLeaveProfiles.BalanceDays
	FROM	L_EmployeeLeaveProfiles WITH (NOLOCK)
			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.LeaveProfileHeaderId
					AND L_LeaveProfiles.ActiveStatus = 1 AND L_LeaveProfiles.ExceptionCodeId = L_EmployeeLeaveProfiles.ExceptionId
	WHERE	EmployeeId	=	@EmployeeId
	AND		LeaveYear	=	Year(GETDATE())
	AND		D_ExceptionCodes.ExcpetionCodeName IN (SELECT * FROM fnStringToTable(@FilterExceptionCodes))

END
GO

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

CREATE PROCEDURE prDash_GetEmployeeProfileByEmployeeId
(
	@EmployeeId	BigInt = 0
)
AS
BEGIN
	SELECT	C_Employee.EmployeeId,
			C_Employee.EmployeeNumber,
			IsNull(C_Employee.FirstName,'') FirstName,
			IsNull(C_Employee.MiddleName,'') MiddleName,
			IsNull(C_Employee.LastName,'') LastName,
			IsNull(C_Employee.DisplayName,'') DisplayName,
			IsNull(C_Employee.BadgeNumber,'') BadgeNumber,
			C_Employee.DateOfBirth,
			Gender.CodeValue Gender,
			D_EmploymentBasis.EmploymentBasisCode,
			MatrialStatus.CodeValue MaritalStatus,
			C_Employee.Title,
			C_Employee.Position,
			Religion.CodeValue Religion,
			IsNull(C_Employee.Address1,'') Address1,
			IsNull(C_Employee.Address2,'') Address2,
			IsNull(C_Employee.Address3,'') Address3,
			IsNull(C_Employee.City,'') City,
			IsNull(C_Employee.State,'') State,
			IsNull(Country.CodeValue,'') Country,
			IsNull(C_Employee.MobilePhone,'') MobileNumber,
			IsNull(C_Employee.HomePhone,'') HomePhoneNumber,
			IsNull(C_Employee.EmailAddress,'') EmailAddress,
			C_OrganizationNode.OUName OrganizationUnit,
			S_RosterGroup.GroupName RosterGroupCode,
			C_Employee.HiredDate,
			C_Employee.DateOfBirth,
			C_Employee.TerminationDate,
			C_Employee.HourlyRate,
			C_Employee.ContractedHours,
			S_ScheduleRules.Description SchedulRuleDescription,
			D_PayGroup.PayGroupDesc PayGroupDescription,
			P_OvertimeSettings.OTName OvertimeName,
			S_PublicholidayEmployeeList.TypeDesc PublicHolidayType,
			D_RamadanPeriodEmployeeList.TypeDescription RamadanType
	FROM	C_Employee WITH (NOLOCK)
			LEFT OUTER JOIN D_MasterCodes MatrialStatus WITH (NOLOCK) ON MatrialStatus.CodeId = C_Employee.MaritalStatusId
			LEFT OUTER JOIN D_MasterCodes Gender WITH (NOLOCK) ON Gender.CodeId = C_Employee.GenderId
			LEFT OUTER JOIN D_MasterCodes Religion WITH (NOLOCK) ON Religion.CodeId = C_Employee.ReligionId
			LEFT OUTER JOIN D_MasterCodes Country WITH (NOLOCK) ON Country.CodeId = C_Employee.CountryId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
			INNER JOIN S_RosterGroup WITH (NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
			LEFT OUTER JOIN S_ScheduleRules WITH (NOLOCK) ON S_ScheduleRules.ScheduleRuleId = C_Employee.ScheduleRuleId
			LEFT OUTER JOIN D_PayGroup WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId
			LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OvertimeId
			LEFT OUTER JOIN S_PublicholidayEmployeeList WITH (NOLOCK) ON S_PublicholidayEmployeeList.EmployeeId = C_Employee.EmployeeId
			LEFT OUTER JOIN D_RamadanPeriodEmployeeList WITH (NOLOCK) ON D_RamadanPeriodEmployeeList.EmployeeId = C_Employee.EmployeeId
			LEFT OUTER JOIN D_RamadanPeriod WITH (NOLOCK) ON D_RamadanPeriod.RamadanPeriodId = D_RamadanPeriodEmployeeList.RamadanPeriodId 
				AND D_RamadanPeriod.RamadanYear = YEAR(GETDATE())
	WHERE	C_Employee.EmployeeId = @EmployeeId
END
GO

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

CREATE PROCEDURE prDash_GetEmployeeRolesSkillsByEmployeeId
(
	@EmployeeId	BigInt = 0
)
AS
BEGIN
	
	-- Retrieve Employee Roles
	SELECT	D_Roles.RoleName,
			C_EmployeeRoles.IsPrimaryRole
	FROM	C_EmployeeRoles WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
	WHERE	EmployeeId	=	@EmployeeId
	AND		D_Roles.ActiveStatus = 1

	-- Retrieve Employee SKills
	SELECT	D_Skill.Skill SkillName,
			C_EmployeeSkills.IsPrimary IsPrimarySkill,
			C_EmployeeSkills.IsActingSkill,
			C_EmployeeSkills.StartDate,
			C_EmployeeSkills.EndDate
	FROM	C_EmployeeSkills WITH (NOLOCK)
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId
	WHERE	EmployeeId	=	@EmployeeId
	AND		C_EmployeeSkills.ActiveStatus = 1 
	AND		D_Skill.ActiveStatus = 1
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 sysobjects WHERE name = 'prDash_GetLoginUserPendingApplicationsCount')
	DROP PROC prDash_GetLoginUserPendingApplicationsCount
GO

----------------------------------------------------------------------------
-- Retrieve List of Pending Applications From L_Leaves, L_TimeOff, L_RequestDaysInLieu
----------------------------------------------------------------------------
CREATE PROC prDash_GetLoginUserPendingApplicationsCount
(
	@EmployeeId		BigInt = 0
)
AS
BEGIN
	SELECT	Count(*) PendingCount, (SELECT ModuleName FROM  W_Modules  WHere W_Modules.ModuleId = 201) ModuleName
	FROM	L_Leaves WITH (NOLOCK)
	WHERE	L_Leaves.EmployeeId = @EmployeeId 
	AND		L_Leaves.ApprovalStatusId IN (3,6)
	UNION ALL
	SELECT	Count(*) PendingCount, (SELECT ModuleName FROM  W_Modules  WHere W_Modules.ModuleId = 202) ModuleName
	FROM	L_RequestDaysInLieu WITH (NOLOCK)
	WHERE	L_RequestDaysInLieu.EmployeeId = @EmployeeId 
	AND		L_RequestDaysInLieu.ApprovalStatusId IN (3,6)
	UNION ALL
	SELECT	Count(*) PendingCount, (SELECT ModuleName FROM  W_Modules  WHere W_Modules.ModuleId = 203) ModuleName
	FROM	L_TimeOff WITH (NOLOCK)
	WHERE	L_TimeOff.EmployeeId = @EmployeeId 
	AND		L_TimeOff.ApprovalStatusId IN (3,6)
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ActingIncentiveRatesDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ActingIncentiveRatesDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ActingIncentiveRatesDel]    
(
	@PositionId    bigInt
)
AS
BEGIN
	DELETE FROM P_ActingIncentiveRates WHERE PositionId=@PositionId
	 
	SELECT 1	 
END
go

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_ActingIncentiveRatesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ActingIncentiveRatesIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ActingIncentiveRatesIns]    
(
   @IncentiveRate   decimal(18,5),
   @PositionId      bigInt,
   @CreatedBy		nVarchar(50)
)
AS
BEGIN
   DECLARE @ValidateDuplicate int = 0

   SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	P_ActingIncentiveRates WITH (NOLOCK)
	WHERE   PositionId=@PositionId 

   If (@ValidateDuplicate = 0)
   BEGIN
   INSERT INTO P_ActingIncentiveRates
		(PositionId,IncentiveRate,CreatedBy, CreatedDate)
		VALUES(@PositionId, @IncentiveRate,@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_ActingIncentiveRatesUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_ActingIncentiveRatesUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_ActingIncentiveRatesUpd]    
(
	@IncentiveRate        decimal(18,5),
	@PositionId           bigint
)
AS
BEGIN
   UPDATE P_ActingIncentiveRates
   SET    IncentiveRate = @IncentiveRate
   WHERE  PositionId = @PositionId
		
   SELECT 1;
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 sysobjects WHERE name = 'prD_EquipmentBrandSel')
	DROP PROC prD_EquipmentBrandSel
GO
----------------------------------------------------------------------------
-- Select Records into M_EquipmentBrandNames
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_EquipmentBrandSel]    
(
	@BrandNameId		bigint,
	@OuId            bigint
)
AS
BEGIN
	SELECT	M_EquipmentBrandNames.BrandNameId,
			M_EquipmentBrandNames.EquipmentTypeId,
			M_EquipmentBrandNames.BrandName,
			M_EquipmentBrandNames.BrandDesc ,
			M_EquipmentBrandNames.OUID,	
		    M_EquipmentBrandNames.IsActive,
			M_EquipmentBrandNames.CreatedBy, 
			M_EquipmentBrandNames.CreatedDate,
			M_EquipmentBrandNames.UpdatedBy,
			M_EquipmentBrandNames.UpdatedDate
	FROM	M_EquipmentBrandNames	  WITH (NOLOCK) 	
	INNER JOIN C_OrganizationNode with (NOLOCK) ON M_EquipmentBrandNames.OUId = C_OrganizationNode.OUId			
	WHERE	(M_EquipmentBrandNames.BrandNameId = @BrandNameId OR @BrandNameId = 0)
	AND		(C_OrganizationNode.OUId = @OuId)
	ORDER BY M_EquipmentBrandNames.BrandName
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
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetAllActingIncentiveRates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_GetAllActingIncentiveRates]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prD_GetAllActingIncentiveRates]    
(
	@PositionId   bigInt
)
AS
BEGIN
	SELECT P_ActingIncentiveRates.ActingIncentiveId,
		   P_ActingIncentiveRates.PositionId,
		   P_ActingIncentiveRates.IncentiveRate IncentiveRates,
		   D_MasterCodes.CodeValue Positions
	FROM   P_ActingIncentiveRates WITH (NOLOCK)
		   INNER JOIN D_MasterCodes WITH (NOLOCK)  ON D_MasterCodes.CodeId = P_ActingIncentiveRates.PositionId
	WHERE  (P_ActingIncentiveRates.PositionId = @PositionId OR @PositionId = 0)
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'prD_GetAllPanelClinic') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_GetAllPanelClinic
GO
 
Create PROCEDURE prD_GetAllPanelClinic
(
	@PanelClinicId	Int,
	@OuId			BigInt
)
AS
BEGIN
	SELECT D_PanelClinics.PanelClinicId,
		   D_PanelClinics.PanelClinicName,
		   D_PanelClinics.Address,
		   D_PanelClinics.State,
		   D_PanelClinics.ContactPerson,
		   D_PanelClinics.Remarks,
		   D_PanelClinics.ActiveStatus,
		   D_PanelClinics.PostCode,
		   D_PanelClinics.City,
		   D_PanelClinics.PanelClinicCode
	FROM D_PanelClinics WITH (NOLOCK) 		   
	WHERE  D_PanelClinics.PanelClinicId = @PanelClinicId OR @PanelClinicId = 0
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,
				IsNull(A_Shifts.RBRRank,'') RBRRank,
				A_Shifts.ActionBy
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 sysobjects WHERE name = 'prD_GetCraneConditionTypeDetails')
	DROP PROC prD_GetCraneConditionTypeDetails
GO

-----------------------------------------------------------------------------------------
-- Get Records from S_THPEmployeeCraneConditionCounter Based on DateRange And ActionType
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_GetCraneConditionTypeDetails]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
		SELECT  S_THPEmployeeCraneConditionCounter.TransId,
				S_THPEmployeeCraneConditionCounter.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				S_THPEmployeeCraneConditionCounter.CraneConditionTypeId,
				S_THPEmployeeCraneConditionCounter.THPPeriodId,
				S_THPEmployeeCraneConditionCounter.StartDate,
				S_THPEmployeeCraneConditionCounter.EndDate,
				S_THPEmployeeCraneConditionCounter.Occurrence
		FROM	S_THPEmployeeCraneConditionCounter WITH (NOLOCK)
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_THPEmployeeCraneConditionCounter.EmployeeId
		WHERE   (S_THPEmployeeCraneConditionCounter.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,S_THPEmployeeCraneConditionCounter.StartDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_THPEmployeeCraneConditionCounter.EndDate) <= Convert(Date,@EndDate)
END
GO




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

----------------------------------------------------------------------------
-- Retrieve Data From A_Employees Table By Employee Id
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prD_GetEmployeeAudit] 
(
	@EmployeeId	    BigInt,
	@StartDate		DateTime = NULL,
	@EndDate		DateTime = NULL
)
AS
	If (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
	BEGIN
		SELECT  AuditId, ActionDate, ProcessName, EmployeeId, OUName, RosterGroupName, EmployeeNumber, BadgeNumber,
				FirstName, MiddleName, LastName, EmploymentBasis, IsTerminated, Position, Title, ScheduleRuleName ScheduleRule,
				PayGroupName PayGroup, OvertimeName OvertimeCode, HourlyRate, ContractedHours, UpdatedBy, UpdatedDate,
				RamadanPeriodType, PublicHolidayType, PrimaryRole, More, Roles, Skills, Disciplinary,
				Workflow, UserSecurityRoles, SharedOrganizationUnits, LeaveProfiles, Miscellaneous
		FROM	A_Employee WITH (NOLOCK)
		WHERE   (A_Employee.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,A_Employee.ActionDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,A_Employee.ActionDate) <= Convert(Date,@EndDate)
		ORDER BY    A_Employee.EmployeeNumber
	END
	ELSE
	BEGIN
		SELECT  AuditId, ActionDate, ProcessName, EmployeeId, OUName, RosterGroupName, EmployeeNumber, BadgeNumber,
				FirstName, MiddleName, LastName, EmploymentBasis, IsTerminated, Position, Title, ScheduleRuleName ScheduleRule,
				PayGroupName PayGroup, OvertimeName OvertimeCode, HourlyRate, ContractedHours, UpdatedBy, UpdatedDate,
				RamadanPeriodType, PublicHolidayType, PrimaryRole, More, Roles, Skills, Disciplinary,
				Workflow, UserSecurityRoles, SharedOrganizationUnits, LeaveProfiles, Miscellaneous
		FROM	A_Employee WITH (NOLOCK)
		WHERE   (A_Employee.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		ORDER BY    A_Employee.EmployeeNumber
	END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prD_GetEmployeeMessgaesByModuleId') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_GetEmployeeMessgaesByModuleId
GO
 
Create PROCEDURE prD_GetEmployeeMessgaesByModuleId
(
	@ModuleId	Int,
	@LanguageId Int,
	@EmployeeId	BigInt
)
AS
BEGIN
	SELECT	DISTINCT 
			--C_EmployeeMessages.EmployeeMessageId,
			--C_EmployeeMessages.MessageSecurityRoleId,
			C_EmployeeMessages.EmployeeId,
			C_EmployeeMessages.MessageId,
			C_EmployeeMessages.EnableMessages,
			C_EmployeeMessages.EnableEmails,
			C_EmployeeMessages.EnablePushNotifications,
			C_EmployeeMessages.IsMessagesDisabledByUser,
			C_EmployeeMessages.IsEmailDisabledByUser,
			C_EmployeeMessages.IsPushNotificationsDisabledByUser,
			C_EmployeeMessages.MessagesDisabledDate,
			C_EmployeeMessages.EmailDisabledDate,
			C_EmployeeMessages.PushNotificationsDisabledDate,
			C_EmployeeMessages.ActiveStatus --,
			--C_EmployeeMessages.CreatedBy,
			--C_EmployeeMessages.CreatedDate,
			--C_EmployeeMessages.UpdatedBy,
			--C_EmployeeMessages.UpdatedDate
	FROM	C_EmployeeMessages WITH (NOLOCK) 
			INNER JOIN D_Messages WITH (NOLOCK) ON C_EmployeeMessages.MessageId = D_Messages.MessageId		
	WHERE	D_Messages.MessageModuleId		=	@ModuleId
	AND		(C_EmployeeMessages.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)
	AND		(D_Messages.LanguageId			=	@LanguageId OR @LanguageId = 0)
END
GO


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

----------------------------------------------------------------------------
-- Get All Records from C_EmployeeNotifications
----------------------------------------------------------------------------
CREATE PROC prD_GetEmployeeNotifications
 (
	@EmployeeId	BigInt,
	@StartDate		DateTime = NULL,
	@EndDate		DateTime = NULL
)
AS
BEGIN
			SELECT   C_Employee.EmployeeId,
			         C_Employee.EmployeeNumber,
			         C_Employee.DisplayName,
					 C_EmployeeNotifications.WebAppHeader,
					 C_EmployeeNotifications.WebAppMessage,
					 C_EmployeeNotifications.MobileAppHeader,
					 C_EmployeeNotifications.MobileAppMessage,
			    CASE WHEN C_EmployeeNotifications.MessageStatus = 1 THEN 'New'
					 WHEN C_EmployeeNotifications.MessageStatus = 2 THEN 'Read'
					 WHEN C_EmployeeNotifications.MessageStatus = 3 THEN 'Deleted'
					 WHEN C_EmployeeNotifications.MessageStatus = 4 THEN 'Clicked'
					 END AS Status,
					 C_EmployeeNotifications.CreatedBy,
					 C_EmployeeNotifications.CreatedDate,
					 C_EmployeeNotifications.ViewedDate,
					 C_EmployeeNotifications.ReadDate,
					 C_EmployeeNotifications.HideDate,
					 C_EmployeeNotifications.DeletedDate,
					 C_EmployeeNotifications.ClickedDate,
					 C_EmployeeNotifications.LastStatusUpdatedDate,
					 C_EmployeeNotifications.IsDeleted,
					 C_EmployeeNotifications.DeletedBy,
					 C_EmployeeNotifications.IsWebNotification,
					 C_EmployeeNotifications.IsMobileNotification,
					 C_EmployeeNotifications.IsActionRequired
			 
			FROM       C_EmployeeNotifications  WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK)  on C_EmployeeNotifications.EmployeeId = C_Employee.EmployeeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK)  on C_Employee.OUId = C_OrganizationNode.OUId
			WHERE      (C_Employee.EmployeeId = @EmployeeId OR @EmployeeId =0)	
			AND		(Convert(Date,C_EmployeeNotifications.CreatedDate) >= Convert(Date,@StartDate)  OR @StartDate = @StartDate)
		    AND		(Convert(Date,C_EmployeeNotifications.CreatedDate) <= Convert(Date,@EndDate)	 OR @EndDate = @EndDate)
END	
GO

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

----------------------------------------------------------------------------
-- Get Records from MultipleTables Based on Exceptiontype
----------------------------------------------------------------------------

CREATE PROCEDURE prD_GetEmployeeUnavailabilityReport
(
    @ExceptionTypeId    BigInt,
	@RosterGroupId      nVarchar(100),
	@RoleGroupId		nVarchar(100),
	@EmployeeId         nVarchar(100),
	@ExceptionCodeId    nVarchar(100),
	@StartDate          DateTime,
	@EndDate            DateTime
)
AS
BEGIN
	
	If (@ExceptionTypeId  = 1 OR @ExceptionTypeId = 4 )  -- Attendance (OR) Exclude Deployment 
	BEGIN
	 With Cte as(
			SELECT  C_Employee.EmployeeId,
					C_Employee.EmployeeNumber,
					C_Employee.DisplayName EmployeeName,
					D_Roles.RoleName,
					D_ExceptionCodes.ExcpetionCodeName,
					S_ShiftExceptions.StartTime StartDate,
					S_ShiftExceptions.EndTime EndDate,
					S_ShiftExceptions.CreatedBy,
					S_ShiftExceptions.CreatedDate,
					ISNULL(S_ShiftExceptions.Remarks,'')Remarks
			FROM    S_ShiftExceptions WITH (NOLOCK)
					INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.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
					INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_ShiftExceptions.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
					INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
			WHERE   D_ExceptionType.ExceptionTypeId = @ExceptionTypeId 
			AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId = '0')
			AND     (D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId = '0')
			AND     (C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
			AND 	(D_ExceptionCodes.ExceptionCodeId IN (SELECT * FROM fnStringToTable(@ExceptionCodeId)) OR @ExceptionCodeId = '0')
			AND		Convert(Date,S_ShiftExceptions.StartTime) >= Convert(Date,@StartDate) 
			--AND		Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
			AND		Convert(Date,S_ShiftExceptions.StartTime) <= Convert(Date,@EndDate)
		UNION
				SELECT  C_Employee.EmployeeId,
                C_Employee.EmployeeNumber,
                C_Employee.DisplayName EmployeeName,
				D_Roles.RoleName,
				D_ExceptionCodes.ExcpetionCodeName,
				S_EmployeeLeaves.FromDate StartDate,
				S_EmployeeLeaves.EndDate EndDate,
				S_EmployeeLeaves.CreatedBy,
				S_EmployeeLeaves.CreatedDate,
				ISNULL(S_EmployeeLeaves.Remarks,'')
		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 D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
		WHERE   D_ExceptionType.ExceptionTypeId = @ExceptionTypeId 
		AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId = '0')
		AND     (D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId = '0')
		AND     (C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
		AND 	(D_ExceptionCodes.ExceptionCodeId IN (SELECT * FROM fnStringToTable(@ExceptionCodeId)) OR @ExceptionCodeId = '0')
		AND		Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@StartDate) 		
		AND		Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@EndDate)
		
		)

		SELECT * FROM CTE
	END
	Else If (@ExceptionTypeId = 2) -- Leave
	BEGIN
		SELECT  C_Employee.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_Roles.RoleName,
				D_ExceptionCodes.ExcpetionCodeName,
				S_EmployeeLeaves.FromDate StartDate,
				S_EmployeeLeaves.EndDate EndDate,
				S_EmployeeLeaves.CreatedBy,
				S_EmployeeLeaves.CreatedDate,
				L_Leaves.IsEmergency,
				ISNULL(L_Leaves.Remarks,'')Remarks
		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 D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
				LEFT OUTER JOIN L_Leaves WITH (NOLOCK) ON L_Leaves.EmployeeId = C_Employee.EmployeeId AND L_Leaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				           AND Convert(Date,L_Leaves.LeaveStart) >= Convert(Date,S_EmployeeLeaves.FromDate) AND Convert(Date,L_Leaves.LeaveStart) <= Convert(Date,S_EmployeeLeaves.EndDate) 
						   AND L_Leaves.ApprovalStatusId = 1
		WHERE   D_ExceptionType.ExceptionTypeId = @ExceptionTypeId 
		AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId = '0')
		AND     (D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId = '0')
		AND     (C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
		AND 	(D_ExceptionCodes.ExceptionCodeId IN (SELECT * FROM fnStringToTable(@ExceptionCodeId)) OR @ExceptionCodeId = '0')
		AND		Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@EndDate)
	END
	Else If (@ExceptionTypeId = 3) -- Uncontrolled Leave
	BEGIN
		SELECT  C_Employee.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_Roles.RoleName,
				D_ExceptionCodes.ExcpetionCodeName,
				L_UCL.UCLDate StartDate,
				L_UCL.UCLDate EndDate,
				L_UCL.CreatedBy,
				L_UCL.CreatedDate,
				ISNULL(L_UCL.Remarks,'')Remarks
		FROM    L_UCL WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_UCL.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_ExceptionCodes WITH (NOLOCK) ON L_UCL.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
		WHERE   D_ExceptionType.ExceptionTypeId = @ExceptionTypeId
		AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId = '0')
		AND     (D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId = '0')
		AND     (C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
		AND 	(D_ExceptionCodes.ExceptionCodeId IN (SELECT * FROM fnStringToTable(@ExceptionCodeId)) OR @ExceptionCodeId = '0')
		AND		Convert(Date,L_UCL.UCLDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)
	END		
END
GO

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

----------------------------------------------------------------------------
-- Get Records from D_ExceptionCodes Based on ExceptionType
---------------------------------------------------------------------------- 
Create PROCEDURE prD_GetExceptionCodesByExceptionType 
(
	@ExceptionTypeId	Bigint
)
AS
BEGIN
	SELECT	D_ExceptionCodes.ExceptionCodeId,
			D_ExceptionCodes.ExceptionTypeId,
			D_ExceptionCodes.ExcpetionCodeName,
			D_ExceptionCodes.ExceptionCodeDesc,
			D_ExceptionCodes.ActiveStatus,
			D_ExceptionCodes.CreatedBy, 
			D_ExceptionCodes.CreatedDate,
			D_ExceptionCodes.UpdatedBy,
			D_ExceptionCodes.UpdatedDate,
			D_ExceptionType.ExceptionTypeName
	FROM	D_ExceptionCodes	  WITH (NOLOCK) 
			INNER JOIN D_ExceptionType WITH (NOLOCK)  on D_ExceptionType.ExceptionTypeId =D_ExceptionCodes.ExceptionTypeId			
	WHERE	(D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId OR @ExceptionTypeId = 0)
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prD_GetFixedRankingSkills]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prD_GetFixedRankingSkills]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prD_GetFixedRankingSkills]    
AS
BEGIN
	SELECT	D_Roles.RoleId, 
			D_Roles.RoleName, 
			D_Skill.SkillId, 
			D_SKill.Skill SkillName, 
			D_Skill.FixedRanking 
	FROM	D_Roles WITH (NOLOCK) 
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Roles.PrimarySkillId = D_Skill.SkillID	
	WHERE	FixedRanking IS NOT NULL
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prD_GetMessages') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_GetMessages
GO
 
Create PROCEDURE prD_GetMessages
(
	@MessageId	BigInt,
	@LanguageId Int
)
AS
BEGIN
	SELECT	MessageId,
			MessageCode, 
			MessageName,
			MessageModuleId,
			MessageModuleName,
			LanguageId,
			EmailTemplateId,
			PushMessageHeader,
			PushMessageDetails,
			PushMessageIcon,
			NotificationHeader,
			NotificationDetails,
			NotificationIcon,
			NavigationUrlWeb,
			NavigationUrlMobile,
			ActiveStatus,
			IsEmail,
			IsMobileNotification,
			IsWebNotification,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_Messages WITH (NOLOCK)
	WHERE	(D_Messages.MessageId = @MessageId OR @MessageId = 0)
	AND		(D_Messages.LanguageId = @LanguageId OR @LanguageId = 0)
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prD_GetMessagesByModuleId') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_GetMessagesByModuleId
GO
 
Create PROCEDURE prD_GetMessagesByModuleId
(
	@ModuleId	Int,
	@LanguageId Int
)
AS
BEGIN
	SELECT	MessageId,
			MessageCode, 
			MessageName,
			MessageModuleId,
			MessageModuleName,
			LanguageId,
			EmailTemplateId,
			PushMessageHeader,
			PushMessageDetails,
			PushMessageIcon,
			NotificationHeader,
			NotificationDetails,
			NotificationIcon,
			NavigationUrlWeb,
			NavigationUrlMobile,
			ActiveStatus,
			IsEmail,
			IsMobileNotification,
			IsWebNotification,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	D_Messages WITH (NOLOCK)
	WHERE	D_Messages.MessageModuleId = @ModuleId
	AND		(D_Messages.LanguageId = @LanguageId OR @LanguageId = 0)
END
GO


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

CREATE PROCEDURE [dbo].[prD_GetOperationAudit]   
(	
	@StartDate		DateTime,
	@EndDate		DateTime,
	@Action         int,
	@ActionType     int
)
AS
BEGIN
		SELECT  *
		FROM	A_Operations WITH (NOLOCK)
		WHERE  	Convert(Date,A_Operations.ActionDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,A_Operations.ActionDate) <= Convert(Date,@EndDate)
		AND     (A_Operations.Action = @Action OR @Action = 0)
		AND     (A_Operations.ActionType = @ActionType OR @ActionType = 0)
END
GO






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

CREATE PROC prD_GetPanelClinicDetailByEmployeePanelClinic
	@EmployeeId	BigInt,
	@LeaveStart DateTime,
	@LeaveEnd   DateTime
AS
BEGIN
	SELECT D_PanelClinics.PanelClinicId,
		   D_PanelClinics.PanelClinicName,
		   D_PanelClinics.PanelClinicCode,
		   C_EmployeePanelClinics.EmployeeId		   	
    FROM   D_PanelClinics WITH (NOLOCK) 
		   INNER JOIN C_EmployeePanelClinics WITH (NOLOCK) ON  D_PanelClinics.PanelClinicId =  C_EmployeePanelClinics.PanelClinicId
	WHERE  C_EmployeePanelClinics.EmployeeId = @EmployeeId
	       AND C_EmployeePanelClinics.EffectiveFrom <= @LeaveEnd
		   AND C_EmployeePanelClinics.EffectiveTo   >= @LeaveStart
END
GO


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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC prD_GetPasswordPolicies
AS
BEGIN
	SELECT	PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate, UpdatedBy, UpdatedDate 
	FROM	D_PasswordPolicy WITH (NOLOCK)
END
GO

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

----------------------------------------------------------------------------
-- Insert a single record into D_PayCodeType
----------------------------------------------------------------------------
CREATE PROC prD_GetPayCodeType
 (
	@PaycodeTypeId  bigint
)
AS
	    
		SELECT   PaycodeTypeId,
				 PaycodeType,
				 Description,
				 ActiveStatus,
				 PaycodeTypeValue,
				 Case when PaycodeTypeValue = 1 then 'Hours'
				      when PaycodeTypeValue =  2 then 'Allowance'
				      end as PaycodeTypeValueName,	  
				      SkillName,
			      DefaultValue
			FROM  D_PayCodeType       
			WHERE (D_PayCodeType.PaycodeTypeId = @PaycodeTypeId OR @PaycodeTypeId =0)
			
GO	

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prD_GetPublicHolidayDetail')
	DROP PROCEDURE prD_GetPublicHolidayDetail
GO

CREATE PROC prD_GetPublicHolidayDetail
 (
	@StartDate			DateTime,
	@EndDate			DateTime
)
AS

-- Public Holiday Detail

SELECT		D_PublicHolidays.HolidayDate
FROM		D_PublicHolidays
WHERE		D_PublicHolidays.HolidayDate >= @StartDate
AND			D_PublicHolidays.HolidayDate <= @EndDate


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 sysobjects WHERE name = 'prD_GetTACostingAudit')
	DROP PROC prD_GetTACostingAudit
GO

----------------------------------------------------------------------------
-- Select a single record from prD_GetTACostingAudit
----------------------------------------------------------------------------

 
CREATE PROCEDURE [dbo].[prD_GetTACostingAudit]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@Action         nvarchar(100) = NULL
)
AS
BEGIN
	SELECT  A_ShiftCosts.AuditId,PayCodeDescription,StartTime,EndTime,S_Shifts.EmployeeId,ActualHour,
		    A_ShiftCosts.ApprovalStatus,ApprovedHours,A_ShiftCosts.CreatedBy,A_ShiftCosts.CreatedDate,A_ShiftCosts.UpdatedBy,
			A_ShiftCosts.UpdatedDate,A_ShiftCosts.Action,A_ShiftCosts.ActionBy,A_ShiftCosts.ActionDate,C_Employee.EmployeeNumber
	FROM	A_ShiftCosts WITH (NOLOCK)
		    INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = A_ShiftCosts.ShiftId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
	WHERE   (S_Shifts.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
	AND		Convert(Date,A_ShiftCosts.StartTime) >= Convert(Date,@StartDate) 
	AND		Convert(Date,A_ShiftCosts.EndTime) <= Convert(Date,@EndDate)
	AND     (A_ShiftCosts.Action = @Action OR @Action IS NULL)
END	
GO

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

----------------------------------------------------------------------------
-- Select a single record from prD_GetTARawClockingAudit
----------------------------------------------------------------------------

 
CREATE PROCEDURE [dbo].[prD_GetTARawClockingAudit]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@Action         nvarchar(100) = NULL
)
AS
BEGIN
		SELECT  AuditId,TypeId,CardNo,TerminalName,SwipeDateTime,EmployeeNumber,EmployeeId,CollectionDateTime,
		        Allocated,ReconDate,ReconBy,CreatedBy,CreatedDate,Action,ActionDate,ActionBy
		FROM	A_RawClocking WITH (NOLOCK)
		WHERE   (A_RawClocking.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,A_RawClocking.SwipeDateTime) >= Convert(Date,@StartDate) 
		AND		Convert(Date,A_RawClocking.SwipeDateTime) <= Convert(Date,@EndDate)
		AND     (A_RawClocking.Action = @Action OR @Action IS NULL)
END
GO






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

-----------------------------------------------------------------------------------------
-- Get Records from S_THPEmployeeDetails Based on DateRange And ActionType
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_GetTHPEmployeeDetails]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
		SELECT  S_THPEmployeeDetails.TranId,
				S_THPEmployeeDetails.THPPeriodId,
				S_THPEmployeePeriods.PeriodStart PeriodStartDate,
				S_THPEmployeePeriods.PeriodEnd PeriodEndDate,
				S_THPEmployeeDetails.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				S_THPEmployeeDetails.ShiftDate,
				S_THPEmployeeDetails.ShiftId,
				S_THPEmployeeDetails.LeaveId,
				S_THPEmployeeDetails.ShiftCounter,
				S_THPEmployeeDetails.ActivityCounter,
				S_THPEmployeeDetails.LeaveCounter,
				S_THPEmployeeDetails.NormalHour,
				S_THPEmployeeDetails.OTHour,
				S_THPEmployeeDetails.THPProcessDate,
				S_THPEmployeeDetails.THPNotes,
				S_THPEmployeeDetails.CreatedBy,
				S_THPEmployeeDetails.CreatedDate
		FROM	S_THPEmployeeDetails WITH (NOLOCK)
		INNER JOIN S_THPEmployeePeriods WITH (NOLOCK) ON S_THPEmployeePeriods.THPPeriodId = S_THPEmployeeDetails.THPPeriodId
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_THPEmployeeDetails.EmployeeId
		WHERE   (S_THPEmployeeDetails.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,S_THPEmployeeDetails.ShiftDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_THPEmployeeDetails.ShiftDate) <= Convert(Date,@EndDate)
END
GO



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

-----------------------------------------------------------------------------------------
-- Get Records from S_THPEmployeeEquipmentDetails Based on DateRange And ActionType
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_GetTHPEmployeeEquipmentDetails]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
		SELECT  S_THPEmployeeEquipmentDetails.TranId,
				S_THPEmployeeEquipmentDetails.THPPeriodId,
				S_THPEmployeePeriods.PeriodStart PeriodStartDate,
				S_THPEmployeePeriods.PeriodEnd PeriodEndDate,
				S_THPEmployeeEquipmentDetails.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				S_THPEmployeeEquipmentDetails.ShiftId,
				S_THPEmployeeEquipmentDetails.ShiftDate,
				S_THPEmployeeEquipmentDetails.EquipmentId,
				S_THPEmployeeEquipmentDetails.ActivityCounter,
				S_THPEmployeeEquipmentDetails.THPProcessDate,
				S_THPEmployeeEquipmentDetails.THPNotes,
				S_THPEmployeeEquipmentDetails.CreatedBy,
				S_THPEmployeeEquipmentDetails.CreatedDate
		FROM	S_THPEmployeeEquipmentDetails WITH (NOLOCK)
		INNER JOIN S_THPEmployeePeriods  WITH (NOLOCK) ON S_THPEmployeePeriods.THPPeriodId = S_THPEmployeeEquipmentDetails.THPPeriodId
		INNER JOIN C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_THPEmployeeEquipmentDetails.EmployeeId
		WHERE   (S_THPEmployeeEquipmentDetails.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,S_THPEmployeeEquipmentDetails.ShiftDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_THPEmployeeEquipmentDetails.ShiftDate) <= Convert(Date,@EndDate)
END
GO

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

-----------------------------------------------------------------------------------------
-- Get Records from S_THPEmployeeSkillDetails Based on DateRange And ActionType
-----------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_GetTHPEmployeeSkillDetails]   
(
	@EmployeeId	    BigInt = 0 ,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
		SELECT  S_THPEmployeeSkillDetails.TranId,
				S_THPEmployeeSkillDetails.THPPeriodId,
				S_THPEmployeePeriods.PeriodStart PeriodStartDate,
				S_THPEmployeePeriods.PeriodEnd PeriodEndDate,
				S_THPEmployeeSkillDetails.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				S_THPEmployeeSkillDetails.ShiftDate,
				S_THPEmployeeSkillDetails.ShiftId,
				S_THPEmployeeSkillDetails.SkillId,
				S_THPEmployeeSkillDetails.ActivityCounter,
				S_THPEmployeeSkillDetails.THPProcessDate,
				S_THPEmployeeSkillDetails.THPNotes,
				S_THPEmployeeSkillDetails.CreatedBy,
				S_THPEmployeeSkillDetails.CreatedDate
		FROM	S_THPEmployeeSkillDetails WITH (NOLOCK)
		INNER JOIN S_THPEmployeePeriods WITH (NOLOCK) ON S_THPEmployeePeriods.THPPeriodId = S_THPEmployeeSkillDetails.THPPeriodId
		INNER JOIN C_Employee WITH (NOLOCK)ON C_Employee.EmployeeId = S_THPEmployeeSkillDetails.EmployeeId
		WHERE   (S_THPEmployeeSkillDetails.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
		AND		Convert(Date,S_THPEmployeeSkillDetails.ShiftDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_THPEmployeeSkillDetails.ShiftDate) <= Convert(Date,@EndDate)
END
GO


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

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROC prD_GetUserPasswordHistory
(
	@UserId	BigInt
)
AS
BEGIN
	SELECT	PasswordAuditId, UserId, PasswordHash, PasswordSalt, CreatedBy, CreatedDate 
	FROM	A_UserPasswords WITH (NOLOCK)
	WHERE	UserId	=	@UserId
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,
	@Weightage      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,Weightage, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@CodeType, @CodeValue, @Sequence,@Weightage, @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)=NULL
)
AS
BEGIN
	SELECT	CodeId,
			CodeType,
			CodeValue,
			Seq,
			ActiveStatus, 
			CreatedBy, 
			CreatedDate,
			UpdatedBy,
			UpdatedDate,
			Weightage
	FROM	D_MasterCodes
	WHERE	(D_MasterCodes.CodeId = @ID OR @ID = 0)
	AND		(D_MasterCodes.CodeType = @CodeType or @CodeType IS NULL)
	ORDER BY D_MasterCodes.CodeType, CodeValue, Seq,Weightage
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,
	@Weightage      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, 
				Weightage      =   @Weightage,
				ActiveStatus	=	@IsActive, 
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
		WHERE	CodeId			=	@CodeID
		
		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

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


CREATE PROC prD_MessageDel
    @MessageId      bigint,
	@UpdatedBy		nVarchar(50)
AS
BEGIN
	UPDATE	D_Messages
	SET		ActiveStatus		=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GetDate()
	WHERE	MessageId			=	@MessageId

	SELECT 1
END
GO


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

CREATE PROCEDURE prD_MessageIns
(
  @MessageCode   nvarchar(50),
  @MessageName   nvarchar(500),
  @MessageModuleId int,
  @MessageModuleName nvarchar(500),
  @LanguageId int,
  @EmailTemplateId bigint,
  @PushMessageHeader nvarchar(max),
  @PushMessageDetails nvarchar(max),
  @PushMessageIcon nvarchar(max),
  @NotificationHeader nvarchar(max),
  @NotificationDetails nvarchar(max),
  @NotificationIcon nvarchar(max),
  @NavigationUrlWeb nvarchar(1000),
  @NavigationUrlMobile nvarchar(1000),
  @ActiveStatus bit,
  @IsEmail bit,
  @IsMobileNotification bit,
  @IsWebNotification bit,
  @CreatedBy nvarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
    SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_Messages WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(MessageModuleName))) = LTrim(RTrim(Upper(@MessageModuleName))) AND LanguageId = @LanguageId

	If (@ValidateDuplicate = 0)
	BEGIN
	Insert INTO D_Messages(
	MessageCode,
	MessageName,
	MessageModuleId,
	MessageModuleName,
	LanguageId,
	EmailTemplateId,
	PushMessageHeader,
	PushMessageDetails,
	PushMessageIcon,
	NotificationHeader,
	NotificationDetails,
	NotificationIcon,
	NavigationUrlWeb,
	NavigationUrlMobile,
	ActiveStatus,
	IsEmail,
	IsMobileNotification,
	IsWebNotification,
	CreatedBy,
	CreatedDate)
	VALUES(@MessageCode,@MessageName,@MessageModuleId,@MessageModuleName,@LanguageId,@EmailTemplateId,@PushMessageHeader,@PushMessageDetails,@PushMessageIcon,
	       @NotificationHeader,@NotificationDetails,@NotificationIcon,@NavigationUrlWeb,@NavigationUrlMobile,@ActiveStatus,@IsEmail,@IsMobileNotification,
		   @IsWebNotification,@CreatedBy,getdate())
	SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

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

CREATE PROC prD_MessageUpd
  @MessageId   bigint,
  @MessageCode   nvarchar(50),
  @MessageName   nvarchar(500),
  @MessageModuleId int,
  @MessageModuleName nvarchar(500),
  @LanguageId int,
  @EmailTemplateId bigint,
  @PushMessageHeader nvarchar(max),
  @PushMessageDetails nvarchar(max),
  @PushMessageIcon nvarchar(max),
  @NotificationHeader nvarchar(max),
  @NotificationDetails nvarchar(max),
  @NotificationIcon nvarchar(max),
  @NavigationUrlWeb nvarchar(1000),
  @NavigationUrlMobile nvarchar(1000),
  @ActiveStatus bit,
  @IsEmail bit,
  @IsMobileNotification bit,
  @IsWebNotification bit,
  @UpdatedBy nvarchar(50)
AS

BEGIN
	UPDATE	D_Messages
	SET     MessageCode = @MessageCode,
	        MessageName = @MessageName,
			MessageModuleId = @MessageModuleId,
			MessageModuleName = @MessageModuleName,
			LanguageId = @LanguageId,
			EmailTemplateId = @EmailTemplateId,
			PushMessageHeader = @PushMessageHeader,
			PushMessageDetails = @PushMessageDetails,
			PushMessageIcon = @PushMessageIcon,
			NotificationHeader = @NotificationHeader,
			NotificationDetails = @NotificationDetails,
			NotificationIcon = @NotificationIcon,
			NavigationUrlWeb = @NavigationUrlWeb,
			NavigationUrlMobile = @NavigationUrlMobile,
			ActiveStatus = @ActiveStatus,
			IsEmail = @IsEmail,
			IsMobileNotification = @IsMobileNotification,
			IsWebNotification = @IsWebNotification,
			UpdatedBy = @UpdatedBy,
			UpdatedDate = getdate()
	WHERE   MessageId = @MessageId

	Select 1
END

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


CREATE PROC prD_PanelClinicDel
   	@PanelClinicId  int,
	@UpdatedBy      nVarChar(50)
AS
BEGIN
	UPDATE	D_PanelClinics
	SET		ActiveStatus		=	0
	WHERE	PanelClinicId			=	@PanelClinicId

	SELECT 1
END
GO




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

CREATE PROCEDURE prD_PanelClinicIns
(
   @PanelClinicName  nvarchar(50),
   @Address  nvarchar(50),
   @State  nvarchar(50),
   @ContactPerson  nvarchar(50),
   @ContactNumber  nvarchar(50),
   @Remarks  nvarchar(50),
   @ActiveStatus bit
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
    SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PanelClinics WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PanelClinicName))) = LTrim(RTrim(Upper(@PanelClinicName)))

	If (@ValidateDuplicate = 0)
	BEGIN
	Insert INTO D_PanelClinics(
	PanelClinicName,
	Address,
	State,
	ContactPerson,
	ContactNumber,
	Remarks,
    ActiveStatus
	)
	VALUES(@PanelClinicName,@Address,@State,@ContactPerson,@ContactNumber,@Remarks,@ActiveStatus)
	SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO



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

CREATE PROC prD_PanelClinicUpd
  @PanelClinicId  int,
   @PanelClinicName  nvarchar(50),
   @Address  nvarchar(50),
   @State  nvarchar(50),
   @ContactPerson  nvarchar(50),
   @ContactNumber  nvarchar(50),
   @Remarks  nvarchar(50),
   @ActiveStatus bit
AS

BEGIN
	Update D_PanelClinics
	Set   PanelClinicName = @PanelClinicName,
	      Address         = @Address,
		  State           = @State,
		  ContactPerson   = @ContactPerson,
		  ContactNumber   = @ContactNumber,
		  Remarks         = @Remarks,
		  ActiveStatus    = @ActiveStatus
   Where  PanelClinicId   = @PanelClinicId

   Select 1
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prD_PasswordPolicySel') AND type in (N'P', N'PC'))
DROP PROCEDURE prD_PasswordPolicySel
GO
 
CREATE PROCEDURE prD_PasswordPolicySel
(
	@PolicyId	BigInt
)
AS
BEGIN
	SELECT	D_PasswordPolicy.PolicyId,
	        D_PasswordPolicy.PolicyDescription,
	        D_PasswordPolicy.PolicyValue,
			D_PasswordPolicy.ActiveStatus,
			D_PasswordPolicy.CreatedDate,
			D_PasswordPolicy.CreatedBy
	FROM	D_PasswordPolicy WITH (NOLOCK)
	WHERE	(D_PasswordPolicy.PolicyId = @PolicyId OR @PolicyId = 0)
END
GO




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

CREATE PROC prD_PasswordPolicyUpd
  @PolicyValue  int,
  @PolicyId   bigint  
AS

BEGIN
	UPDATE	D_PasswordPolicy
	SET     PolicyValue = @PolicyValue,	        
			UpdatedDate = getdate()
	WHERE   PolicyId = @PolicyId

	Select 1
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),
	--Add IsEditable Column in Screen   E10-308
	@IsEditable  Bit
)
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,IsEditable)
		VALUES(@PayCode, @PayCodeDesc, @Sequence, @IsActive, @CreatedBy, GETDATE(), @Multiplier,@IsEditable)

		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),
	--Add IsEditable Column in Screen   E10-308
	@IsEditable  Bit
)
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,
				IsEditable		=   @IsEditable
		WHERE	PayCodeId		=	@PayCodeId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END



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

----------------------------------------------------------------------------
-- Insert a single record into D_PayCodeType
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_PayCodeTypeUpd]    
(
	@PaycodeTypeId		BigInt,
	@PaycodeType		nVarchar(50),
	@PayCodeTypeDesc	nVarchar(500),	
	@PaycodeTypeValue int,
	@IsActive		Bit,
	@SkillName  nVarchar(500),
	@DefaultValue nVarchar(500),
	@UpdatedBy		nVarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	D_PayCodeType WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(PaycodeType))) = LTrim(RTrim(Upper(@PaycodeType)))
	AND		PaycodeTypeId	!=	@PaycodeTypeId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	D_PayCodeType
		SET		PaycodeType		=	@PaycodeType, 
				Description		=	@PayCodeTypeDesc,			
				ActiveStatus	=	@IsActive, 
				PaycodeTypeValue =  @PaycodeTypeValue,
				SkillName = ISNULL(@SkillName,null), 
				DefaultValue = ISNULL(@DefaultValue,null),
				UpdatedBy		=	@UpdatedBy,
				UpdatedDate		=	GETDATE()
				
		WHERE	PaycodeTypeId		=	@PaycodeTypeId

		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,
			D_PayCodes.seq Sequence
	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 OR @OUID = 0)
	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		Decimal(18,2),
	@NoOfEmployee		int,
	@NoOfActivity		int,
	@CreatedBy			nVarchar(50),
	@MinRestHours		Decimal(18,2)
)
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, MinRestHours)
		VALUES(@RuleId, @Seq,@Clause,@SkillId,@OperatingHour,@NoOfEmployee,@NoOfActivity,@CreatedBy, GETDATE(), @MinRestHours)

		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

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,
			D_ReliefRuleSkill.MinRestHours,
			D_Skill.FixedRanking SkillRanking
	FROM	D_ReliefRuleSkill	  WITH (NOLOCK) 
			left outer join D_Skill WITH (NOLOCK) 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		Decimal(18,2),
	@NoOfEmployee		int,
	@NoOfActivity		int,
	@UpdatedBy			nVarchar(50),
	@MinRestHours		Decimal(18,2)
)
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(),
				MinRestHours		=	@MinRestHours
		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,
	@RolePrioritySeq 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,RolePrioritySeq,ActiveStatus,CreatedBy, CreatedDate)
		VALUES(@RoleName, @RoleDesc, @PreparationTime, @DePreparationTime,@PrimarySkillId,@RolePrioritySeq,@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_Roles.RolePrioritySeq,
			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,
			D_RoleGroup.RoleGroupId
	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		
			INNER JOIN D_RoleOU WITH (NOLOCK) ON D_Roles.RoleId = D_RoleOU.RoleId 
			INNER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
		
	WHERE D_RoleOU.OUId = @OuId OR @OUID = 0
	--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,
	@RolePrioritySeq    int,
	@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,
				RolePrioritySeq     =   @RolePrioritySeq,
				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
	--Commented for Shift band name error E10-191
		--SELECT -1; 
		SELECT @ComboId; 
	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,
	@ShiftCounter       decimal(18,5),
	@ActiveStatus		bit,
	@CreatedBy			nvarchar(50)

)
AS
DECLARE @ValidateDuplicate int = 0
--Added for Validate Duplicate ShiftBand name E10-191
DECLARE @ValidateDuplicateShiftBandName 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)))
	-- Validate By ShiftBand name E10-191
	SELECT	@ValidateDuplicateShiftBandName =  COUNT(*)
	FROM	D_ShiftBand WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandName))) = LTrim(RTrim(Upper(@ShiftBandName)))
	--Comment & Validate By ShiftBand name E10-191
	--If (@ValidateDuplicate = 0)
	If (@ValidateDuplicate = 0 and @ValidateDuplicateShiftBandName=0)
	BEGIN
		INSERT INTO D_ShiftBand
		(ShiftBandName,
		 ShiftBandCode, 
		 ShiftBandDesc, 
		 ShiftTypeId, 
		 StartTime, 
		 StartRangeBegin,
		 StartRangeEnd,
		 EndTime,
		EndRangeBegin,
		EndRangeEnd,
		ColorCode,
		OvertimeType,
		OverttimeStart,
		OvertimeEnd,
		ShiftCounter,
		ActiveStatus,
		CreatedBy,
		CreatedDate)
 VALUES(@ShiftBandName, @ShiftBandCode, @ShiftBandDesc, @ShiftTypeId, @StartTime,@StartRangeBegin,@StartRangeEnd,@EndTime,
 @EndRangeBegin,@EndRangeEnd,@ColorCode,@OvertimeType,@OverttimeStart,@OvertimeEnd,@ShiftCounter,@ActiveStatus,@CreatedBy,getdate())

		SELECT SCOPE_IDENTITY();
	END
	-- Added & Comments for Define Error Code Message E10-191
	--Else
	--BEGIN
	--	SET @ValidateDuplicate = -1;
	--	SELECT @ValidateDuplicate;
	--END
	Else If (@ValidateDuplicateShiftBandName != 0)
		BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -2;
		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_ShiftBandOU.ShiftBandId,
			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  OR @ShiftBandId = 0)
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.ShiftCounter, 
				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,
	@ShiftCounter       decimal(18,5),
	@IsActive			Bit,
	@UpdatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
--Added for Validate Duplicate ShiftBand name E10-191
DECLARE @ValidateDuplicateShiftBandName 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

	-- Validate By ShiftBand name E10-191
	SELECT	@ValidateDuplicateShiftBandName =  COUNT(*)
	FROM	D_ShiftBand WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ShiftBandName))) = LTrim(RTrim(Upper(@ShiftBandName)))
	AND	ShiftBandId	!=	@ShiftBandId

	--Comment & Validate By ShiftBand name E10-191
	--If (@ValidateDuplicate = 0)
	If (@ValidateDuplicate = 0 and @ValidateDuplicateShiftBandName=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,
				ShiftCounter       =   @ShiftCounter,
				ActiveStatus		=	@IsActive, 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	ShiftBandId			=	@ShiftBandId
		
		SELECT 1;
	END
	-- Added & Comments for Define Error Code Message E10-191
	--Else
	--BEGIN
	--	SET @ValidateDuplicate = -1;
	--	SELECT @ValidateDuplicate;
	--END
	Else If (@ValidateDuplicateShiftBandName != 0)
		BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -2;
		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,
	@FixedRanking		nVarchar(100),
	@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,FixedRanking)
		VALUES(@SkillCode, @SkillDesc, @LicenceRequired, @Sequence, @ColourCode, @IsActive, @CreatedBy, GETDATE(),@FixedRanking)

		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,
			D_Skill.FixedRanking
	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,
	@FixedRanking		nVarchar(100),
	@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(),
				FixedRanking		=	@FixedRanking
		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_TemplateGroupSel')
	DROP PROC prD_TemplateGroupSel
GO
----------------------------------------------------------------------------
-- Get Records from E_EqipmentMatrixGroupTemplates Based on DateRange
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_TemplateGroupSel]    
(
	@TemplateGroupId		bigint,
	@OUID				BigInt
)
AS
BEGIN
	SELECT	E_EqipmentMatrixGroupTemplates.TemplateGroupId,
			E_EqipmentMatrixGroupTemplates.TemplateGroupName,
			E_EqipmentMatrixGroupTemplates.OUId,
			E_EqipmentMatrixGroupTemplates.TemplateGroupDesc ,		
		    E_EqipmentMatrixGroupTemplates.IsActive,
			E_EqipmentMatrixGroupTemplates.CreatedBy, 
			E_EqipmentMatrixGroupTemplates.CreatedDate,
			E_EqipmentMatrixGroupTemplates.UpdatedBy,
			E_EqipmentMatrixGroupTemplates.UpdatedDate
	FROM	E_EqipmentMatrixGroupTemplates	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON E_EqipmentMatrixGroupTemplates.OUId = C_OrganizationNode.OUId			
	WHERE	(E_EqipmentMatrixGroupTemplates.TemplateGroupId = @TemplateGroupId OR @TemplateGroupId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
	ORDER BY E_EqipmentMatrixGroupTemplates.TemplateGroupName
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),
	@DayStartTime           datetime,       
	@DayEndTime             datetime,
	@NightStartTime         datetime,
	@NightEndTime           datetime,
	@MaxOvrtimehrs     Decimal(18,2)
AS

UPDATE D_RamadanPeriod
SET		RamadanYear				=	@RamadanYear, 
		PeriodStart				=	@PeriodStart, 
		PeriodEnd				=	@PeriodEnd, 
		Description				=	@Description, 
		DailyOverTimeHours		=	@DailyOverTimeHours, 
		WeeklyOverTimeHours		=	@WeeklyOverTimeHours, 
		UpdatedBy				=	@UpdatedBy,
		UpdatedDate				=	GETDATE(),
		DayStartTime			=	@DayStartTime,
		DayEndTime				=	@DayEndTime,
		NightStartTime			=	@NightStartTime,
		NightEndTime			=	@NightEndTime,
		MaxDailyOvertimeHours	=	@MaxOvrtimehrs
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 sysobjects WHERE name = 'prD_WorkFlowModuleUpd')
	DROP PROC prD_WorkFlowModuleUpd
GO

----------------------------------------------------------------------------
-- Update Record from from W_Modules
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prD_WorkFlowModuleUpd]    
(
	@ModuleId	 bigInt, 
	@ModuleName		nVarchar(50),
	@LeaveCodes	nVarchar(500)

)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	W_Modules WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(ModuleName))) = LTrim(RTrim(Upper(@ModuleName)))
	AND		ModuleId	!=	@ModuleId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	W_Modules
		SET		LeaveCodes		=	@LeaveCodes		
		WHERE	ModuleId		=	@ModuleId

		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_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,
	@EquipmentTypeId 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,EquipmentTypeId,CreatedBy, CreatedDate)
		VALUES(@TemplateName, @OUId,@MatrixEQTypeId,@EquipmentTypeId,@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.EquipmentTypeId,

			CASE WHEN E_EquipmentMatrix.EquipmentTypeId = 0 THEN 'Crane'
			else M_EquipmentType.EquipmentType  
			end EquipmentTypeName ,
			E_EquipmentMatrix.CreatedBy, 
			E_EquipmentMatrix.CreatedDate,
			E_EquipmentMatrix.UpdatedBy,
			E_EquipmentMatrix.UpdatedDate
	FROM	E_EquipmentMatrix WITH (NOLOCK) 	
			LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON E_EquipmentMatrix.EquipmentTypeId = M_EquipmentType.EquipmentTypeId	 
			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,
	@EquipmentTypeId 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,
				EquipmentTypeId = @EquipmentTypeId,			 
				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,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	Update	E_EquipmentType_Matrix_Template
	SET		ActiveStatus	=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	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 = 'prE_GetEquipmentMatrixByTemplateGroupId')
	DROP PROC prE_GetEquipmentMatrixByTemplateGroupId
GO
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prE_GetEquipmentMatrixByTemplateGroupId]    
(
	@TemplateGroupId		bigint
)
AS
BEGIN
	SELECT	E_EqipmentMatrixGroupTemplates.TemplateGroupId,
			E_EqipmentMatrixGroupTemplates.TemplateGroupName,
			E_EqipmentMatrix_Schedule.MatrixId,
			E_EqipmentMatrix_Schedule.ScheduledValue,
			E_EquipmentMatrix_EquipmentType.EquipmentTypeId,
			E_EquipmentMatrix_EquipmentType.EquipmentTypeValue Requirement,
			E_EquipmentMatrix.EquipmentTypeId MatrixEquipmentTypeId,
			ISNULL(M_EquipmentType.EquipmentType,'QC') MatrixEquipmentType
	FROM	E_EqipmentMatrixGroupTemplates	  WITH (NOLOCK) 
			INNER JOIN E_EqipmentMatrixGroupTemplDet   WITH (NOLOCK) ON E_EqipmentMatrixGroupTemplates.TemplateGroupId = E_EqipmentMatrixGroupTemplDet.TemplateGroupId
			INNER JOIN E_EqipmentMatrix_Schedule WITH (NOLOCK) ON E_EqipmentMatrix_Schedule.MatrixId = E_EqipmentMatrixGroupTemplDet.MatrixId
			INNER JOIN E_EquipmentMatrix_EquipmentType  WITH (NOLOCK) ON E_EquipmentMatrix_EquipmentType.MatrixScheduleId = E_EqipmentMatrix_Schedule.MatrixScheduleId
			INNER JOIN E_EquipmentMatrix  WITH (NOLOCK) ON E_EquipmentMatrix.MatrixId = E_EquipmentMatrix_EquipmentType.MatrixId
			LEFT JOIN M_EquipmentType WITH (NOLOCK) ON  M_EquipmentType.EquipmentTypeId = E_EquipmentMatrix.EquipmentTypeId
	WHERE	E_EqipmentMatrixGroupTemplates.TemplateGroupId = @TemplateGroupId
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_EmployeeAbsentsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_EmployeeAbsentsIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_EmployeeAbsentsIns]    
(
	@StartDate			Date,
	@EndDate			Date,
	@ProcessBy			nVarchar(50)
)
AS
DECLARE @RunningSeq int = 1
BEGIN
--Source Table
	 With EmployeeAbsents as (
 		SELECT S_Shifts.EmployeeId,C_Employee.EmployeeNumber,TA_ExceptionCodes.TAException AttendanceCode,CONVERT(date,ShiftStartTime)ShiftDate 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 Convert(Date,ActualStartTime) >= @StartDate And  Convert(Date,ActualStartTime) <= @EndDate and S_Shifts.ReconStatusId =2
		union
		SELECT S_Shifts.EmployeeId,C_Employee.EmployeeNumber,TA_ExceptionCodes.TAException AttendanceCode,CONVERT(date,ShiftStartTime)ShiftDate 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 Convert(Date,S_Shifts.UpdatedDate) >= @StartDate And  Convert(Date,S_Shifts.UpdatedDate) <= @EndDate and S_Shifts.ReconStatusId =2 and
		(Convert(Date,ActualStartTime) between convert(datetime,@StartDate)-90 and convert(datetime,@StartDate)-1) )
--Insert Or Update		
		Merge IE_EmployeeAbsents as Target using EmployeeAbsents as Source on (Target.EmployeeId=Source.EmployeeId and Target.ShiftDate=Source.ShiftDate and
		Target.AttendanceCode=Source.AttendanceCode and Target.AsAtDate=@EndDate)
		When Not matched then
			Insert (EmployeeId,EmployeeNumber,AttendanceCode,ShiftDate,AsAtDate,ProcessDate,ProcessBy,RunningSeq,InterfaceFlag) values
			(Source.EmployeeId,Source.EmployeeNumber,Source.AttendanceCode,Source.ShiftDate,@EndDate,getdate(),@ProcessBy,@RunningSeq,0)
	   when matched then
	        Update set Target.EmployeeNumber=Source.EmployeeNumber,Target.ProcessDate=getdate(),ProcessBy=@ProcessBy,
			Target.RunningSeq=Target.RunningSeq+1;
	Select @RunningSeq
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_EmployeeOvertimeIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_EmployeeOvertimeIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_EmployeeOvertimeIns]    
(
	@StartDate			Date,
	@EndDate			Date,
	@ProcessBy			nVarchar(50)
)
AS
DECLARE @RunningSeq int = 1
BEGIN
  --Source Table
	With EmployeeOverTime as (
		SELECT S_Shifts.EmployeeId,C_Employee.EmployeeNumber,D_PayCodes.PayCode,'' HRMSPaycode,CONVERT(date,ShiftStartTime)ShiftDate,P_ShiftCosts.ApprovedHours OTHours
		FROM S_Shifts inner join C_Employee on C_Employee.EmployeeId=S_Shifts.EmployeeId inner join P_ShiftCosts on P_ShiftCosts.ShiftId=S_Shifts.ShiftId 
		inner join D_PayCodes on D_PayCodes.PayCodeId =P_ShiftCosts.PayCodeId
		Where  Convert(Date,ShiftStartTime) >= @StartDate And  Convert(Date,ShiftStartTime) <= @EndDate and D_PayCodes.IsEditable=1 and P_ShiftCosts.ApprovalStatus=1
		union 
		SELECT S_Shifts.EmployeeId,C_Employee.EmployeeNumber,D_PayCodes.PayCode,'' HRMSPaycode,CONVERT(date,ShiftStartTime)ShiftDate,P_ShiftCosts.ApprovedHours OTHours
		FROM S_Shifts inner join C_Employee on C_Employee.EmployeeId=S_Shifts.EmployeeId inner join P_ShiftCosts on P_ShiftCosts.ShiftId=S_Shifts.ShiftId 
		inner join D_PayCodes on D_PayCodes.PayCodeId =P_ShiftCosts.PayCodeId
		Where  Convert(Date,P_ShiftCosts.UpdatedDate) >= @StartDate And  Convert(Date,P_ShiftCosts.UpdatedDate) <= @EndDate and D_PayCodes.IsEditable=1 and
		S_Shifts.OTStartTime between (convert(datetime,@StartDate)-90) and (convert(datetime,@StartDate)-1) and P_ShiftCosts.ApprovalStatus=1
	)
 --Insert Or Update
	Merge IE_EmployeeOvertime as Target Using EmployeeOverTime as Source on(Target.EmployeeId=Source.EmployeeId and Target.PayCode=Source.PayCode and Target.ShiftDate=Source.ShiftDate
	and Target.AsAtDate=@EndDate)
	When not matched then
		Insert (EmployeeId,EmployeeNumber,PayCode,HRMSPaycode,ShiftDate,OTHours,AsAtDate,ProcessDate,ProcessBy,RunningSeq,InterfaceFlag) values
		(Source.EmployeeId,Source.EmployeeNumber,Source.PayCode,Source.HRMSPaycode,Source.ShiftDate,Source.OTHours,@EndDate,getdate(),@ProcessBy,@RunningSeq,0)
	When matched then
		Update Set Target.EmployeeNumber=Source.EmployeeNumber,Target.HRMSPaycode=Source.HRMSPaycode,Target.OTHours=Source.OTHours,Target.ProcessDate=getdate(),
		Target.ProcessBy=@ProcessBy,Target.RunningSeq=Target.RunningSeq+1;

	Select @RunningSeq

END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_EquipmentClockingIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_EquipmentClockingIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_EquipmentClockingIns]    
(
  @EquipmentClocking UIE_EquipmentClocking readonly,
  @InterfaceType int
)
AS
BEGIN
    IF @InterfaceType = 16
	BEGIN
    Merge IE_EquipmentClocking as Target Using @EquipmentClocking as Source on(Target.EmployeeNumber =Source.EmployeeNumber and Target.EquipmentName = Source.EquipmentName and Target.ClockingDateTime = Source.ClockingDateTime and Target.TypeId = Source.TypeId)	
	When Not Matched By Target Then
	Insert (EquipmentName,EmployeeNumber,EmployeeId,ClockingDateTime,TypeId,PickupPoint,Remarks,Source,CreatedBy,CreatedDate) 
	Values (Source.EquipmentName,Source.EmployeeNumber,Source.EmployeeId,Source.ClockingDateTime,Source.TypeId,Source.PickupPoint,Source.Remarks,Source.Source,Source.CreatedBy,getdate())
	When Matched Then
	Update Set Target.Remarks=Source.Remarks,
			   Target.Source =Source.Source,	   
	           Target.PickupPoint = Source.PickupPoint;
	select 1
	END
    ELSE	
	BEGIN
    Merge IE_EquipmentClocking as Target Using @EquipmentClocking as Source on(Target.EmployeeNumber =Source.EmployeeNumber and Target.EquipmentName = Source.EquipmentName and Target.ClockingDateTime = Source.ClockingDateTime)	
	When Not Matched By Target Then
	Insert (EquipmentName,EmployeeNumber,EmployeeId,ClockingDateTime,PickupPoint,Remarks,Source,CreatedBy,CreatedDate,ClockOutDateTime) 
	Values (Source.EquipmentName,Source.EmployeeNumber,Source.EmployeeId,Source.ClockingDateTime,Source.PickupPoint,Source.Remarks,Source.Source,Source.CreatedBy,getdate(),Source.ClockOutDateTime)
	When Matched Then
	Update Set Target.ClockOutDateTime = Source.ClockOutDateTime,
	           Target.Remarks=Source.Remarks,
			   Target.Source =Source.Source,	   
	           Target.PickupPoint = Source.PickupPoint;
	select 1
	END
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetClientDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetClientDetails]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetClientDetails]    
(
	@ClientName		nVarchar(100),
	@ClientId		nVarchar(500)
)
AS

BEGIN
	SELECT	ClientKeyId, ClientId, ClientSecret, ClientName, CreatedBy, CreatedDate
	FROM	IE_ClientMaster WITH (NOLOCK) 
	WHERE	LTRIM(RTRIM(ClientName)) = LTRIM(RTRIM(@ClientName))
	AND		LTRIM(RTRIM(ClientId)) = LTRIM(RTRIM(@ClientId))
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetEmployeeAbsents]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetEmployeeAbsents]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetEmployeeAbsents]    
(
	@StartDate			Date,
	@EndDate			Date,
	@EmployeeId			bigint
)
AS

BEGIN
	Select IE_EmployeeAbsents.LeaveBalanceId, IE_EmployeeAbsents.EmployeeId,IE_EmployeeAbsents.EmployeeNumber,IE_EmployeeAbsents.AttendanceCode,IE_EmployeeAbsents.ShiftDate,
	IE_EmployeeAbsents.AsAtDate,IE_EmployeeAbsents.ProcessDate,IE_EmployeeAbsents.ProcessBy
	 from IE_EmployeeAbsents where IE_EmployeeAbsents.AsAtDate>=@StartDate and IE_EmployeeAbsents.AsAtDate<=@EndDate and 
	 (IE_EmployeeAbsents.EmployeeId =@EmployeeId or @EmployeeId=0)
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetEmployeeAbsentsBetweenDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetEmployeeAbsentsBetweenDates]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetEmployeeAbsentsBetweenDates]    
(
	@StartDate			Date,
	@EndDate			Date
)
AS

BEGIN
	SELECT	EmployeeNumber, Replace(Convert(nvarchar,ShiftDate,106),' ','-') ShiftDate, AttendanceCode, TransRefId
	FROM	IE_EmployeeAbsents WITH (NOLOCK) 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetEmployeeOvertime]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetEmployeeOvertime]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetEmployeeOvertime]    
(
	@StartDate			Date,
	@EndDate			Date,
	@EmployeeId			bigint
)
AS

BEGIN
	Select IE_EmployeeOvertime.LeaveBalanceId, IE_EmployeeOvertime.EmployeeId,IE_EmployeeOvertime.EmployeeNumber,IE_EmployeeOvertime.Paycode,IE_EmployeeOvertime.HRMSPaycode,
	IE_EmployeeOvertime.ShiftDate,IE_EmployeeOvertime.OTHours,(RIGHT('0'+CONVERT(VARCHAR,CONVERT(INT,IE_EmployeeOvertime.OTHours)/60),2)+':'+ 
	RIGHT('0'+CONVERT(VARCHAR,CONVERT(INT,IE_EmployeeOvertime.OTHours)%60),2)) OTHourMin,
	IE_EmployeeOvertime.AsAtDate,IE_EmployeeOvertime.ProcessDate,IE_EmployeeOvertime.ProcessBy
	 from IE_EmployeeOvertime where IE_EmployeeOvertime.AsAtDate>=@StartDate and IE_EmployeeOvertime.AsAtDate<=@EndDate and 
	 (IE_EmployeeOvertime.EmployeeId =@EmployeeId or @EmployeeId=0)
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetEmployeeOvertimeBetweenDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetEmployeeOvertimeBetweenDates]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetEmployeeOvertimeBetweenDates]    
(
	@StartDate			Date,
	@EndDate			Date
)
AS

BEGIN
	SELECT	EmployeeNumber, Paycode, SUM(OTHours) OverTimeMinutes, Convert(nVarchar(500),NEWID()) TransRefId
	FROM	IE_EmployeeOvertime WITH (NOLOCK) 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	GROUP BY EmployeeNumber, Paycode
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetLeaveBalance]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetLeaveBalance]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetLeaveBalance]    
(
	@StartDate			Date,
	@EndDate			Date,
	@EmployeeId			bigint
)
AS

BEGIN
	Select IE_LeaveBalance.LeaveBalanceId,IE_LeaveBalance.EmployeeId,IE_LeaveBalance.EmployeeNumber,IE_LeaveBalance.LeaveCode,IE_LeaveBalance.LeaveBalance,
	IE_LeaveBalance.LeaveBalance,IE_LeaveBalance.AsAtDate,IE_LeaveBalance.ProcessDate,IE_LeaveBalance.ProcessBy
	 from IE_LeaveBalance where IE_LeaveBalance.AsAtDate>=@StartDate and IE_LeaveBalance.AsAtDate<=@EndDate and 
	 (IE_LeaveBalance.EmployeeId =@EmployeeId or @EmployeeId=0)
	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetLeaveBalanceAsAtDate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetLeaveBalanceAsAtDate]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetLeaveBalanceAsAtDate]    
(
	@AsAtDate	Date
)
AS

BEGIN
	SELECT	EmployeeNumber, LeaveBalance, TransRefId
	FROM	IE_LeaveBalance WITH (NOLOCK) 
	WHERE	Convert(Date,AsAtDate) = Convert(Date,@AsAtDate)
	AND		LeaveBalance != 0
	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetLeaveTransactions]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetLeaveTransactions]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetLeaveTransactions]    
(
	@StartDate			Date,
	@EndDate			Date,
	@TranType			int,
	@EmployeeId			bigint
)
AS

BEGIN
	Select IE_LeaveTransactions.LeaveBalanceId,IE_LeaveTransactions.EmployeeId,IE_LeaveTransactions.EmployeeNumber,IE_LeaveTransactions.LeaveCode,IE_LeaveTransactions.LeaveDate,
	IE_LeaveTransactions.AppliedDate,IE_LeaveTransactions.ApprovedDate,IE_LeaveTransactions.ApprovedBy,
	IE_LeaveTransactions.ApprovalStatus,IE_LeaveTransactions.AsAtDate,
	IE_LeaveTransactions.ProcessDate,IE_LeaveTransactions.ProcessBy
	 from IE_LeaveTransactions where IE_LeaveTransactions.AsAtDate>=@StartDate and IE_LeaveTransactions.AsAtDate<=@EndDate and
	(IE_LeaveTransactions.EmployeeId =@EmployeeId or @EmployeeId=0) and
	IE_LeaveTransactions.LeaveCode =(case when @TranType=2 then 'SL' when @TranType=4 then 'UL' else '' End)
	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_GetLeaveTransBetweenDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_GetLeaveTransBetweenDates]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_GetLeaveTransBetweenDates]    
(
	@StartDate		Date,
	@EndDate		Date,
	@ApprovalStatus	nVarchar(100)
)
AS

BEGIN
	SELECT	EmployeeNumber, LeaveCode, Replace(Convert(nvarchar,LeaveDate,106),' ','-') LeaveDate, 
			IE_LeaveTransactions.LeaveBalanceId, TransRefId
	FROM	IE_LeaveTransactions WITH (NOLOCK) 
	WHERE	Convert(Date,LeaveDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,LeaveDate) <= Convert(Date,@EndDate)
	AND		ApprovalStatus LIKE (@ApprovalStatus + '%')
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_LeaveBalanceIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_LeaveBalanceIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_LeaveBalanceIns]    
(
	@AsAtDate			Date,
	@ProcessBy			nVarchar(50)
)
AS
DECLARE @RunningSeq int = 1
BEGIN
--source Table
 		with AnnualLeaveBalance as(
		Select * from V_AnnualLeavebalance with (NoLock) )
			  
--Insert or Update
      Merge IE_LeaveBalance as Target using  AnnualLeaveBalance as Source on(Target.EmployeeId =Source.EmployeeId and Target.AsAtDate =@AsAtDate)
	  when not matched then
	  insert (EmployeeId,EmployeeNumber,LeaveCode,LeaveBalance,AsAtDate,ProcessDate,ProcessBy,RunningSeq,InterfaceFlag) 
	  values(Source.EmployeeId,Source.EmployeeNumber,Source.LeaveCode,Source.LeaveBalance,@AsAtDate,GETDATE(),@ProcessBy,@RunningSeq,0)
	  when matched then
	  Update set Target.LeaveCode=Source.LeaveCode,Target.LeaveBalance=Source.LeaveBalance,Target.ProcessDate=getdate(),
	  Target.ProcessBy=@ProcessBy,Target.RunningSeq=Target.RunningSeq+1;

	  select 1
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_LeaveTransactionsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_LeaveTransactionsIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_LeaveTransactionsIns]    
(
	@LeaveTransactions UT_LeaveTransactions readonly	
)
AS
DECLARE @RunningSeq int = 1

BEGIN
 
	--Insert Or Update
	Merge IE_LeaveTransactions as Target Using @LeaveTransactions as Source on(Target.EmployeeId =Source.EmployeeId and 
		Target.LeaveCode=Source.LeaveCode and Target.LeaveDate=Source.LeaveDate and Target.AsAtDate=Source.AsAtDate)
	When Not Matched then
	Insert (EmployeeId,EmployeeNumber,LeaveCode,LeaveDate,AppliedDate,ApprovedDate,ApprovedBy,ApprovalStatus,AsAtDate,ProcessDate,
	ProcessBy,RunningSeq,InterfaceFlag) values(
	Source.EmployeeId,Source.EmployeeNumber,Source.LeaveCode,Source.LeaveDate,Source.AppliedDate,Source.ApprovedDate,Source.ApprovedBy,
	Source.ApprovalStatus,Source.AsAtDate,Source.ProcessDate,Source.ProcessBy,@RunningSeq,0)
	when Matched then
	Update Set Target.EmployeeNumber=Source.EmployeeNumber,Target.LeaveDate=Source.LeaveDate,Target.AppliedDate=Source.AppliedDate,
	Target.ApprovedDate=Source.ApprovedDate,Target.ApprovalStatus=Source.ApprovalStatus,Target.ProcessDate=Source.ProcessDate,
	Target.ProcessBy=Source.ProcessBy, Target.RunningSeq=RunningSeq+1;

	
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_PoS_InterfacesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_PoS_InterfacesIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_PoS_InterfacesIns]    
(
	@StartDate			DateTime,
	@EndDate			DateTime,
	@InterfaceList		nVarchar(max),
	@InterfaceStatus	nVarchar(max),
	@ActionBy			nVarchar(50)
)
AS
DECLARE @HistoryStartDate DateTime,@HistoryEndDate DateTime,@HistoryStartFrom int
BEGIN
  select @HistoryStartFrom=(ParamValue) from D_SystemParams where ParamName='HistoryStartFrom'
  set @HistoryStartDate=Dateadd(DAY,@HistoryStartFrom,@StartDate)
  set @HistoryEndDate=@StartDate-1
 
  insert into IE_PoS_Interfaces(ActionDate,ActionBy,StartDate,EndDate,InterfaceList,HistoryStartDate,HistoryEndDate,InterfaceStatus)
  values(GETDATE(),@ActionBy,@StartDate,@EndDate,@InterfaceList,@HistoryStartDate,@HistoryEndDate,@InterfaceStatus)
  
  select 1;
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prIE_UpdateExportedRecord]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prIE_UpdateExportedRecord]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prIE_UpdateExportedRecord]    
(
	@TransRefId			nVarchar(500),
	@ExportModule		Int,
	@ExportedBy			nVarchar(100) = 'ADRENALINE'
)
AS

BEGIN
	IF (@ExportModule = 1) -- Annual Leave Balance Records
	BEGIN
		UPDATE	IE_LeaveBalance 
		SET		InterfaceFlag = 1, ExportedDate = GETDATE(), ExportedBy = @ExportedBy
		WHERE	TransRefId	=	@TransRefId

		SELECT 1
	END
	ELSE IF (@ExportModule = 2)
	BEGIN
		UPDATE	IE_LeaveTransactions
		SET		InterfaceFlag = 1, ExportedDate = GETDATE(), ExportedBy = @ExportedBy
		WHERE	TransRefId	=	@TransRefId

		SELECT 1
	END
	ELSE IF (@ExportModule = 3)
	BEGIN
		UPDATE	IE_LeaveTransactions
		SET		InterfaceFlag = 1, ExportedDate = GETDATE(), ExportedBy = @ExportedBy
		WHERE	TransRefId	=	@TransRefId

		SELECT 1
	END
	ELSE IF (@ExportModule = 4)
	BEGIN
		UPDATE	IE_EmployeeAbsents
		SET		InterfaceFlag = 1, ExportedDate = GETDATE(), ExportedBy = @ExportedBy
		WHERE	TransRefId	=	@TransRefId
		
		SELECT 1
	END
	ELSE IF (@ExportModule = 5)
	BEGIN
		UPDATE	IE_EmployeeOvertime
		SET		InterfaceFlag = 1, ExportedDate = GETDATE(), ExportedBy = @ExportedBy
		WHERE	TransRefId	=	@TransRefId

		SELECT 1
	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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_ActivityEquipmentNotesUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_ActivityEquipmentNotesUpdate]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prJ_ActivityEquipmentNotesUpdate]    
(
   @ActivityEqupimentNotes UTJ_ActivityEquipmentNotesUpdate readonly	
)
AS
BEGIN

	Merge J_Activity as Target Using @ActivityEqupimentNotes as Source on(Target.ActivityId = Source.ActivityId)	
	When Matched Then
	Update Set Target.EquipmentNotes	=	Source.EquipmentNotes,
			   Target.UpdatedBy			=	Source.UpdatedBy,
			   Target.UpdatedDate		=	GETDATE();
	select 1
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_ActivityLocationUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_ActivityLocationUpdate]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prJ_ActivityLocationUpdate]    
(
   @ActivityLocations UTJ_ActivityLocationUpdate readonly	
)
AS
BEGIN

	Merge J_Activity as Target Using @ActivityLocations as Source on(Target.ActivityId = Source.ActivityId)	
	When Matched Then
	Update Set Target.LocationId	=	Source.LocationId;

	select 1
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 BigInt = NULL,
	@CreatedBy nvarchar(100) = NULL,
	@ProgressionState Int = 0,
	@WorkloadId			BigInt = 0,
	@RBRRank			nChar(1) = NULL
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 INTO J_Activity
(OUId, SkillId, ShiftBandId,StartTime, EndTime, WorkType, ShiftId, RuleId, GroupNo, AllocationNo, CreatedBy, CreatedDate, 
 ProgresstionState, WorkloadId, RBRRank)
VALUES (@OUId, @SkillId, @ShiftBandId,@StartTime, @EndTime, COALESCE(@WorkType, (0)),   @ShiftId, @RuleId,@GroupNo, 
		IsNull(@AllocationNo,1), @CreatedBy, GETDATE(), @ProgressionState, @WorkloadId, @RBRRank)

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_AddEmployeeRBR')
	DROP PROC prJ_AddEmployeeRBR
GO

CREATE PROCEDURE prJ_AddEmployeeRBR
(
	@EmployeeId		BigInt,
	@RBRRank		nVarchar(1),
	@Remarks		nVarchar(500) = NULL,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	-- Validate whether employee id exists if exists update if not create
	DECLARE @RBRId BigInt = 0
	SELECT	@RBRId = IsNull(RBRId,0)
	From	J_EmployeeRBR WITH (NOLOCK) 
	WHERE	EmployeeId = @EmployeeId

	If (@RBRId = 0) 
	BEGIN
		INSERT INTO J_EmployeeRBR 
		(EmployeeId, Remarks, RBRRank, UpdatedBy, UpdatedDate)
		VALUES(@EmployeeId, @Remarks, @RBRRank, @UpdatedBy, GETDATE())

		SELECT  CAST(@@Identity AS bigint)  
	END
	Else
	BEGIN
		UPDATE	J_EmployeeRBR
		SET		RBRRank		=	@RBRRank,
				Remarks		=	@Remarks,
				UpdatedBy	=	@UpdatedBy,
				UpdatedDate	=	GETDATE()
		WHERE	RBRId		=	@RBRId

		SELECT 1
	END

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

CREATE PROCEDURE prJ_AddEmployeeShiftRBR
(
	@EmployeeId		BigInt,
	@ShiftId		BigInt,
	@ShiftDate		DateTime,
	@RBRRank		nVarchar(1),
	@Remarks		nVarchar(500) = NULL,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	
	INSERT INTO J_EmployeeShiftRBR
	(EmployeeId, ShiftId, ShiftDate, RBRRank, Remarks, UpdatedBy, UpdatedDate)
	VALUES(@EmployeeId, @ShiftId, Convert(Date,@ShiftDate), @RBRRank, @Remarks, @UpdatedBy, GETDATE())

	SELECT  CAST(@@Identity AS bigint)  

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),
	@EquipmentTypes		nVarchar(500)
)	with ENCRYPTION
AS
BEGIN
	If (CHARINDEX('0',@EquipmentTypes) > 0 OR @EquipmentTypes IS NULL)
	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
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),
	@SignedOffSkills	nVarchar(500)
)	
AS
BEGIN
	-- If Signed Off By Selected Equipment Types, Then Perform Selected Skills Related Actions Instead of entire ou and shiftband
	If (@SignedOffSkills IS NOT NULL)
	BEGIN
		DELETE FROM J_PlanningRequirements 
		WHERE	Convert(Date,RequirementDate) = Convert(Date,@ShiftDate) 
		AND		ShiftBandId =	@ShiftBandId
		AND		OUId		=	@OUId
		AND		SkillId		IN  (SELECT * FROM fnStringToTable(@SignedOffSkills))

		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
		AND		SkillId IN  (SELECT * FROM fnStringToTable(@SignedOffSkills))
		GROUP BY J_Activity.SkillId

		--SELECT CAST(@@Identity AS BigInt)
	END
	ELSE
	BEGIN
		-- If No Equipment Types Are Selected Perform conventional update
		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
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

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.FactorType,
			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.FactorType,
			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

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_AllocationFactor.FactorType,
			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_DeleteActivityByActivityId')
	DROP PROC prJ_DeleteActivityByActivityId
GO


CREATE PROC prJ_DeleteActivityByActivityId
	@ActivityId bigint
	
AS


delete from J_Activity where J_Activity.ActivityId=@ActivityId

delete J_ActivityAttributes from J_ActivityAttributes where J_ActivityAttributes.ActivityId=@ActivityId

	
select 1


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteActivityByCraneScheduleId')
	DROP PROC prJ_DeleteActivityByCraneScheduleId
GO
  
  
CREATE PROC prJ_DeleteActivityByCraneScheduleId  
 @CraneScheduleId bigint,   
 @ShiftEndTime datetime,  
 @ReliefBreakId bigInt,  
 @UpdatedBy nVarchar(50)  
   
AS  
  
;with ActivityDetails as(  
select J_Activity.ActivityId from J_Activity WITH (NoLock)  
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId  
inner join M_CraneSchedule WITH (NoLock) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
where M_CraneSchedule.CraneScheduleId =@CraneScheduleId and J_Activity.StartTime>=@ShiftEndTime)  
  
delete J_Activity from J_Activity inner join ActivityDetails on J_Activity.ActivityId=ActivityDetails.ActivityId  
  
;with RBActivityDetails as(  
select J_Activity.ActivityId from J_Activity WITH (NoLock)  
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId  
inner join M_CraneSchedule WITH (NoLock) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
where  M_CraneSchedule.CraneScheduleId =@CraneScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=@ReliefBreakId)  
  
delete J_Activity from J_Activity inner join RBActivityDetails on J_Activity.ActivityId=RBActivityDetails.ActivityId  
  
  
;with ActivityAttributesDetails as(  
select J_Activity.ActivityId from J_Activity WITH (NoLock)  
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId  
inner join M_CraneSchedule WITH (NoLock) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
where  M_CraneSchedule.CraneScheduleId =@CraneScheduleId and J_Activity.StartTime>=@ShiftEndTime)  
  
delete J_ActivityAttributes from J_ActivityAttributes inner join ActivityAttributesDetails on J_ActivityAttributes.ActivityId=ActivityAttributesDetails.ActivityId  
  
;with RBActivityAttributesDetails as(  
select J_Activity.ActivityId from J_Activity WITH (NoLock)  
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId  
inner join M_CraneSchedule WITH (NoLock) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
where  M_CraneSchedule.CraneScheduleId =@CraneScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=@ReliefBreakId)  
  
delete J_ActivityAttributes from J_ActivityAttributes inner join RBActivityAttributesDetails on J_ActivityAttributes.ActivityId=RBActivityAttributesDetails.ActivityId  
   
-- Update Activity End Time  
;with UpdateActivityDetails as(  
select J_Activity.ActivityId from J_Activity WITH (NoLock)  
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId  
inner join M_CraneSchedule WITH (NoLock) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
where M_CraneSchedule.CraneScheduleId =@CraneScheduleId and J_Activity.EndTime >=@ShiftEndTime)  
  
Update J_Activity   
  Set J_Activity.EndTime = @ShiftEndTime,  
   J_Activity.UpdatedBy =@UpdatedBy,  
   J_Activity.UpdatedDate =getdate()   from J_Activity   
inner join UpdateActivityDetails on J_Activity.ActivityId = UpdateActivityDetails.ActivityId  
  
select 1  
  
  

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


CREATE PROC prJ_DeleteActivityByEquipmentScheduleId
	@EquipmentScheduleId bigint,	
	@ShiftEndTime datetime,
	@ReliefBreakId bigInt,
	@UpdatedBy nVarchar(50)
	
AS

;with ActivityDetails as(
select J_Activity.ActivityId from J_Activity WITH (NoLock)
inner join J_Workload  WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_EquipmentSchedule  WITH (NoLock) on M_EquipmentSchedule.EquipmentScheduleId=J_Workload.EquipmentScheduleId
where M_EquipmentSchedule.EquipmentScheduleId =@EquipmentScheduleId and J_Activity.StartTime>=@ShiftEndTime)

delete J_Activity from J_Activity inner join ActivityDetails on J_Activity.ActivityId=ActivityDetails.ActivityId

;with RBActivityDetails as(
select J_Activity.ActivityId from J_Activity  WITH (NoLock)
inner join J_Workload  WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_EquipmentSchedule  WITH (NoLock) on M_EquipmentSchedule.EquipmentScheduleId=J_Workload.EquipmentScheduleId
where  M_EquipmentSchedule.EquipmentScheduleId =@EquipmentScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=@ReliefBreakId)

delete J_Activity from J_Activity inner join RBActivityDetails on J_Activity.ActivityId=RBActivityDetails.ActivityId


;with ActivityAttributesDetails as(
select J_Activity.ActivityId from J_Activity  WITH (NoLock)
inner join J_Workload  WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_EquipmentSchedule  WITH (NoLock) on M_EquipmentSchedule.EquipmentScheduleId=J_Workload.EquipmentScheduleId
where  M_EquipmentSchedule.EquipmentScheduleId =@EquipmentScheduleId and J_Activity.StartTime>=@ShiftEndTime)

delete J_ActivityAttributes from J_ActivityAttributes inner join ActivityAttributesDetails on J_ActivityAttributes.ActivityId=ActivityAttributesDetails.ActivityId

;with RBActivityAttributesDetails as(
select J_Activity.ActivityId from J_Activity  WITH (NoLock)
inner join J_Workload  WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_EquipmentSchedule  WITH (NoLock) on M_EquipmentSchedule.EquipmentScheduleId=J_Workload.EquipmentScheduleId
where  M_EquipmentSchedule.EquipmentScheduleId =@EquipmentScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=@ReliefBreakId)

delete J_ActivityAttributes from J_ActivityAttributes inner join RBActivityAttributesDetails on J_ActivityAttributes.ActivityId=RBActivityAttributesDetails.ActivityId

-- Update Activity End Time
;with UpdateActivityDetails as(
select J_Activity.ActivityId from J_Activity WITH (NoLock)
inner join J_Workload WITH (NoLock) on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_EquipmentSchedule  WITH (NoLock) on M_EquipmentSchedule.EquipmentScheduleId=J_Workload.EquipmentScheduleId
where M_EquipmentSchedule.EquipmentScheduleId =@EquipmentScheduleId and J_Activity.EndTime>=@ShiftEndTime)


Update J_Activity 
		Set J_Activity.EndTime = @ShiftEndTime,
			J_Activity.UpdatedBy =@UpdatedBy,
			J_Activity.UpdatedDate =getdate()   from J_Activity 
inner join UpdateActivityDetails on J_Activity.ActivityId = UpdateActivityDetails.ActivityId

select 1


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,
	@ShiftBandId bigint = 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)
	 and ShiftBandId = @ShiftBandId
	 ) 

	 
	
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)
 and ShiftBandId = @ShiftBandId
	
select 1


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


CREATE PROC prJ_DeleteActivityByVesselScheduleId
	@VesselScheduleId bigint,	
	@ShiftEndTime datetime
	
AS

;with ActivityDetails as(
select J_Activity.ActivityId from J_Activity 
inner join J_Workload on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_CraneSchedule on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId
inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId =M_CraneSchedule.VesselScheduleId
where  M_VesselSchedule.VesselScheduleId =@VesselScheduleId and J_Activity.StartTime>=@ShiftEndTime)

delete J_Activity from J_Activity inner join ActivityDetails on J_Activity.ActivityId=ActivityDetails.ActivityId

;with RBActivityDetails as(
select J_Activity.ActivityId from J_Activity 
inner join J_Workload on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_CraneSchedule on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId
inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId =M_CraneSchedule.VesselScheduleId
where  M_VesselSchedule.VesselScheduleId =@VesselScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=19)

delete J_Activity from J_Activity inner join RBActivityDetails on J_Activity.ActivityId=RBActivityDetails.ActivityId


;with ActivityAttributesDetails as(
select J_Activity.ActivityId from J_Activity 
inner join J_Workload on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_CraneSchedule on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId
inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId =M_CraneSchedule.VesselScheduleId
where  M_VesselSchedule.VesselScheduleId =@VesselScheduleId and J_Activity.StartTime>=@ShiftEndTime)

delete J_ActivityAttributes from J_ActivityAttributes inner join ActivityAttributesDetails on J_ActivityAttributes.ActivityId=ActivityAttributesDetails.ActivityId

;with RBActivityAttributesDetails as(
select J_Activity.ActivityId from J_Activity 
inner join J_Workload on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_CraneSchedule on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId
inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId =M_CraneSchedule.VesselScheduleId
where  M_VesselSchedule.VesselScheduleId =@VesselScheduleId and J_Activity.EndTime>=@ShiftEndTime and J_Activity.SkillId=19)

delete J_ActivityAttributes from J_ActivityAttributes inner join RBActivityAttributesDetails on J_ActivityAttributes.ActivityId=RBActivityAttributesDetails.ActivityId
	
select 1


GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteAllocationRule')
	DROP PROC prJ_DeleteAllocationRule
GO
 
 
Create PROCEDURE [dbo].[prJ_DeleteAllocationRule]    
(	
	@AllocationRuleId	BigInt,
	@UpdatedBy			nVarchar(50)			
)
AS
BEGIN
	 

	Update	J_AllocationRule
	SET		ActiveStatus		=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	AllocationRuleId	=	@AllocationRuleId

	SELECT 1 
END
GO

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

CREATE PROCEDURE prJ_DeleteCraneScheduleFromDate
(
	@ScheduleDate		DateTime,
	@ReliefBreakId		BigInt
)
AS
BEGIN
	--Delete Actvities
	;WITH ActivityDetails  
	AS 
	(  
		SELECT	J_Activity.ActivityId 
		FROM	J_Activity WITH (NOLOCK)  
				INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId  
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = J_Workload.CraneScheduleId  
		where	Convert(DateTime,J_Activity.StartTime) >= Convert(DateTime,@ScheduleDate)
	)
	DELETE J_Activity from J_Activity  INNER JOIN ActivityDetails ON J_Activity.ActivityId = ActivityDetails.ActivityId  

	-- Delete Relief Breaks
	;WITH RBActivityDetails AS(  
	SELECT	J_Activity.ActivityId 
	FROM	J_Activity WITH (NOLOCK)  
			INNER JOIN J_Workload WITH (NOLOCK) on J_Workload.WorkloadId =J_Activity.WorkloadId  
			INNER JOIN M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId = J_Workload.CraneScheduleId  
	where	Convert(DateTime,J_Activity.EndTime) >= Convert(DateTime,@ScheduleDate) 
	AND		J_Activity.SkillId = @ReliefBreakId)  
	
	DELETE J_Activity FROM J_Activity INNER JOIN RBActivityDetails on J_Activity.ActivityId = RBActivityDetails.ActivityId  

	-- Delete Activity Attributes
	;WITH ActivityAttributesDetails 
	AS (  
		SELECT	J_Activity.ActivityId from J_Activity WITH (NOLOCK)  
				INNER JOIN J_Workload WITH (NOLOCK) on J_Workload.WorkloadId =J_Activity.WorkloadId  
				INNER JOIN M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId = J_Workload.CraneScheduleId  
		WHERE	Convert(DateTime,J_Activity.StartTime) >= Convert(DateTime,@ScheduleDate)  
	)
 
	DELETE	J_ActivityAttributes 
	FROM	J_ActivityAttributes 
			INNER JOIN ActivityAttributesDetails ON J_ActivityAttributes.ActivityId = ActivityAttributesDetails.ActivityId  
  
	-- Delete Relief Break For Activity Attributes
	;with RBActivityAttributesDetails 
	AS (  
		SELECT	J_Activity.ActivityId FROM J_Activity WITH (NOLOCK)  
				INNER JOIN J_Workload WITH (NOLOCK) on J_Workload.WorkloadId =J_Activity.WorkloadId  
				INNER JOIN M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId  
		WHERE	Convert(DateTime,J_Activity.EndTime) >= Convert(DateTime,@ScheduleDate) 
		AND		J_Activity.SkillId = @ReliefBreakId
	)  
  
	DELETE	J_ActivityAttributes 
	FROM	J_ActivityAttributes 
			INNER JOIN RBActivityAttributesDetails ON J_ActivityAttributes.ActivityId = RBActivityAttributesDetails.ActivityId  
   
   -- Delete Workload For Crane Schedule
   ;WITH WorkloadDetails
   AS (
		SELECT	J_Workload.WorkloadId 
		FROM	J_Workload WITH (NOLOCK)
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = J_Workload.CraneScheduleId
		WHERE	Convert(DateTime,J_Workload.StartTime) >= Convert(DateTime,@ScheduleDate)
   )
   DELETE J_Workload FROM J_Workload INNER JOIN	WorkloadDetails ON J_Workload.WorkloadId = WorkloadDetails.WorkloadId

   -- Delete Crane Schedule.
   DELETE FROM M_CraneSchedule 
   WHERE	Convert(DateTime,M_CraneSchedule.StartDate) >= Convert(DateTime,@ScheduleDate)

   SELECT 1;

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

CREATE PROCEDURE prJ_DeleteEmployeeShiftRBRForDeAllocation
(
	@ShiftId	BigInt
)
AS
BEGIN
	DELETE FROM J_EmployeeShiftRBR Where ShiftId = @ShiftId

	SELECT 1

END
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,
	@SelectedSkills	nVarchar(100) = NULL
	
AS


DELETE FROM S_THPEmployeeDetails
WHERE ShiftId IN  (
					SELECT	S_Shifts.ShiftId
					FROM	S_Shifts WITH (NOLOCK) 
							INNER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
					WHERE	S_Shifts.ShiftBandId			=	@ShiftBandId
					AND		Convert(Date,ActualStartTime)	=	Convert(Date,@ShiftDate)
					AND		S_Shifts.OUId					=	@OUId
					AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SelectedSkills)) OR @SelectedSkills IS NULL)
				  )

SELECT 1

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteScheduleCreationRule')
	DROP PROC prJ_DeleteScheduleCreationRule
GO
 
 
Create PROCEDURE [dbo].[prJ_DeleteScheduleCreationRule]    
(	
	@ScheduleRuleId	BigInt,
	@UpdatedBy		nVarchar(50)			
)
AS
BEGIN
	Update	S_ScheduleRules
	SET		ActiveStatus		=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	ScheduleRuleId		=	@ScheduleRuleId

	SELECT 1 
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_DeleteTotalHourPeriodSettings')
	DROP PROC prJ_DeleteTotalHourPeriodSettings
GO
 
 
Create PROCEDURE [dbo].[prJ_DeleteTotalHourPeriodSettings]    
(	
	@THPSettingsId	BigInt,
	@UpdatedBy		nVarchar(50)			
)
AS
BEGIN
	Update	S_THPSettings
	SET		ActiveStatus		=	0,
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	THPSettingId		=	@THPSettingsId

	SELECT 1 
END
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 M_EquipmentSchedule

	DELETE FROM M_EquipmentSchedule 
	WHERE  EquipmentScheduleId IN
		   (
				SELECT  J_Workload.EquipmentScheduleId
				FROM	J_Workload  WITH (NOLOCK) 
				WHERE   J_Workload.VesselScheduleId = @VesselScheduleId
			)

	-- 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

	
	--Delete from M_VesselMiscellaneousColumns
	DELETE FROM M_VesselMiscellaneousColumns WHERE VesselScheduleId = @VesselScheduleId

	--Delete from M_VesselScheduleResourceSet
	DELETE FROM M_VesselScheduleResourceSet 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
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prJ_DisassembleShifts') AND type in (N'P', N'PC'))
	DROP PROCEDURE prJ_DisassembleShifts
GO

CREATE PROCEDURE prJ_DisassembleShifts
(
	@ShiftStartDate	DateTime,
	@ShiftEndDate	DateTime,
	@ShiftBandId	BigInt,
	@OUId			BigInt
)
AS
BEGIN
	
	-- Delete Form Workload By Given Date, Shift And OU
	DELETE	FROM J_Workload 
	WHERE	ShiftBandId = @ShiftBandId 
	AND		Convert(Date,StartTime) >= Convert(Date,@ShiftStartDate)
	AND		Convert(Date,StartTime) <= Convert(Date,@ShiftEndDate)
	AND		OUId = @OUId

	-- Delete Form Activity By Given Date, Shift And OU
	DELETE	FROM J_Activity  
	WHERE	ShiftBandId = @ShiftBandId 
	AND		Convert(Date,StartTime) >= Convert(Date,@ShiftStartDate)
	AND		Convert(Date,StartTime) <= Convert(Date,@ShiftEndDate) 
	AND		OUId = @OUId

	-- Delete Form Shift Sign Off Status By Given Date, Shift And OU
	DELETE	FROM M_ShiftSignOffStatus 
	WHERE	ShiftBandId = @ShiftBandId 
	AND		Convert(Date,ShiftDate) >= Convert(Date,@ShiftStartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@ShiftEndDate)
	AND OUId = @OUId

	-- Delete Form THP Employee Details By Given Date, Shift And OU
	DELETE	FROM S_THPEmployeeDetails 
	WHERE	ShiftId IN (SELECT ShiftId FROM S_Shifts WITH (NOLOCK) 
						WHERE ShiftBandId = @ShiftBandId 
						AND Convert(Date,ActualStartTime) >= Convert(Date,@ShiftStartDate)
						AND		Convert(Date,ActualStartTime) <= Convert(Date,@ShiftEndDate)
						AND OUId = @OUId)

	-- Delete Form THP Employee Equipment Details By Given Date, Shift And OU
	DELETE	FROM S_THPEmployeeEquipmentDetails 
	WHERE	ShiftId IN (SELECT ShiftId FROM S_Shifts WITH (NOLOCK) 
						WHERE ShiftBandId = @ShiftBandId 
						AND Convert(Date,ShiftEndTime) >= Convert(Date,@ShiftStartDate)
						AND		Convert(Date,ShiftStartTime) <= Convert(Date,@ShiftEndDate)
						AND OUId = @OUId)

	-- Delete Form Shift Cost By Given Date, Shift And OU
	DELETE	FROM P_ShiftCosts
	WHERE	ShiftId IN (SELECT ShiftId FROM S_Shifts WITH (NOLOCK) 
						WHERE ShiftBandId = @ShiftBandId 
						AND		Convert(Date,ActualStartTime) >= Convert(Date,@ShiftStartDate)
						AND		Convert(Date,ActualStartTime) <= Convert(Date,@ShiftEndDate)
						AND OUId = @OUId)

	-- Delete Form Shifts By Given Date, Shift And OU
	DELETE	FROM S_Shifts 
	WHERE	ShiftBandId = @ShiftBandId 
	AND		Convert(Date,ActualStartTime) >= Convert(Date,@ShiftStartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@ShiftEndDate)
	AND OUId = @OUId
	AND DeploymentNotes Like '%Assemble Shift%'

	-- Delete Equipment Schedule
	DELETE	FROM M_EquipmentSchedule
	WHERE	ShiftBandId = @ShiftBandId
	AND		CONVERT(Date,StartDate) > = Convert(Date,@ShiftStartDate)
	AND		CONVERT(Date,StartDate) < = Convert(Date,@ShiftEndDate)
	AND		OUId = @OUId

	-- Delete Crane Schedule
	DELETE	FROM M_CraneSchedule
	WHERE   StartDate > = @ShiftStartDate
	AND		StartDate < = @ShiftEndDate
	AND		OUId = @OUId

	-- Delete Vesel Schedule
	DELETE	FROM M_VesselSchedule
	WHERE   StartDate > = @ShiftStartDate
	AND		StartDate < = @ShiftEndDate
	AND		OUId = @OUId

	-- Delete Auxiliary Work
	DELETE	FROM M_AuxiliaryWork
	WHERE   StartDate > = @ShiftStartDate
	AND		StartDate < = @ShiftEndDate
	AND		OUId = @OUId

	-- Delte Shift Assemble Detail
	DELETE FROM M_ShiftAssemble_TemplateGroupDetail
	WHERE  M_ShiftAssemble_TemplateGroupDetail.ShiftAssembleId IN 
			(SELECT M_ShiftAssemble_TemplateGroup.ShiftAssembleId 
			 FROM	M_ShiftAssemble_TemplateGroup
			 WHERE  CONVERT(date,PlanDate) >= Convert(date,@ShiftStartDate)
			 AND	CONVERT(date,PlanDate) <= Convert(date,@ShiftEndDate)
			 AND	ShiftBandId = @ShiftBandId)

   -- Delete Shift Assemble
   DELETE FROM	M_ShiftAssemble_TemplateGroup
			 WHERE  CONVERT(date,PlanDate) >= Convert(date,@ShiftStartDate)
			 AND	CONVERT(date,PlanDate) <= Convert(date,@ShiftEndDate)
			 AND	ShiftBandId = @ShiftBandId
	SELECT 1
	
END
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	BigInt,
	@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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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 [Change to J_Activity Instead Shift]
	WHERE	(J_Activity.AllocationNo = @AllocationNo OR (J_Activity.ShiftId = @ShiftId AND @ShiftId != 0))
	AND		J_Activity.ShiftBandId	=	@ShiftBandId -- Updated Based on Reported Issue Of Multiple Activities being displayed from Daily Operations Screen
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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.ShiftBandId	=	@ShiftBandId -- Updated Based on Reported Issue Of Multiple Activities being displayed from Daily Operations Screen
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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.ShiftBandId	=	@ShiftBandId -- Updated Based on Reported Issue Of Multiple Activities being displayed from Daily Operations Screen
	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 sysobjects WHERE name = 'prJ_GetActivitiesByEmployeeId')
	DROP PROC prJ_GetActivitiesByEmployeeId
GO

----------------------------------------------------------------------------
-- Retrieve Data From Activity Details By Allocation Details
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivitiesByEmployeeId]
	@EmployeeId		BigInt,
	@ReliefBreakId	BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@OuId			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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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 [Change to J_Activity Instead Shift]
	WHERE   S_Shifts.EmployeeId = @EmployeeId	
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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	 S_Shifts.EmployeeId = @EmployeeId
	AND 	J_Activity.EndTime > CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.StartTime < CONVERT(DATETIME, @EndDate)
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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 
	WHERE	 S_Shifts.EmployeeId = @EmployeeId
	AND 	J_Activity.EndTime > CONVERT(DATETIME, @StartDate)
	AND 	J_Activity.StartTime < CONVERT(DATETIME, @EndDate)
	AND		J_Activity.WorkType		=	3
	AND		J_Activity.OUId			=	@OuId
	
	order by StartTime
GO

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

----------------------------------------------------------------------------
-- Retrieve Data From Activity Details By Given ShiftId
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetActivitiesByShiftId]
(
	@ShiftId		BigInt,
	@ReliefBreakId	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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 [Change to J_Activity Instead Shift]
	WHERE	J_Activity.ShiftId		=	@ShiftId
	AND		J_Activity.WorkType		=	2
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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.ShiftId		=	@ShiftId
	AND		J_Activity.WorkType		=	1
	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, 
			IsNull(J_Activity.GroupNo,0) GroupNo , IsNull(J_Activity.RuleId,0) RuleId, IsNull(J_Activity.WorkloadId,0) WorkloadId
	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.ShiftId		=	@ShiftId
	AND		J_Activity.WorkType		=	3
	ORDER BY StartTime
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetActivitiesForPrimeMoverUpdate')
	DROP PROCEDURE prJ_GetActivitiesForPrimeMoverUpdate
GO

CREATE PROC prJ_GetActivitiesForPrimeMoverUpdate
 (
	@StartDateTime			DateTime,
	@EndDateTime			DateTime,
	@ConfigScreen			nVarchar(500),
	@ConfigName				nVarchar(500),
	@FileterLastLocation	Bit,
	@RequestType			Int = 0
)
AS
BEGIN
	
	-- Retrieve Equipment Schedule, Activity, Workload Details
	SELECT  M_EquipmentSchedule.EquipmentScheduleId,
			M_EquipmentSchedule.EquipmentId,
			J_Activity.ActivityId,
			J_Workload.WorkloadId,
			J_Activity.StartTime ActivityStartTime,
			J_Activity.EndTime ActivityEndTime,
			S_Shifts.EmployeeId,
			S_Shifts.ShiftId,
			S_Shifts.Notes ShiftNotes
	FROM	M_EquipmentSchedule WITH (NOLOCK)
			INNER JOIN J_Workload WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = J_Workload.EquipmentScheduleId
			INNER JOIN J_Activity WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
			INNER JOIN S_Shifts WITH (NOLOCK) ON J_Activity.Shiftid = S_Shifts.ShiftId
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
	WHERE	Convert(DateTime,M_EquipmentSchedule.StartDate) >= Convert(DateTime,@StartDateTime)
	AND		Convert(DateTime,M_EquipmentSchedule.EndDate) <= Convert(DateTime,@EndDateTime)	
	--AND		J_Activity.SkillId != 8
	AND		M_EquipmentType.EquipmentType = (SELECT TOP 1 ConfigValue  FROM	M_ScreenConfiguration WITH (NOLOCK)  
											 WHERE	LTRIM(RTRIM(LOWER(ConfigScreen)))	=	LTRIM(RTRIM(LOWER(@ConfigScreen)))
											 AND	LTRIM(RTRIM(LOWER(ConfigName)))		= LTRIM(RTRIM(LOWER(@ConfigName))))
	
	If(@RequestType = 1 OR @RequestType = 3)
	BEGIN
		-- Retrieve Employee Equipment Login Details Between Selected Date And Time
		SELECT	ClockingId,
				EquipmentName,
				EmployeeId,
				EmployeeNumber,
				ClockInDateTime,
				ClockOutDateTime,
				IsClockInPicked,
				IsClockOutPicked,
				IsNull(ActivityId,0) ActivityId,
				LastLocation
		FROM	M_EmployeeEquipmentLogin WITH (NOLOCK)
		WHERE	Convert(DateTime,ClockInDateTime) >= Convert(DateTime, DATEADD(MI, -15, @StartDateTime))
		AND		Convert(DateTime,ClockInDateTime) <= Convert(DateTime, DATEADD(MI, 15, @EndDateTime))
	END
	Else 
	BEGIN
		DECLARE @EquipmentLastLocationValidHours Int = 24
		SELECT	@EquipmentLastLocationValidHours = IsNull(Convert(int,ParamValue),0) 
		FROM	D_SystemParams WITH (NOLOCK)
		WHERE	ParamName = 'EquipmentLocationValidityHours'

		;WITH EmpEquipmentLog AS 
		(  
			SELECT	ClockingId,
					EquipmentName,
					EmployeeId,
					EmployeeNumber,
					ClockInDateTime,
					ClockOutDateTime,
					IsClockInPicked,
					IsClockOutPicked,
					IsNull(ActivityId,0) ActivityId,
					LastLocation,
					ROW_NUMBER() OVER(PARTITION BY M_EmployeeEquipmentLogin.EquipmentName ORDER BY M_EmployeeEquipmentLogin.ClockInDateTime DESC) RowId   
			FROM	M_EmployeeEquipmentLogin WITH (NOLOCK)
			WHERE	Convert(DateTime,ClockOutDateTime) > Convert(DateTime,DATEADD(HOUR, -@EquipmentLastLocationValidHours, @StartDateTime))
			AND		Convert(DateTime,ClockInDateTime) <  Convert(DateTime, @StartDateTime)
			--AND		Convert(Date,M_EmployeeEquipmentLogin.ClockInDateTime) <= Convert(Date, @StartDateTime)
		)
		SELECT * FROM EmpEquipmentLog WHERE RowId = 1
	END
END
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,
			J_Activity.RBRRank
	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,
			IsNull(M_Equipments.EquipmentId,0) EquipmentId,
			IsNull(M_Equipments.EquipmentName, D_Skill.Skill) 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,
			J_Activity.RBRRank
	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,
			J_Activity.RBRRank
	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
			LEFT OUTER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = VesselSchedule.ScheduleId 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = J_Activity.ShiftBandId
	WHERE 	J_Activity.OUId=@OUId
	AND		J_Activity.WorkType = 4
	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,
			J_Activity.RBRRank
	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
BEGIN
	SELECT	J_Activity.*, IsNull(M_EquipmentSchedule.EquipmentId,0) EquipmentId, 
			IsNull(M_EquipmentBrands.BrandNameId,0) BrandNameId
	FROM	J_Activity WITH (NOLOCK) 
			LEFT OUTER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
			LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
			LEFT OUTER JOIN M_EquipmentBrands WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_EquipmentBrands.EquipmentId
	WHERE	J_Activity.OUId		=	@OUId 
	AND		(ShiftId	=	0 OR ShiftId IS NULL)
	AND		ProgresstionState >	1 
	AND		J_Activity.SkillId IN (@SkillId, @ReliefBreakId)
	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 J_Activity.StartTime	<	@EndTime)
	ORDER BY BrandNameId
END
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 BigInt
	
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 sysobjects WHERE name = 'prJ_GetActivityLastAllocationGroupNo')
	DROP PROC prJ_GetActivityLastAllocationGroupNo
GO

CREATE PROCEDURE prJ_GetActivityLastAllocationGroupNo
(
	@StartDateTime		DateTime,
	@EndDateTime		DateTime
)
AS
BEGIN
	SELECT	Max(IsNull(GroupNo,0)) LastGroupNo, Max(IsNull(AllocationNo,0)) LastAllocationNo
	FROM	J_Activity WITH (NOLOCK)
	WHERE	Convert(DateTime,EndTime)	> Convert(DateTime, @StartDateTime)
	AND		Convert(DateTime,StartTime) < Convert(DateTime, @EndDateTime)
	--SELECT	IIF(IsNull(Max(IsNull(GroupNo,0)),1) > 2000,1, IsNull(Max(IsNull(GroupNo,0)),1)) LastGroupNo, 
	--		IIF(IsNull(Max(IsNull(AllocationNo,0)),1) > 2000,1, IsNull(Max(IsNull(AllocationNo,0)),1)) LastAllocationNo
	--FROM	J_Activity WITH (NOLOCK)
	--WHERE	Convert(Date,StartTime) =	Convert(Date,@SignOffDate)
END
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
/****** Object:  StoredProcedure [dbo].[prT_GetAttachmentsBySourceId]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prJ_GetAssembleShiftEmployeeForAllocation') AND type in (N'P', N'PC'))
DROP PROCEDURE prJ_GetAssembleShiftEmployeeForAllocation
GO

CREATE PROCEDURE prJ_GetAssembleShiftEmployeeForAllocation
(
	@ShiftStartTime	DateTime,
	@ShiftEndTime	DateTime,
	@SkillId		BigInt,
	@OUId			BigInt
)
AS
BEGIN
	-- Retrieve Available Employees
	SELECT	C_Employee.EmployeeId, C_EmployeeSkills.SkillId, C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
			CASE WHEN D_Roles.PrimarySkillId = D_RoleSkill.SkillId THEN CONVERT(BIT,1) ELSE CONVERT(BIT,0) END PrimarySkill,
			C_EmployeeOU.IsPrimaryOU PrimaryOU, C_EmployeeOU.StartDate OrgUnitStartDate, C_EmployeeOU.EndDate OrgUnitEndDate,
			D_Roles.RoleId, IsNull(D_Roles.RolePrioritySeq,0) RolePrioritySeq, D_Roles.RoleGroupId, 
			@ShiftStartTime ActualStartTime, 
			@ShiftEndTime ActualEndTime,
			IsNull(S_Shifts.ShiftId, 0) ShiftId,
			C_Employee.OUId,
			ISNull(C_Employee.ScheduleRuleId,0) ScheduleRuleId
	FROM	C_Employee WITH (NOLOCK) 
			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 AND D_RoleSkill.SkillId = @SkillId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON D_EmploymentBasis.EmploymentBasisId = C_Employee.EmploymentBasisId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId AND C_EmployeeSkills.SkillId= @SkillId
			INNER JOIN C_EmployeeOU WITH (NOLOCK) ON C_EmployeeOU.EmployeeId = C_Employee.EmployeeId 
				AND Convert(Date,C_EmployeeOU.EndDate) >= Convert(Date,@ShiftStartTime) 
				And Convert(date,C_EmployeeOU.StartDate) <= Convert(Date,@ShiftStartTime)
				AND	C_EmployeeOU.OUId = @OUId
			LEFT OUTER JOIN S_Shifts WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId 
			And Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @ShiftStartTime)
	WHERE	IsNull(S_SHifts.ShiftId, 0) = 0

	-- 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 Schedule Periods By Organization Unit
	;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, @ShiftStartTime) >= StartDate And Convert(Date, @ShiftStartTime) <= EndDate
		AND		S_SchedulePeriod.OUId = @OUId
		--AND		S_SchedulePeriod.ScheduleRuleId	=	1
	)
	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	=	1
	UNION ALL
	SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	FROM	SchedulePeriod;

	-- Retrieve Shifts Between Schedule Period
	WITH  SchedulePeriod 
	AS
	(	
		SELECT	SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate 
		FROM	S_SchedulePeriod WITH (NOLOCK)
		WHERE	Convert(Date, @ShiftStartTime) >= StartDate And Convert(Date,@ShiftStartTime) <= EndDate
		AND		S_SchedulePeriod.OUId = @OUId
		--AND		S_SchedulePeriod.ScheduleRuleId	=	1
	),
	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	=	1
		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)

	-- Retrieve Shift And Activity Counters Between Selected Shift Date
	SELECT	IsNull(SUM(ShiftCounter),0) ShiftCounter, IsNull(SUM(ActivityCounter),0) ActivityCounter, EmployeeId 	 
	FROM	S_THPEmployeeDetails WITH (NOLOCK)
	WHERE	CONVERT(date,ShiftDate) >= (SELECT	TOP 1 PeriodStart FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  Convert(Date,@ShiftStartTime) and PeriodEnd >= Convert(Date,@ShiftStartTime) And OUId	=	@OUId)
	AND		CONVERT(date,ShiftDate) <= (SELECT	TOP 1 PeriodEnd FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  Convert(Date,@ShiftStartTime) and PeriodEnd >= Convert(Date,@ShiftStartTime) And OUId	=	@OUId)
	GROUP BY EmployeeId
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.ShiftStartTime) = 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
	WITH BroadCastedRows
	AS
	(
		SELECT	BroadcastId, 
				OUId, 
				BroadcastDate, 
				ShiftBandId, 
				StartTime, 
				EndTime, 
				EmployeeId, 
				ShiftId, 
				Sequence, 
				CreatedBy, 
				CreatedDate, 
				ROW_NUMBEr() OVER(PARTITION BY J_BroadcastDeployment.ShiftId ORDER BY J_BroadcastDeployment.Sequence DESC) as RowNumber,
				ActivityId
		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
	)
	SELECT * FROM BroadCastedRows where RowNumber = 1
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

/****** Object:  StoredProcedure [dbo].[prTA_GetDeployedNonPrimarySkill]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prJ_GetDeployedNonPrimarySkill') AND type in (N'P', N'PC'))
	DROP PROCEDURE prJ_GetDeployedNonPrimarySkill
GO
 
CREATE PROCEDURE prJ_GetDeployedNonPrimarySkill
(
	@ShiftDate		DateTime,
	@ShiftBand		nVarchar(max),
	@RoleGroups		nVarchar(max),
	@PrimarySkills	nVarchar(max),
	@ReliefBreakId	BigInt,
	@OUId			BigInt
)
AS
BEGIN
	;WITH FirstActivity as 
	(
		SELECT	J_Activity.ActivityId, J_Activity.StartTime, S_Shifts.ShiftId, J_Activity.SkillId, D_Skill.Skill,
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				IsNull(J_Activity.UpdatedBy,'') UpdatedBy
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @ShiftDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
		AND		J_Activity.SkillId != @ReliefBreakId
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
	)
	SELECT	C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStart, 
			S_Shifts.InTime ClockInTime,
			S_Shifts.ShiftEndTime ShiftEnd,
			S_Shifts.OutTime ClockOutTime,
			S_Shifts.ReconStatusId AttendanceStatusId,
			EmpPrimaryRole.RoleName PrimaryRole,
			D_Skill.Skill PrimarySkill,
			FirstActivity.Skill DeployedSkill,
			FirstActivity.SkillId, S_Shifts.RoleId, S_Shifts.ShiftId,
			FirstActivity.EquipmentName DeployedEquipment, FirstActivity.StartTime,
			FirstActivity.UpdatedBy LastUpdatedBy
	FROM	S_Shifts WITH (NOLOCK) INNER JOIN FirstActivity WITH (NOLOCK) ON S_Shifts.ShiftId = FirstActivity.ShiftId And FirstActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId 
	WHERE	(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroups)) OR @RoleGroups = '0')
	AND		(D_Skill.SkillId IN (SELECT * FROM fnStringToTable(@PrimarySkills)) OR @PrimarySkills = '0')
	AND		FirstActivity.SkillId != C_EmployeeSkills.SkillId
END
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,
	@ConfigSkills		nVarchar(200) = NULL,
	@LastPublishedDate	DateTime = NULL,
	@ReliefBreakId		BigInt = 0
AS
BEGIN
	-- Retrieve List of Deployed Shifts
	--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, D_ShiftBand.ShiftBandName,
	--		S_Shifts.RBRRank ShiftRank, IsNull(Notes,'') ShiftNotes
	--FROM	S_Shifts WITH (NOLOCK)
	--		LEFT OUTER JOIN Activities ON S_Shifts.ShiftId = Activities.ShiftId
	--		INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId

	-- Retrieve Deployed Skills
	If(@LastPublishedDate IS NULL)
	BEGIN
		SELECT	DISTINCT S_Shifts.OUId, S_Shifts.ShiftBandId, S_Shifts.EmployeeId, S_Shifts.ShiftId,
				S_Shifts.ShiftStartTime ActualStartTime, S_Shifts.ShiftEndTime ActualEndTime, D_ShiftBand.ShiftBandName,
				S_Shifts.RBRRank ShiftRank, IsNull(Notes,'') ShiftNotes, IsNull(MessageId,0) MessageId,
				C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
				S_Shifts.CreatedDate, S_Shifts.UpdatedDate
		FROM	S_Shifts WITH (NOLOCK) 
				INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId =  C_Employee.EmployeeId
				INNER JOIN D_RoleSkill WITH (NOLOCK) ON S_Shifts.RoleId = D_RoleSkill.RoleId 				
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
				INNER JOIN D_MessageSkill WITH (NOLOCK) ON D_MessageSkill.SkillId = D_RoleSkill.SkillId
		WHERE	Convert(Date,ShiftStartTime)	=	Convert(Date,@StartTime)
		AND		S_Shifts.ShiftBandId			=	@ShiftBandId
		AND		S_Shifts.OUId					=	@OUId
		AND		(D_RoleSkill.SkillId IN (SELECT * FROM fnStringToTable(@ConfigSkills)) OR IsNull(@ConfigSkills,'0') = '0')
		AND S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM S_EmployeeLeaves  WITH (NOLOCK)
						   WHERE Convert(Date,@StartTime) = Convert(Date,FromDate) 
						   AND S_EmployeeLeaves.OUId = @OUId) 
		AND	S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@StartTime))
		AND		S_Shifts.ShiftId NOT  IN (
												SELECT	ShiftId
												FROM	S_ShiftExceptions WITH (NOLOCK)
												WHERE	Convert(Date, StartTime) = Convert(Date, @StartTime)
										 )
	END
	ELSE
	BEGIN
		SELECT	DISTINCT S_Shifts.OUId, S_Shifts.ShiftBandId, S_Shifts.EmployeeId, S_Shifts.ShiftId,
				S_Shifts.ShiftStartTime ActualStartTime, S_Shifts.ShiftEndTime ActualEndTime, D_ShiftBand.ShiftBandName,
				S_Shifts.RBRRank ShiftRank, IsNull(Notes,'') ShiftNotes, IsNull(MessageId,0) MessageId,
				C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
				S_Shifts.CreatedDate, S_Shifts.UpdatedDate
		FROM	S_Shifts WITH (NOLOCK) 
				INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId =  C_Employee.EmployeeId
				INNER JOIN D_RoleSkill WITH (NOLOCK) ON S_Shifts.RoleId = D_RoleSkill.RoleId 				
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
				INNER JOIN D_MessageSkill WITH (NOLOCK) ON D_MessageSkill.SkillId = D_RoleSkill.SkillId
				LEFT OUTER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
		WHERE	Convert(Date,ShiftStartTime)	=	Convert(Date,@StartTime)
		AND		S_Shifts.ShiftBandId			=	@ShiftBandId
		AND		S_Shifts.OUId					=	@OUId
		AND		(D_RoleSkill.SkillId IN (SELECT * FROM fnStringToTable(@ConfigSkills)) OR IsNull(@ConfigSkills,'0') = '0')
		AND S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM S_EmployeeLeaves  WITH (NOLOCK)
						   WHERE Convert(Date,@StartTime) = Convert(Date,FromDate) 
						   AND S_EmployeeLeaves.OUId = @OUId) 
		AND	S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@StartTime))
		AND		S_Shifts.ShiftId NOT  IN (
												SELECT	ShiftId
												FROM	S_ShiftExceptions WITH (NOLOCK)
												WHERE	Convert(Date, StartTime) = Convert(Date, @StartTime)
										 )
		AND		((Convert(DateTime,S_Shifts.CreatedDate) >= Convert(DateTime, @LastPublishedDate) OR 
				 Convert(DateTime,S_Shifts.UpdatedDate) >= Convert(DateTime, @LastPublishedDate) )
		OR		(Convert(DateTime,J_Activity.CreatedDate) >= Convert(DateTime, @LastPublishedDate) OR 
				 Convert(DateTime,J_Activity.UpdatedDate) >= Convert(DateTime, @LastPublishedDate) ))
		
	END

	-- Retrieve Activities For Broadcasting
	SELECT	ActivityId, StartTime, EndTime, ShiftId, EquipmentName, Min(Convert(int,RowNumber)) FirstRowNumber, Max(TotalRowsCount) LastRowNumber, EquipmentType, EquipmentId,
			VesselStartTime, VesselEndTime, VesselName, IsNull(LocationName,'') LocationName, IsNull(ShiftNotes,'') ShiftNotes, EmployeeNumber, EmployeeName,
			ShiftBandName, MessageId, DeployedSkill
	FROM (
		SELECT J_Activity.ActivityId, J_Activity.StartTime, J_Activity.EndTime, S_Shifts.ShiftId,
		IIF(CraneWorkLoad.CraneScheduleId != 0, 0, Equipments.EquipmentTypeId) EquipmentType,
		IIF(CraneWorkLoad.CraneScheduleId != 0, Cranes.CraneId, Equipments.EquipmentId) EquipmentId,
		IIF(CraneWorkLoad.CraneScheduleId != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName,
		M_VesselSchedule.VesselName, M_VesselSchedule.StartDate VesselStartTime, M_VesselSchedule.EndDate VesselEndTime,
		IsNull(CraneLocations.LocationName, IsNull(EquipmentLocations.LocationName,'')) LocationName,
		S_SHifts.Notes ShiftNotes, C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName, D_ShiftBand.ShiftBandName, D_MessageSkill.MessageId,
		D_Skill.Skill DeployedSkill,
		ROW_NUMBEr() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
		COUNT(*) over (PARTITION BY J_Activity.ShiftId) as TotalRowsCount, IsNull(J_Activity.RBRRank,'') DeployedRank
		FROM J_Activity WITH (NOLOCK)
		INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
		INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		INNER JOIN D_MessageSkill WITH (NOLOCK) ON D_MessageSkill.SkillId = J_Activity.SkillId
		INNER JOIN D_Skill WITH (NOLOCK) ON J_Activity.SkillId = D_SKill.SkillId
		LEFT OUTER JOIN M_Locations CraneLocations WITH (NOLOCK) ON CraneLocations.LocationId = J_Activity.LocationId
		LEFT OUTER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = CraneWorkLoad.VesselScheduleId
		LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
		INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
		LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
		LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		LEFT OUTER JOIN M_Locations EquipmentLocations WITH (NOLOCK) ON EquipmentLocations.LocationId = EquipmentWorkLoad.LocationId
		WHERE Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date, @StartTime)
		AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date, @EndTime)
		AND	 S_Shifts.ShiftBandId  = @ShiftBandId
		AND S_Shifts.OUId = @OUId
		AND	J_Activity.SkillId != @ReliefBreakId
	) Activities
	--WHERE RowNumber = 1 or RowNumber = TotalRowsCount
	GROUP BY	ActivityId, StartTime, EndTime, ShiftId, EquipmentName, EquipmentType, EquipmentId, VesselStartTime, VesselEndTime, VesselName, 
				LocationName, ShiftNotes, EmployeeNumber, EmployeeName, ShiftBandName, MessageId, DeployedSkill
	ORDER BY 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,
	@ShiftBandId		nVarchar(max)
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.ShiftBandId IN (SELECT  * From fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')
	--AND		J_Activity.ShiftId IS NOT NULL
	--AND		J_Activity.ProgresstionState = 3
END


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetEmployeeActingIncentiveByDateRange')
	DROP PROC prJ_GetEmployeeActingIncentiveByDateRange
GO
CREATE PROCEDURE prJ_GetEmployeeActingIncentiveByDateRange
(
	@OUId				BigInt,
	@EmployeeNumber		nVarchar(max),
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ShiftBands			nVarchar(500),
	@Position			nVarchar(255),
	@SkillId			nVarchar(255),
	@IsReconciledShifts	Bit -- 1 = Reconciled Shifts Only, 0 = All Shifts
)
AS
BEGIN
	SELECT	C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName, C_Employee.Position, 
			D_ShiftBand.ShiftBandCode, D_Skill.Skill DeployedSkill,  S_Shifts.ReconStatusId,
			Min(J_Activity.StartTime) StartTime, Max(J_Activity.EndTime) EndTime, 
			IsNull(S_Shifts.ReconStatusId, 0) AttendanceStatusId
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN S_Shifts WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
			INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId 
						AND C_EmployeeSkills.IsActingSkill = 1 AND J_Activity.SkillId = C_EmployeeSkills.SkillId
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@StartDate) 
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@EndDate)
	AND		(C_Employee.EmployeeNumber LIKE (@EmployeeNumber)  OR C_Employee.DisplayName LIKE (@EmployeeNumber))
	AND		(J_Activity.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '')
	AND		(C_Employee.Position = @Position OR @Position = '')
	AND		(J_Activity.SkillId  IN (SELECT * FROM fnStringToTable(@SkillId)) OR @SkillId = '')
	AND		(S_Shifts.Reconciled = @IsReconciledShifts OR @IsReconciledShifts = 0)
	AND		J_Activity.OUId = @OUId
	GROUP BY C_Employee.EmployeeNumber, C_Employee.DisplayName, C_Employee.Position,
			D_ShiftBand.ShiftBandCode, D_Skill.Skill,  S_Shifts.ReconStatusId, S_Shifts.ShiftId, 
			C_Employee.EmployeeId, Convert(Date,S_Shifts.ActualStartTime)
	ORDER BY C_Employee.EmployeeNumber
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetEmployeeIncentive')
	DROP PROCEDURE pr_GetEmployeeIncentive
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetEmployeeIncentive')
	DROP PROCEDURE prJ_GetEmployeeIncentive
GO

CREATE PROC prJ_GetEmployeeIncentive
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeNumber		nVarchar(max),
	@ShiftBands			nVarchar(500),  
	@Paycode			nVarchar(255),  
	@SkillId			nVarchar(255),  
	@ReliefBreakId		BigInt
)
AS
	-- Retrieve Shift Details

		Select distinct  S_Shifts.ShiftId,
				S_Shifts.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_Skill.Skill,
				D_ShiftBand.ShiftBandCode ShiftBand,
				CONVERT(Date,ShiftStartTime)ShiftDate,
				(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ApprovedHours)/60),2) + ':' + 
				RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ApprovedHours)%60),2)) Hours,
				D_PayCodes.PayCode,
				isnull(P_ShiftCosts.UpdatedBy,P_ShiftCosts.CreatedBy) ApprovedBy,
				isnull(P_ShiftCosts.UpdatedDate,P_ShiftCosts.CreatedDate) ApprovedDate
		FROM  S_Shifts
		INNER JOIN J_Activity  WITH (NOLOCK)  on S_Shifts.ShiftId = J_Activity.ShiftId
		INNER JOIN D_Skill  WITH (NOLOCK)  on D_Skill.SkillId =J_Activity.SkillId
		INNER JOIN C_Employee  WITH (NOLOCK)  on C_Employee.EmployeeId =S_Shifts.EmployeeId
		INNER JOIN D_ShiftBand  WITH (NOLOCK)  on D_ShiftBand.ShiftBandId=S_Shifts.ShiftBandId 
		INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
	    INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId 
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 
		AND  (C_Employee.EmployeeNumber LIKE (@EmployeeNumber)  OR C_Employee.DisplayName LIKE (@EmployeeNumber))  
		AND     J_Activity.SkillId !=@ReliefBreakId
		AND    (J_Activity.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '')  
		AND    (J_Activity.SkillId  IN (SELECT * FROM fnStringToTable(@SkillId)) OR @SkillId = '')  
		AND    (P_ShiftCosts.PayCodeId  IN (SELECT * FROM fnStringToTable(@Paycode)) OR @Paycode = '')  
		

	
GO

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

CREATE PROCEDURE prJ_GetEmployeeRBRRanks
(
	@EmployeeIds	nVarchar(max)
)
AS
BEGIN	
	SELECT	J_EmployeeRBR.RBRId, 
			J_EmployeeRBR.EmployeeId,
			C_Employee.EmployeeNumber + ' ' +  C_Employee.DisplayName EmployeeNumberAndName,
			J_EmployeeRBR.Remarks,
			J_EmployeeRBR.RBRRank,
			J_EmployeeRBR.UpdatedBy,
			J_EmployeeRBR.UpdatedDate 
	FROM	J_EmployeeRBR WITH (NOLOCK) 
			INNER JOIN	C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = J_EmployeeRBR.EmployeeId
	WHERE	(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeIds)) OR @EmployeeIds = '0')
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetEmployeeRBRRanksHistory')
	DROP PROC prJ_GetEmployeeRBRRanksHistory
GO

CREATE PROCEDURE prJ_GetEmployeeRBRRanksHistory
(
	@EmployeeId		BigInt,
	@SelectedDate	DateTime
)
AS
BEGIN	
	SELECT	J_EmployeeShiftRBR.RBRHisId,
			J_EmployeeShiftRBR.ShiftId,
			J_EmployeeShiftRBR.EmployeeId,
			J_EmployeeShiftRBR.ShiftDate,
			J_EmployeeShiftRBR.RBRRank,
			J_EmployeeShiftRBR.Remarks,
			J_EmployeeShiftRBR.UpdatedBy,
			J_EmployeeShiftRBR.UpdatedDate
	FROM	J_EmployeeShiftRBR WITH (NOLOCK) 
	WHERE	J_EmployeeShiftRBR.EmployeeId = @EmployeeId
	AND		(Convert(Date,J_EmployeeShiftRBR.ShiftDate) <= Convert(Date,@SelectedDate) OR @SelectedDate IS NULL)
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,
			IsNull(D_Roles.PreparationTime, 0) PreparationMins,
			IsNull(D_Roles.DePreparationTime, 0) DePreparationMins
	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,
			IsNull(D_Roles.PreparationTime, 0) PreparationMins,
			IsNull(D_Roles.DePreparationTime, 0) DePreparationMins
	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 = 'pr_GetFinalBookingReport')
	DROP PROCEDURE pr_GetFinalBookingReport
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetFinalBookingReport')
	DROP PROCEDURE prJ_GetFinalBookingReport
GO

CREATE PROC prJ_GetFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeId			BigInt,
	@CraneConditionType Int,
	@OUId				BigInt,
	@SkillIds			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@ReliefBreakId		BigInt,
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS

		-- Retrieve Shift Details  
	 WITH ShiftDetails AS (  
	  SELECT  S_Shifts.ShiftId,   
		J_Activity.StartTime BookingDate,   
		S_Shifts.EmployeeId,   
		J_Activity.RBRRank DeployedRank,   
		S_Shifts.RBRRank LiveRank,   
		ISNULL(S_SHifts.Notes,'') Notes,  
		C_Employee.EmployeeNumber,   
		C_Employee.DisplayName EmployeeName,   
		M_CraneSchedule.CraneId,  
		D_MasterCodes.CodeValue Priority,  
		--IsNull(M_Cranes.CraneNumber,M_Equipments.EquipmentName) CraneNumber,  
		M_Cranes.CraneNumber,
		J_Activity.AllocationNo,  
		J_Activity.GroupNo,  
		J_Activity.ActivityId,  
		J_Activity.WorkType,  
		D_Roles.RoleName,  
		D_Roles.RoleDesc RoleDescription,
		D_ShiftBand.ShiftBandCode,  
		S_Shifts.ActualStartTime ShiftActualStart,  
		S_Shifts.ActualEndTime ShiftActualEnd,  
		D_Roles.RoleId,  
		J_Activity.SkillId DeployedSkillId,  
		C_EmployeeSkills.SkillId PrimarySkillId,  
		J_Activity.StartTime ActivityStartTime,  
		J_Activity.EndTime ActivityEndTime,  
		ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId   
	  FROM S_Shifts   WITH (NOLOCK)   
		INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId   
		INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId  
		INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId    
		   --INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId   
		--INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId   
		   INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId  
		   INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId  
		INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId  
		LEFT OUTER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId  
		LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK)  ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId  
		LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = M_CraneSchedule.CranePriorityId   
		LEFT OUTER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId  
		--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
		--LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
	  WHERE S_Shifts.ShiftStartTime >= @StartDate   
	  AND  S_Shifts.ShiftEndTime <= @EndDate   
	  AND  (S_Shifts.EmployeeId = @EmployeeId OR @EmployeeId=0)  
	  AND  (J_Activity.SkillId  IN (SELECT * FROM fnStringToTable(@SkillIds)) OR @SkillIds = '0')  
	  AND  S_Shifts.OUId = @OUId  
	 )  
	 SELECT * FROM ShiftDetails WITH (NOLOCK)    
	 WHERE RowId = 1  
	--ORDER BY SkillId, GroupNo, Ranks

	--Crane Condition Detail
	 SELECT M_CraneConditionDetails.CraneId,   
	 'YES' Jerk,  
	 StartDate,  
	 EndDate  
	 FROM M_CraneConditiondetails WITH (NOLOCK)    
	   INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneConditionDetails.CraneId  
	 WHERE M_Cranes.OUId =  @OUId  
	 AND  M_CraneConditionDetails.ConditionType = @CraneConditionType  
	 --AND  (StartDate BETWEEN @StartDate AND @EndDate)   
	 --OR  (EndDate BETWEEN @StartDate AND @EndDate)   
	 AND    Convert(datetime,EndDate) > @StartDate   
	 AND    Convert(datetime,StartDate) < @EndDate 

	--Over Time Details
	SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)

	-- Retrieve Skills For Fixed Ranking Grouping
	SELECT	D_Skill.SkillId, D_SKill.FixedRanking,
			D_Skill.Skill SkillName
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK) ON D_Skill.SkillId = D_SkillOU.SkillId
	WHERE	D_SkillOU.OUId	=	@OUId
	AND		D_Skill.FixedRanking IS NOT NULL

	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
				--LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON  S_EmployeeLeaves.EmployeeId = S_Shifts.EmployeeId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
	
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_Roles.RoleDesc RoleDescription,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			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 = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
	AND		(C_EmployeeSkills.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_MasterCodes.CodeValue Priority,  
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) CraneNumber, 
					 Cranes.CraneNumber,
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = M_CraneSchedule.CranePriorityId   
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_Roles.RoleDesc RoleDescription,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.CraneNumber,
			NonPrimarySkillActivity.Priority
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			CraneWorkLoad.CraneScheduleId,
			--EquipmentWorkLoad.EquipmentScheduleId,
	  --      iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) CraneNumber,
			--Equipments.EquipmentId,
			Cranes.CraneNumber, 
			Cranes.CraneId,
			J_Activity.RBRRank DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			J_Activity.StartTime ActivityStartTime,  
			J_Activity.EndTime ActivityEndTime
	FROM    J_Activity  WITH (NOLOCK)
			LEFT OUTER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId  
			LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId  
			--LEFT OUTER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId  
			--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId  
			--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId  
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 


 --Retrieve Slashed Crane Details  
 SELECT SlashedCraneId,   
   ShiftDate,  
   ShiftBandId,  
   SkillId,  
   ActivityStart,  
   ActivityEnd,  
   J_SlashedCranes.CraneId,  
   M_Cranes.CraneNumber,  
   GroupNumber  
 FROM J_SlashedCranes WITH (NOLOCK)   
   INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = J_SlashedCranes.CraneId  
 WHERE (ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')  
 AND  Convert(Date,ShiftDate) = Convert(Date,@StartDate)  

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,
	@EmployeeFilterShiftBands nVarchar(500) = NULL -- Filter Employees By Multiple Shiftbands if selected
AS
BEGIN
	-- If Filter Is NULL Update With Selected Shift Band
	-- <JiraItem cref="E10-223">Workload Planning - Select Multiple ShiftBands To Filter Employees For Deployment</JiraItem> 
	If(@EmployeeFilterShiftBands IS NULL) SET @EmployeeFilterShiftBands = Convert(nVarchar(50),@ShiftBandId);

	-- 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,
			Convert(Date,S_Shifts.ActualStartTime) ShiftDate,
			S_Shifts.ActualStartTime, S_Shifts.ActualEndTime,
			D_Roles.RoleGroupId,
			IsNull(S_Shifts.RBRRank,'D') RBRRank,
			IsNull(C_EmployeeSkills.SkillRating,0) SkillRating,
			IsNull(Nationality.Weightage,0) NationalityWeightage,
			IsNull(Religion.Weightage,0) ReligionWeightage,
			IsNull(Gender.Seq,0) GenderSequence
	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 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 C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.SkillId = D_RoleSkill.SkillId 
				AND C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId-- To Retrieve SKill Rating
			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
			-- <JiraItem cref="E10-223">Workload Planning - Select Multiple ShiftBands To Filter Employees For Deployment</JiraItem>  
			--AND D_ShiftBandCombination.ComboShiftBandId = @ShiftBandId
			AND D_ShiftBandCombination.ComboShiftBandId IN (SELECT * FROM fnStringToTable(@EmployeeFilterShiftBands))
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = D_RoleSkill.RoleId
			LEFT OUTER JOIN D_MasterCodes Nationality WITH (NOLOCK) ON Nationality.CodeId = C_Employee.CountryId
			LEFT OUTER JOIN D_MasterCodes Religion WITH (NOLOCK) ON Religion.CodeId = C_Employee.ReligionId
			LEFT OUTER JOIN D_MasterCodes Gender WITH (NOLOCK) ON Gender.CodeId = C_Employee.GenderId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ShiftDate)
	AND		S_Shifts.ouid = @OUId
	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.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftDate))
	AND		S_Shifts.ShiftId NOT  IN (
											SELECT	ShiftId
											FROM	S_ShiftExceptions WITH (NOLOCK)
											WHERE	Convert(Date, StartTime) = Convert(Date, @ShiftDate)
									 )
	
	---- 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_GetHSSEFinalBookingReport')
	DROP PROCEDURE prJ_GetHSSEFinalBookingReport
GO

CREATE PROC prJ_GetHSSEFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@OUId				BigInt,
	@ReliefBreakId		BigInt,
	@LocationId			nVarchar(100),
	@SkillIds			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS
	-- Retrieve Shift Details
	WITH ShiftDetails AS (
		SELECT	 S_Shifts.ShiftId, 
				J_Activity.StartTime BookingDate, 
				S_Shifts.EmployeeId, 
				J_Activity.SkillId,
				ISNULL(S_SHifts.Notes,'') Notes,
				C_Employee.DisplayName EmployeeName, 
				M_Locations.LocationId,
				M_Locations.LocationName,
				J_Workload.ScheduleId,
				J_Activity.RBRRank DeployedRank, 
				S_Shifts.RBRRank LiveRank, 
				J_Activity.SkillId DeployedSkillId,
				D_Skill.Skill DeployedSkillName,
				J_Activity.ActivityId,
				J_Activity.WorkType,
				D_Roles.RoleName,
				D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime ShiftActualStart,
				S_Shifts.ActualEndTime ShiftActualEnd,
				D_Roles.RoleId,
				J_Activity.AllocationNo,
				C_Employee.EmployeeNumber,
				ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId ORDER BY J_Activity.StartTime) RowId 
		--FROM	S_Shifts   WITH (NOLOCK) 
		--		INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
		--		INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
		--		INNER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
		--		INNER JOIN M_AuxiliaryWork WITH (NOLOCK)  ON J_Workload.ScheduleId = M_AuxiliaryWork.ScheduleId
		--		INNER JOIN M_Locations   WITH (NOLOCK)  ON	M_Locations.LocationId =J_Activity.LocationId
		FROM	M_AuxiliaryWork WITH (NOLOCK) 
				INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.ScheduleId = M_AuxiliaryWork.ScheduleId
				INNER JOIN J_Activity WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
				INNER JOIN M_Locations WITH (NOLOCK) ON M_Locations.LocationId = J_Workload.LocationId
				INNER JOIN S_Shifts WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			    INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 	
		AND		S_Shifts.OUId =	@OUId
		AND		J_Activity.SkillId	!= @ReliefBreakId
		And		(M_Locations.LocationId IN (SELECT * FROM fnStringToTable(@LocationId)) OR @LocationId='0') 
		AND		(D_Skill.SkillId	IN (SELECT * FROM fnStringToTable(@SkillIds)))
	)
	SELECT		ShiftDetails.ShiftId, 
				ShiftDetails.BookingDate, 
				ShiftDetails.EmployeeId, 
				ShiftDetails.SkillId,
				ShiftDetails.DeployedRank,
				ShiftDetails.LiveRank,
				ISNULL(ShiftDetails.Notes,'') Notes,
				ShiftDetails.EmployeeName, 
				ShiftDetails.LocationId,
				ShiftDetails.LocationName,
				ShiftDetails.ScheduleId,
				ShiftDetails.DeployedSkillName,
				ShiftDetails.ActivityId,
				ShiftDetails.WorkType,
				ShiftDetails.RoleName,
				ShiftDetails.ShiftBandCode,
				ShiftDetails.ShiftActualStart,
				ShiftDetails.ShiftActualEnd,
				ShiftDetails.RoleId,
				ShiftDetails.AllocationNo,
				ShiftDetails.EmployeeNumber,
				ROW_NUMBER() Over(partition by ShiftDetails.LocationId ORDER BY ShiftDetails.LocationId)Nos FROM ShiftDetails WITH (NOLOCK)  
	WHERE	RowId = 1

	--Over Time  Details
	SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	

		-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 				
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId,
			ROW_NUMBER() Over(partition by StandbyEmployeeActivity.WorkType ORDER BY S_Shifts.EmployeeId)Nos
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1			
			LEFT JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
    AND		(C_EmployeeSkills.SkillId	IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_Skill.Skill DeployedSkillName,
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					INNER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.DeployedSkillName,
			ROW_NUMBER() Over(partition by NonPrimarySkillActivity.WorkType ORDER BY S_Shifts.EmployeeId)Nos
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			IsNull(J_Activity.RBRRank,'A') DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			D_Skill.Skill DeployedSkillName,
			ROW_NUMBER() Over(partition by J_Activity.WorkType ORDER BY J_Activity.WorkType)Nos
	FROM    J_Activity  WITH (NOLOCK)			
			LEFT JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId  	
			LEFT JOIN M_AuxiliaryWork WITH (NOLOCK) ON J_Workload.ScheduleId = M_AuxiliaryWork.ScheduleId
			LEFT JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId 
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetLashingFinalBookingReport')
	DROP PROCEDURE prJ_GetLashingFinalBookingReport
GO

CREATE PROC prJ_GetLashingFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@OUId				BigInt,
	@ReliefBreakId		BigInt,
	@SkillId			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS
	-- Retrieve Shift Details
	WITH ShiftDetails AS (
		SELECT	 S_Shifts.ShiftId, 
				J_Activity.StartTime BookingDate, 
				S_Shifts.EmployeeId, 
				IsNull(J_Activity.RBRRank,'') DeployedRank,
				IsNull(S_Shifts.RBRRank,'') LiveRank, 
				J_Activity.SkillId,
				D_Skill.Skill SkillName,
				ISNULL(S_SHifts.Notes,'') Notes,
				'' OT,
				C_Employee.EmployeeNumber,	
				J_Workload.CraneScheduleId,
				J_Workload.VesselScheduleId,
				C_Employee.DisplayName EmployeeName, 
				J_Activity.AllocationNo,
				J_Activity.GroupNo,
				IsNull(J_Activity.LocationId, J_Workload.LocationId) LocationId,
				J_Activity.SkillId DeployedSkillId,
				D_Skill.Skill DeployedSkillName,
				J_Activity.ActivityId,
				J_Activity.WorkType,
				D_Roles.RoleName,
				D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime ShiftActualStart,
				S_Shifts.ActualEndTime ShiftActualEnd,
				D_Roles.RoleId,
				ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId 
		FROM	S_Shifts   WITH (NOLOCK) 
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
				INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
				INNER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			    INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 		
		AND		(J_Activity.SkillId		IN (SELECT * FROM fnStringToTable(@SkillId)))
		AND     J_Activity.SkillId != @ReliefBreakId
		AND		S_Shifts.OUId =	@OUId
	)
	SELECT * FROM ShiftDetails WITH (NOLOCK)  
	WHERE	RowId = 1

	--Over Time  Details
		SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 

	-- Cone Man Plan
	SELECT M_ConeManPlan.ConeManPlanId,
		   M_ConeManPlanDetail.CraneScheduleId,		   
		   M_CraneSchedule.CraneId,
		   M_Cranes.CraneNumber
	FROM   M_ConeManPlanDetail WITH(NOLOCK)
		   INNER JOIN M_ConeManPlan WITH(NOLOCK) ON M_ConeManPlanDetail.ConeManPlanId = M_ConeManPlan.ConeManPlanId
		   INNER JOIN M_CraneSchedule WITH (NOLOCK)  ON M_ConeManPlanDetail.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		   INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
	AND	   M_ConeManPlan.PlannedDate >= Convert(Date,@StartDate)
	AND	   M_ConeManPlan.PlannedDate <= Convert(Date,@EndDate)

	-- Top Man Plan
	SELECT M_TopManPlanDetail.TopManPlanId,
		   M_TopManPlanDetail.CraneScheduleId,
		   M_CraneSchedule.CraneId,
		   M_Cranes.CraneNumber
	FROM   M_TopManPlanDetail WITH(NOLOCK)
		   INNER JOIN M_TopManPlan WITH(NOLOCK) ON M_TopManPlanDetail.TopManPlanId = M_TopManPlan.TopManPlanId
		   INNER JOIN M_CraneSchedule WITH (NOLOCK)  ON M_TopManPlanDetail.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		   INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
	AND	   Convert(Date,M_TopManPlan.PlannedDate) >= Convert(Date,@StartDate)
	AND	   Convert(Date,M_TopManPlan.PlannedDate) <= Convert(Date,@EndDate)

	-- Tab Reader Plan
	SELECT M_TabReaderPlan.TabReaderPlanId,
		   M_TabReaderPlanDetail.VesselScheduleId,
		   M_TabReaderPlanDetail.Requirement,
		   M_VesselSchedule.VesselName
	FROM   M_TabReaderPlanDetail WITH(NOLOCK)
		   INNER JOIN M_TabReaderPlan WITH(NOLOCK) ON M_TabReaderPlanDetail.TabReaderPlanId = M_TabReaderPlan.TabReaderPlanId
		   INNER JOIN M_VesselSchedule WITH(NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_TabReaderPlanDetail.VesselScheduleId
	AND	   Convert(Date,M_TabReaderPlan.PlannedDate) >= Convert(Date,@StartDate)
	AND	   Convert(Date,M_TabReaderPlan.PlannedDate) <= Convert(Date,@EndDate)

	-- Lasher Plan
	SELECT M_LasherPlanDetail.LasherPlanId,
		   M_LasherPlanDetail.LocationId,
		   M_LasherPlanDetail.Requirement,
		   M_LasherPlanDetail.VesselName,
		   M_Locations.LocationName
	FROM   M_LasherPlanDetail WITH(NOLOCK)
		   INNER JOIN M_LasherPlan WITH(NOLOCK) ON M_LasherPlanDetail.LasherPlanId = M_LasherPlan.LasherPlanId
		   INNER JOIN M_Locations  WITH(NOLOCK) ON M_Locations.LocationId = M_LasherPlanDetail.LocationId
	AND	   Convert(Date,M_LasherPlan.PlannedDate) >= Convert(Date,@StartDate)
	AND	   Convert(Date,M_LasherPlan.PlannedDate) <= Convert(Date,@EndDate)

	--Location Details
	SELECT  M_Locations.LocationId,
			M_Locations.LocationName
	FROM	M_Locations WITH (NOLOCK) 


	-- Retrieve Skills For Fixed Ranking Grouping
	SELECT	D_Skill.SkillId, D_SKill.FixedRanking
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK) ON D_Skill.SkillId = D_SkillOU.SkillId
	WHERE	D_SkillOU.OUId	=	@OUId
	AND		(D_Skill.SkillId		IN (SELECT * FROM fnStringToTable(@SkillId)))
	AND		D_Skill.FixedRanking IS NOT NULL

		-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,				
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				Cranes.CraneNumber, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId,
			D_Skill.Skill SkillName,
			ROW_NUMBER() Over(partition by StandbyEmployeeActivity.WorkType ORDER BY S_Shifts.EmployeeId)Nos
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1			
			LEFT JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
    AND		(C_EmployeeSkills.SkillId	IN (SELECT * FROM fnStringToTable(@SkillId)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_Skill.Skill DeployedSkillName,
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
					Cranes.CraneNumber, 
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					--LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					INNER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillId)))
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.DeployedSkillName,
			ROW_NUMBER() Over(partition by NonPrimarySkillActivity.WorkType ORDER BY S_Shifts.EmployeeId)Nos
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			IsNull(J_Activity.RBRRank,'') DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			D_Skill.Skill DeployedSkillName,
			ROW_NUMBER() Over(partition by J_Activity.WorkType ORDER BY J_Activity.WorkType)Nos
	FROM    J_Activity  WITH (NOLOCK)			
			LEFT JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId  	
			LEFT JOIN M_AuxiliaryWork WITH (NOLOCK) ON J_Workload.ScheduleId = M_AuxiliaryWork.ScheduleId
			LEFT JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId 
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillId)))

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 

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,
		IsNull(J_ManningRatio.SkillNames,'') SkillNames,
		IsNull(J_ManningRatio.RatioName, '') RatioName 
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 = 'pr_GetPayoutReportDetails')
    DROP PROCEDURE pr_GetPayoutReportDetails
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetPayoutReportDetails')
	DROP PROCEDURE prJ_GetPayoutReportDetails
GO

CREATE PROC prJ_GetPayoutReportDetails
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ReliefBreakId		BigInt,
	@SkillId			BigInt
)
AS
	SELECT 	S_Shifts.ShiftId,
			S_Shifts.EmployeeId,
			C_Employee.EmployeeNumber,
			J_Activity.StartTime,
			J_Activity.EndTime,
			M_CraneSchedule.CraneId,
			M_Cranes.CraneNumber,
			D_Skill.Skill SkillName
	FROM    J_Activity WITH (NOLOCK)
	INNER JOIN S_Shifts WITH (NOLOCK) on S_Shifts.ShiftId=J_Activity.ShiftId 
	INNER JOIN J_WorkLoad WITH (NOLOCK) on J_WorkLoad.WorkLoadId=J_Activity.WorkLoadId
	INNER JOIN M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId=J_WorkLoad.CraneScheduleId
	INNER JOIN M_Cranes WITH (NOLOCK) on M_Cranes.CraneId=M_CraneSchedule.CraneId
	INNER JOIN C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = S_Shifts.EmployeeId
	INNER JOIN D_Skill WITH (NOLOCK) on D_Skill.SkillId = J_Activity.SkillId
	WHERE S_Shifts.ShiftStartTime >=	@StartDate 
	AND	  S_Shifts.ShiftEndTime	<=	@EndDate  
	AND   J_Activity.SkillId !=@ReliefBreakId
	AND	  J_Activity.SkillId =@SkillId

	--Crane Payout Granularity
	SELECT  ParamValue GranularityValue from D_SystemParams 
	Where ParamName='CranePayoutGranularity'
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetPMFinalBookingReport')
	DROP PROCEDURE prJ_GetPMFinalBookingReport
GO

CREATE PROC prJ_GetPMFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@Ranks				nVarchar(100),
	@ReliefBreakId		BigInt,
	@OUId				BigInt,
	@SkillIds			nVarchar(500),
	@LocationIDs		nVarchar(100),
	@EquipmentTypeName	nVarchar(100),
	@EmployeeId			BigInt,
	@ShiftBand			nVarchar(max),
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS
	--Retrieve Shift Details
		SELECT  S_Shifts.ShiftId, 				
				J_Activity.StartTime,
				J_Activity.EndTime,
				S_Shifts.EmployeeId, 
				IsNull(J_Activity.RBRRank,'A') DeployedRank,
				S_Shifts.RBRRank LiveRank, 
				J_Activity.SkillId,
				ISNULL(S_Shifts.Notes,'') Notes,
				C_Employee.EmployeeNumber,	
				C_Employee.DisplayName EmployeeName, 
				M_EquipmentSchedule.EquipmentId,
				--M_Equipments.EquipmentName,
				IsNull(J_Activity.EquipmentNotes,M_Equipments.EquipmentName) EquipmentName,
				M_EquipmentType.EquipmentType,
				J_Activity.LocationId,
				M_Locations.LocationName,
				D_Skill.Skill DeployedSkillName,
				J_Activity.ActivityId,
				J_Activity.WorkType,
				D_Roles.RoleName,
				D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime ShiftActualStart,
				S_Shifts.ActualEndTime ShiftActualEnd,
				D_Roles.RoleId,
				J_Activity.SkillId DeployedSkillId,				
				J_Activity.AllocationNo,
				J_Activity.GroupNo,
				S_Shifts.DeploymentNotes		
		FROM	S_Shifts   WITH (NOLOCK) 
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
				INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
				LEFT OUTER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK)  ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments  WITH (NOLOCK)  ON  M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
				LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
				And		M_EquipmentType.EquipmentType IN (SELECT * FROM fnStringToTable(@EquipmentTypeName))
				LEFT OUTER JOIN M_Locations   WITH (NOLOCK)  ON	M_Locations.LocationId = J_Activity.LocationId
				LEFT JOIN D_Skill  WITH (NOLOCK)  ON D_Skill.SkillId = J_Activity.SkillId
			    INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			    INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 
		AND		J_Activity.SkillId		!=	@ReliefBreakId
		AND		(D_ShiftBand.ShiftBandId	IN (SELECT * FROM fnStringToTable(@ShiftBand)))
		AND		(J_Activity.SkillId		IN (SELECT * FROM fnStringToTable(@SkillIds)))
		AND		S_Shifts.OUId			=	@OUId
		AND		(J_Activity.LocationId IN (SELECT * FROM fnStringToTable(@LocationIds)) OR @LocationIds = '0')
		AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId= '0')
	    AND  (J_Activity.RBRRank  IN (SELECT * FROM fnStringToTable(@Ranks)) OR @Ranks = '0')  

		
	--Over Time & Allowances Details
		SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)

		-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				Equipments.EquipmentName,
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			ISNULL(S_Shifts.RBRRank,'A') LiveRank,
			ISNULL(StandbyEmployeeActivity.DeployedRank,'A')DeployedRank,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			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 = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
	AND		(C_EmployeeSkills.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		(S_Shifts.RBRRank IN (SELECT * FROM fnStringToTable(@Ranks)) OR @Ranks = '0')
	AND		 D_ShiftBand.ShiftTypeId != @ShiftBandTypeId
	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					J_Activity.EndTime,
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_Skill.Skill DeployedSkillName,
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
					 Equipments.EquipmentName,
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					INNER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.DeployedSkillName,
			NonPrimarySkillActivity.StartTime ShiftStartTime,
			NonPrimarySkillActivity.EndTime ShiftEndTime,
			NonPrimarySkillActivity.EquipmentName
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  
	AND		(NonPrimarySkillActivity.DeployedRank IN (SELECT * FROM fnStringToTable(@Ranks)) OR @Ranks = '0')
	
	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			EquipmentWorkLoad.EquipmentScheduleId,
	        Equipments.EquipmentName,
			Equipments.EquipmentId,
			M_EquipmentType.EquipmentType,
			IsNull(J_Activity.RBRRank,'A') DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			D_Skill.Skill DeployedSkillName
	FROM    J_Activity  WITH (NOLOCK)
			LEFT OUTER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId  
			LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId 
			LEFT OUTER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)
	AND		(J_Activity.RBRRank IN (SELECT * FROM fnStringToTable(@Ranks)) OR @Ranks = '0')

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetPMPlanningDetail')
	DROP PROCEDURE prJ_GetPMPlanningDetail
GO

CREATE PROC prJ_GetPMPlanningDetail
 (
	@PlanningDate		DateTime,
	@ShiftBandId		nVarchar(50),
	@OUId				BigInt
)
AS
Declare @PlanId BigInt
 ---PM Planning
 SELECT		M_PMPlanning.PMPlanningId,
			M_PMPlanning.PlanningDate,
			M_PMPlanning.ShiftBandId,
			M_PMPlanning.ActivityGenerationRuleId,
			M_PMPlanning.AllocationRuleId
 FROM		M_PMPlanning WITH(NOLOCK)
 WHERE		Convert(Date,M_PMPlanning.PlanningDate) = @PlanningDate
 AND		M_PMPlanning.ShiftBandId = @ShiftBandId

 --PM Planning Skill
 SELECT			M_PMPlanningSkills.PMPlanningSkillId,
				M_PMPlanningSkills.PMPlanningId,
				M_PMPlanningSkills.SkillId,
				M_PMPlanningSkills.Requirement
 FROM			M_PMPlanningSkills  WITH(NOLOCK)
				INNER JOIN	M_PMPlanning  WITH(NOLOCK) ON M_PMPlanning.PMPlanningId =  M_PMPlanningSkills.PMPlanningId
 WHERE			Convert(Date,M_PMPlanning.PlanningDate) = @PlanningDate
 AND			M_PMPlanning.ShiftBandId = @ShiftBandId

 --PM Location
  SELECT		DISTINCT M_PMPlanningLocation.PMPlanningId,
				M_PMPlanningLocation.LocationId
 FROM			M_PMPlanningLocation  WITH(NOLOCK)
				INNER JOIN	M_PMPlanning  WITH(NOLOCK) ON M_PMPlanning.PMPlanningId =  M_PMPlanningLocation.PMPlanningId
 WHERE			Convert(Date,M_PMPlanning.PlanningDate) = @PlanningDate
 AND			M_PMPlanning.ShiftBandId = @ShiftBandId


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
	DECLARE @ReliefBreakId BigInt  = 0;

	SELECT	@ReliefBreakId = Convert(BigInt,ParamValue) 
	FROM	D_SystemParams WITH (NOLOCK) 
	WHERE	ParamName ='ReliefBreakId';

	WITH ACTIVITIES (ShiftId)
	AS
	(
		SELECT	DISTINCT J_Activity.ShiftID 
		FROM	J_Activity  WITH (NOLOCK)
		WHERE	J_Activity.SkillId IN (SELECT SKILLID FROM J_Activity WITH (NOLOCK) WHERE ShiftId = @ShiftId AND SkillId != @ReliefBreakId) --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

	--Equipments Detail
		SELECT	S_Shifts.ShiftID,
				S_Shifts.EmployeeId,
				M_Equipments.EquipmentId,
				M_Equipments.EquipmentName
		FROM	S_Shifts  WITH (NOLOCK)
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.ShiftId = J_Activity.ShiftId
				INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
				INNER JOIN M_EquipmentSchedule  WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = J_Workload.EquipmentScheduleId
				INNER JOIN M_Equipments  WITH (NOLOCK) ON M_Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	J_Activity.SkillId IN (SELECT SKILLID FROM J_Activity WITH (NOLOCK) WHERE ShiftId = @ShiftId AND SkillId != @ReliefBreakId) 
		AND Convert(DateTime,J_Activity.EndTime) > Convert(DateTime,@ShiftStartTime)
		AND Convert(DateTime,J_Activity.StartTime) < Convert(DateTime,@ShiftEndTime)
		AND	J_Activity.ShiftId != @ShiftId
		AND J_Activity.OUId = @OUId

END

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetRTGFinalBookingReport')
	DROP PROCEDURE prJ_GetRTGFinalBookingReport
GO

CREATE PROC prJ_GetRTGFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@OUId				BigInt,
	@ReliefBreakId		BigInt,
	@EquipmentTypeName	nVarchar(100),
	@SkillIds			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int,
	@NormalPaycodeId	BigInt
)
AS
	-- Retrieve Shift Details
	WITH ShiftDetails AS (
		SELECT	 S_Shifts.ShiftId, 
				J_Activity.StartTime BookingDate, 
				S_Shifts.EmployeeId, 
				J_Activity.SkillId,
				ISNULL(S_SHifts.Notes,'') Notes,
				C_Employee.EmployeeNumber,	
				C_Employee.DisplayName EmployeeName, 
				M_EquipmentSchedule.EquipmentId,
				M_Equipments.EquipmentName,
				M_EquipmentType.EquipmentType,
				J_Activity.RBRRank DeployedRank, 
				S_Shifts.RBRRank LiveRank, 
				J_Activity.SkillId DeployedSkillId,
				D_Skill.Skill DeployedSkillName,
				J_Activity.ActivityId,
				J_Activity.WorkType,
				D_Roles.RoleName,
				D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime ShiftActualStart,
				S_Shifts.ActualEndTime ShiftActualEnd,
				D_Roles.RoleId,
				J_Activity.AllocationNo,
				S_Shifts.ShiftStartTime,
				S_Shifts.ShiftEndTime,
				ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId 
		FROM	S_Shifts   WITH (NOLOCK) 
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
				INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
				INNER JOIN D_Skill  WITH (NOLOCK)  ON D_Skill.SkillId = J_Activity.SkillId
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			    INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
				LEFT OUTER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK)  ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
				LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
								And		M_EquipmentType.EquipmentType IN (SELECT * FROM fnStringToTable(@EquipmentTypeName))
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 	
		AND		S_Shifts.OUId =	@OUId
		AND		J_Activity.SkillId	!= @ReliefBreakId
		AND		(J_Activity.SkillId		IN (SELECT * FROM fnStringToTable(@SkillIds)))
		

	)
	SELECT * FROM ShiftDetails WITH (NOLOCK)  
	--WHERE	RowId = 1


	--Over Time & Allowances Details
	SELECT	S_Shifts.ShiftId,
			P_ShiftCosts.PayCodeId,
			D_PayCodes.PayCode,
			P_ShiftCosts.ActualHour
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	AND		D_PayCodes.PayCodeId != @NormalPaycodeId

	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				Equipments.EquipmentName,
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId,
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1			
			LEFT JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
    AND		(C_EmployeeSkills.SkillId	IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_Skill.Skill DeployedSkillName,
					Equipments.EquipmentId,
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
					Equipments.EquipmentName,
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					INNER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.DeployedSkillName,
			NonPrimarySkillActivity.EquipmentId,
			NonPrimarySkillActivity.EquipmentName,
			S_Shifts.ShiftStartTime,
			S_Shifts.ShiftEndTime
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId --And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			--CraneWorkLoad.CraneScheduleId,
			EquipmentWorkLoad.EquipmentScheduleId,
	        --iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) CraneNumber,
			Equipments.EquipmentName,
			Equipments.EquipmentId,
			--Cranes.CraneId,
			IsNull(J_Activity.RBRRank,'A') DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			D_Skill.Skill DeployedSkillName
	FROM    J_Activity  WITH (NOLOCK)
			--LEFT OUTER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId  
			--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId  
			--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId  
			LEFT OUTER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId  
			LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId  
			LEFT OUTER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 
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 
	(PeriodNo)
	--(SchedulePeriodId, OUId, ScheduleRuleId, StartDate, EndDate, PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate)
	AS
	(	SELECT  PeriodNo	--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, Convert(Date,StartDate) StartDate, Convert(Date,EndDate) EndDate, 
			PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
	FROM	S_SchedulePeriod  WITH (NOLOCK)
	WHERE	PeriodNo	>= (SELECT PeriodNo FROM SchedulePeriod) - 1
	AND		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, Convert(Date,StartDate) StartDate, Convert(Date,EndDate) 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, Convert(Date, StartDate) StartDate, Convert(Date, EndDate) EndDate, 
				PeriodYear, PeriodNo, ReferenceNotes, CreatedBy, CreatedDate
		FROM	S_SchedulePeriod  WITH (NOLOCK)
		WHERE	PeriodNo	>= (SELECT PeriodNo FROM SchedulePeriod) - 1
		AND		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,
			1 ShiftType -- Shift
	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
	UNION ALL
	SELECT  S_EmployeeLeaves.ShiftId ShiftId,
			S_EmployeeLeaves.EmployeeId,
			S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime,
			2 ShiftType -- Employee Leaves
	FROM	S_EmployeeLeaves 
			INNER JOIN S_Shifts ON S_Shifts.ShiftId = S_EmployeeLeaves.ShiftId 
	WHERE  Convert(Date, S_EmployeeLeaves.FromDate) >= (select MIN(STARTDATE) FROM SchedulePeriodPrevCurr)
	AND		Convert(Date, S_EmployeeLeaves.EndDate) <= (select MAX(EndDate) FROM SchedulePeriodPrevCurr)
	AND		ShiftBandId = S_Shifts.CombinationShiftId
	AND		S_EmployeeLeaves.ShiftId IS NOT NULL
	AND		S_EmployeeLeaves.EmployeeId		=	@EmployeeId
	UNION ALL
	SELECT	ISNull(S_EmployeeLeaves.ShiftId,0) ShiftId,
			S_EmployeeLeaves.EmployeeId,
			0 ShiftBandId,
			S_EmployeeLeaves.FromDate,
			S_EmployeeLeaves.EndDate,
			3 ShiftType -- Employee Leave With No Shift
	FROM	S_EmployeeLeaves 
	WHERE	Convert(Date, S_EmployeeLeaves.FromDate) >= (select MIN(STARTDATE) FROM SchedulePeriodPrevCurr)
	AND		Convert(Date, S_EmployeeLeaves.EndDate) <= (select MAX(EndDate) FROM SchedulePeriodPrevCurr)
	AND		S_EmployeeLeaves.EmployeeId		=	@EmployeeId
	AND		S_EmployeeLeaves.ShiftId IS NULL
	UNION ALL
	SELECT	S_ShiftExceptions.ShiftId,
			S_Shifts.EmployeeId,
			S_Shifts.ShiftBandId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime,
			4 ShiftType -- Shift Exception
	FROM	S_ShiftExceptions WITH (NOLOCK) 
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_ShiftExceptions.ShiftId = S_Shifts.ShiftId
	WHERE	Convert(Date, S_ShiftExceptions.StartTime) >= (select MIN(STARTDATE) FROM SchedulePeriodPrevCurr)
	AND		Convert(Date, S_ShiftExceptions.StartTime) <= (select Max(EndDate) FROM SchedulePeriodPrevCurr)
	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

----------------------------------------------------------------------------
-- Get All Flexi Shifts
-- <JiraItem cref="E10-223">Workload Planning - Select Multiple ShiftBands To Filter Employees For Deployment</JiraItem> 
-- [Added employeeFilterShiftBands  Parameter]
----------------------------------------------------------------------------
CREATE PROC prJ_GetShiftsForAllocation
	@OUId bigint,
	@ShiftBandId bigint,	
	@ShiftDate Date,
	@EmployeeFilterShiftBands nVarchar(500) = NULL -- Filter Employees By Multiple Shiftbands if selected
AS
BEGIN
	-- If Filter Is NULL Update With Selected Shift Band
	-- <JiraItem cref="E10-223">Workload Planning - Select Multiple ShiftBands To Filter Employees For Deployment</JiraItem> 
	If(@EmployeeFilterShiftBands IS NULL) SET @EmployeeFilterShiftBands = Convert(nVarchar(50),@ShiftBandId)

	-- 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, 
			IsNull(C_Employee.ContractedHours,0) ContractedHours,
			C_Employee.EmploymentBasisId, 
			D_EmploymentBasis.EmploymentBasisCode,
			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, 
			Convert(Date,S_Shifts.ActualStartTime) ShiftDate,
			S_Shifts.ActualStartTime, 
			S_Shifts.ActualEndTime,
			D_Roles.RoleGroupId, 
			IsNull(S_Shifts.RBRRank,'D') RBRRank, 
			IsNull(C_EmployeeSkills.SkillRating,0) SkillRating,
			IsNull(Nationality.Weightage,0) NationalityWeightage,
			IsNull(Religion.Weightage,0) ReligionWeightage,
			IsNull(Gender.Seq,0) GenderSequence
	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
			LEFT OUTER JOIN D_MasterCodes Nationality WITH (NOLOCK) ON Nationality.CodeId = C_Employee.CountryId
			LEFT OUTER JOIN D_MasterCodes Religion WITH (NOLOCK) ON Religion.CodeId = C_Employee.ReligionId
			LEFT OUTER JOIN D_MasterCodes Gender WITH (NOLOCK) ON Gender.CodeId = C_Employee.GenderId
			INNER JOIN D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.SkillId = D_RoleSkill.SkillId 
				AND C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId-- To Retrieve SKill Rating
	-- <JiraItem cref="E10-223">Workload Planning - Select Multiple ShiftBands To Filter Employees For Deployment</JiraItem>  
	-- where ShiftBandId = @ShiftBandId
	WHERE	ShiftBandId IN (SELECT * FROM fnStringToTable(@EmployeeFilterShiftBands))
	 --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) 
	AND		S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftDate))
	AND		S_Shifts.ShiftId NOT  IN (
											SELECT	ShiftId
											FROM	S_ShiftExceptions WITH (NOLOCK)
											WHERE	Convert(Date, StartTime) = Convert(Date, @ShiftDate)
									 )
	--order by C_Employee.EmployeeNumber


	-- Retrieve THP Period Start And End Date For Selected Shift Date
	SELECT	PeriodStart StartDate, PeriodEnd EndDate, EmployeeId, THPPeriodId 
	FROM	S_THPEmployeePeriods WITH (NOLOCK)
	WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate And OUId = @OUId

	-- Retrieve Shift And Activity Counters Between Selected Shift Date
	SELECT	IsNull(SUM(ShiftCounter),0) ShiftCounter, IsNull(SUM(ActivityCounter),0) ActivityCounter, EmployeeId 	 
	FROM	S_THPEmployeeDetails WITH (NOLOCK)
	WHERE	CONVERT(date,ShiftDate) >= (SELECT	TOP 1 PeriodStart FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate And OUId	=	@OUId)
	AND		CONVERT(date,ShiftDate) <= (SELECT	TOP 1 PeriodEnd FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate And OUId	=	@OUId)
	GROUP BY EmployeeId

	-- Retrieve Activity Counter Values By Skill And Employee [Enables To Calculate Employee Skill THP Counters]
	;WITH THPPeriodRows (PeriodStart, PeriodEnd)
	AS
	(
		SELECT	Min(PeriodStart) PeriodStart,
				Max(PeriodEnd)	PeriodEnd
		FROM	S_THPEmployeePeriods WITH (NOLOCK)
		WHERE	S_THPEmployeePeriods.OUId	=	@OUId
		AND		CONVERT(Date,PeriodEnd)		>=	@ShiftDate 
		AND		CONVERT(Date,PeriodStart)	<=	@ShiftDate
	)
	SELECT	IsNull(SUM(ActivityCounter),0) ActivityCounter, EmployeeId, SkillId
	FROM	S_THPEmployeeSkillDetails WITH (NOLOCK)
	WHERE	Convert(Date,ShiftDate) >= (SELECT PeriodStart From THPPeriodRows)
	AND		Convert(Date,ShiftDate) <= (SELECT PeriodEnd From THPPeriodRows)
	GROUP BY EmployeeId, SkillId

	--Retrieve Shift And Activity Counters From Previous Period And Use Them Only If Deployment Date Is First Day Of Current Period
	;WITH PreviousPeriodLastDate (EndDate)
	AS
	(
		SELECT	DateAdd(DD, -1, Min(PeriodStart)) PreviousPeriod
			FROM	S_THPEmployeePeriods WITH (NOLOCK)
			WHERE	S_THPEmployeePeriods.OUId	=	@OUId
			AND		CONVERT(Date,PeriodEnd)		>=	@ShiftDate
			AND		CONVERT(Date,PeriodStart)	<=	@ShiftDate
	), 
	PeriodStartAndEnd AS
	( SELECT	Min(PeriodStart) PeriodStart,
					Max(PeriodEnd)	PeriodEnd
			FROM	S_THPEmployeePeriods WITH (NOLOCK)
			WHERE	S_THPEmployeePeriods.OUId	=	@OUId
			AND		CONVERT(Date,PeriodEnd)		>=	(SELECT EndDate From PreviousPeriodLastDate) 
			AND		CONVERT(Date,PeriodStart)	<=	(SELECT EndDate From PreviousPeriodLastDate)
	)
	--SELECT PeriodStart, PeriodEnd From PeriodStartAndEnd
	SELECT	IsNull(SUM(ShiftCounter),0) ShiftCounter, IsNull(SUM(ActivityCounter),0) ActivityCounter, EmployeeId 	 
	FROM	S_THPEmployeeDetails WITH (NOLOCK)
	WHERE	CONVERT(date,ShiftDate) >= (SELECT PeriodStart From PeriodStartAndEnd)
	AND		CONVERT(date,ShiftDate) <= (SELECT PeriodEnd From PeriodStartAndEnd)
	GROUP BY EmployeeId


	-- Retrieve Employee Crane Condition THP Counters For Weightage Calculation By THP Period
	SELECT	thpCraneCondition.CraneConditionTypeId,
			thpCraneCondition.EmployeeId,
			thpCraneCondition.THPPeriodId,
			thpCraneCondition.TransId,
			thpCraneCondition.StartDate,
			thpCraneCondition.EndDate,
			thpCraneCondition.Occurrence
	FROM	S_THPEmployeeCraneConditionCounter thpCraneCondition WITH (NOLOCK) 
			INNER JOIN S_THPEmployeePeriods thpEmployee WITH (NOLOCK) ON thpCraneCondition.EmployeeId = thpEmployee.EmployeeId
			AND	thpCraneCondition.THPPeriodId = thpEmployee.THPPeriodId
	WHERE	Convert(Date,PeriodEnd)		>=	Convert(Date,@ShiftDate) 
	AND		Convert(Date,PeriodStart)	<=	Convert(Date,@ShiftDate)
	AND		thpEmployee.OUId			=	@OUId

	-- Retrieve Employee Equipment THP Counter For Total Hour Period
	SELECT	thpEmpEquipment.EmployeeId, thpEmpEquipment.EquipmentId,
			SUM(thpEmpEquipment.ActivityCounter) ActivityHours,
			IsNull(M_EquipmentBrands.BrandNameId,0) BrandNameId
	FROM	S_THPEmployeeEquipmentDetails thpEmpEquipment WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = thpEmpEquipment.EmployeeId
			--INNER JOIN S_THPEmployeePeriods thpEmployee WITH (NOLOCK) ON thpEmployee.THPPeriodId = thpEmpEquipment.THPPeriodId
			INNER JOIN M_EquipmentBrands WITH (NOLOCK) ON M_EquipmentBrands.EquipmentId = thpEmpEquipment.EquipmentId 
	WHERE	C_Employee.OUId			=	@OUId
	GROUP BY thpEmpEquipment.EmployeeId, thpEmpEquipment.EquipmentId, IsNull(M_EquipmentBrands.BrandNameId,0)

	-- Retrieve Eligible Equipment Brands For Current Shift	
	;WITH LastEqBrand AS 
	(
		SELECT	EmployeeId, 
				CASE WHEN IsNull(M_EquipmentBrands.BrandNameId,0) + 1 > 3 THEN 1 ELSE IsNull(M_EquipmentBrands.BrandNameId,0) + 1 END BrandId,
				ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY ShiftDate DESC) RowId  
		FROM	S_THPEmployeeEquipmentDetails thpEmpEquipment WITH (NOLOCK) 
				INNER JOIN M_EquipmentBrands WITH (NOLOCK) ON M_EquipmentBrands.EquipmentId = thpEmpEquipment.EquipmentId 
		WHERE	Convert(Date,ShiftDate) < Convert(Date,@ShiftDate)
	)
	SELECT EmployeeId, BrandId FROM LastEqBrand WITH (NOLOCK)  
	WHERE	RowId = 1
END

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,
	@ShiftBandTypeId	Int
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	Convert(DateTime, ShiftEndTime) >= CONVERT(DATETIME, @ShiftStartTime) 
AND		Convert(DateTime, ShiftStartTime) <= CONVERT(DATETIME, @ShiftEndTime) -- OR S_Shifts.ShiftBandId = S_Shifts.CombinationShiftId)
AND		S_Shifts.OUId = @OUId
AND		C_Employee.ActiveStatus = 1
AND		(S_Shifts.ShiftBandId	=	@ShiftBandId OR @ShiftBandId = 0)
AND		SHIFTID NOT IN (SELECT SHIFTID FROM S_EmployeeLeaves Where ShiftId Is Not Null)
AND		S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftStartTime))
AND		S_Shifts.ShiftId NOT  IN (
											SELECT	ShiftId
											FROM	S_ShiftExceptions WITH (NOLOCK)
											WHERE	Convert(Date, StartTime) = Convert(Date, @ShiftStartTime)
									 )
AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

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) 
AND		S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftStartTime))
AND		S_Shifts.ShiftId NOT  IN (
											SELECT	ShiftId
											FROM	S_ShiftExceptions WITH (NOLOCK)
											WHERE	Convert(Date, StartTime) = Convert(Date, @ShiftStartTime)
									 )
AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

-- 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
AND		C_Employee.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftStartTime))
AND		C_Employee.EmployeeId NOT IN (	SELECT EmployeeId FROM S_EmployeeLeaves  WITH (NOLOCK)
										WHERE Convert(Date,@ShiftStartTime) = Convert(Date,FromDate) 
									 ) 
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetSkillsByEquipmentTypeAndActGenId')
	DROP PROCEDURE prJ_GetSkillsByEquipmentTypeAndActGenId
GO

CREATE PROCEDURE prJ_GetSkillsByEquipmentTypeAndActGenId
(
	@EquipmentTypes			nVarchar(500),
	@OUId					BigInt,
	@RequiredCraneType		Bit,
	@ActivityGenerationId	BigInt
)
AS
BEGIN
	-- Retrieve List Of Available Skills By Selected Equipment Types Including Crane Type If Selected
	IF (@RequiredCraneType = 1)
	BEGIN
		SELECT  M_Crane_Requirement.SkillId, D_Skill.Skill SkillCode, D_Skill.FixedRanking SkillRanking 
		FROM	M_Crane_Requirement WITH (NOLOCK)
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_Crane_Requirement.SkillId
		WHERE	M_Crane_Requirement.OUId	=	@OUId
		UNION
		SELECT	M_EquipmentType_Requirement.SkillId, D_Skill.Skill SkillCode, D_Skill.FixedRanking SkillRanking
		FROM	M_EquipmentType_Requirement WITH (NOLOCK) 
				INNER JOIN M_EquipmentType WITH (NOLOCK) 
					ON M_EquipmentType_Requirement.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_EquipmentType_Requirement.SkillId
		WHERE	M_EquipmentType.OUId	=	@OUId
		AND		M_EquipmentType.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes))
	END
	ELSE
	BEGIN
		SELECT	M_EquipmentType_Requirement.SkillId, D_Skill.Skill SkillCode, D_Skill.FixedRanking SkillRanking
		FROM	M_EquipmentType_Requirement WITH (NOLOCK) 
				INNER JOIN M_EquipmentType WITH (NOLOCK) 
					ON M_EquipmentType_Requirement.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
				INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_EquipmentType_Requirement.SkillId
		WHERE	M_EquipmentType.OUId	=	@OUId
		AND		M_EquipmentType.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes))
	END

	-- Retreive List Of Skills By Selected Activity Generation Rule Id
	SELECT	D_ReliefRuleSkill.SkillId, D_Skill.Skill SkillCode, D_Skill.FixedRanking SkillRanking
	FROM	D_ReliefRuleSkill WITH (NOLOCK) 
			INNER JOIN D_ReliefRule WITH (NOLOCK) ON D_ReliefRule.RuleId = D_ReliefRuleSkill.RuleId
			INNER JOIN D_Skill WITH (NOLOCK) ON D_ReliefRuleSkill.SkillId = D_Skill.SkillId
	WHERE	D_ReliefRule.RuleId		=	@ActivityGenerationId
	AND		D_ReliefRule.OUId		=	@OUId
END
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_GetSlashedCranesByDate')
	DROP PROC prJ_GetSlashedCranesByDate
GO

----------------------------------------------------------------------------
-- Retrieve Data From Activity Details By Allocation Details
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_GetSlashedCranesByDate]
(
	@ShiftDate		DateTime,
	@ShiftBandId	BigInt
)	
AS	
BEGIN
	SELECT	SlashedCraneId,
			ShiftDate,
			J_SlashedCranes.ShiftBandId,
			J_SlashedCranes.SkillId,
			ActivityStart,
			ActivityEnd,
			J_SlashedCranes.CraneScheduleId,
			GroupNumber,
			M_Cranes.CraneNumber,
			J_SlashedCranes.CraneId,
			IsSlashed,
			J_Workload.WorkloadId,
			M_CraneSchedule.CranePriorityId,
			D_MasterCodes.CodeValue CranePriority,
			IsNull(J_Workload.LocationId,0) LocationId,
			Convert(nVarchar(50),SlashedCraneId) id,
			M_Cranes.CraneNumber + ' ' + Convert(nVarchar(50),ActivityStart,120)  + ' ' + Convert(nVarchar(50),ActivityEnd,120)   text
	FROM	J_SlashedCranes WITH (NOLOCK) 
			INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = J_SlashedCranes.CraneScheduleId
			INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId
			INNER JOIN D_MasterCodes WITH (NOLOCK) ON M_CraneSchedule.CranePriorityId = D_MasterCodes.CodeId
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
	WHERE	Convert(Date,ShiftDate) = Convert(Date,@ShiftDate)
	AND		J_SlashedCranes.ShiftBandId = @ShiftBandId	
	AND		J_Workload.SkillId = 1
END
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_GetStackersFinalBookingReport')
	DROP PROCEDURE prJ_GetStackersFinalBookingReport
GO

CREATE PROC prJ_GetStackersFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@OUId				BigInt,
	@ReliefBreakId		BigInt,
	@EquipmentTypeName	nVarchar(100),
	@EquipmentTypeId	nVarchar(100),
	@SkillIds			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS
	-- Retrieve Shift Details
	WITH ShiftDetails AS (
		SELECT	 S_Shifts.ShiftId, 
				J_Activity.StartTime BookingDate, 
				S_Shifts.EmployeeId, 
				J_Activity.SkillId,
				ISNULL(S_SHifts.Notes,'') Notes,
				C_Employee.EmployeeNumber,	
				C_Employee.DisplayName EmployeeName, 
				M_EquipmentSchedule.EquipmentId,
				M_Equipments.EquipmentName,
				M_EquipmentType.EquipmentType,
				IsNull(J_Activity.RBRRank,'A') DeployedRank,
				S_Shifts.RBRRank LiveRank, 
				J_Activity.SkillId DeployedSkillId,
				D_Skill.Skill DeployedSkillName,
				J_Activity.ActivityId,
				J_Activity.WorkType,
				D_Roles.RoleName,
				D_ShiftBand.ShiftBandCode,
				S_Shifts.ActualStartTime ShiftActualStart,
				S_Shifts.ActualEndTime ShiftActualEnd,
				D_Roles.RoleId,
				J_Activity.AllocationNo,
				ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId 
		FROM	S_Shifts   WITH (NOLOCK) 
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
				INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
				LEFT OUTER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK)  ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
				LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
				INNER JOIN D_Skill  WITH (NOLOCK)  ON D_Skill.SkillId = J_Activity.SkillId
				INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			    INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
				INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 	
		AND		S_Shifts.OUId =	@OUId
		AND		J_Activity.SkillId	!= @ReliefBreakId
		AND		(J_Activity.SkillId		IN (SELECT * FROM fnStringToTable(@SkillIds)))
		And		M_EquipmentType.EquipmentType IN (SELECT * FROM fnStringToTable(@EquipmentTypeName))
		And		(M_EquipmentType.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypeId)) OR @EquipmentTypeId='') 
	)
	SELECT * FROM ShiftDetails WITH (NOLOCK)  
	WHERE	RowId = 1

	--Over Time  Details
		SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	

	-- Retrieve Skills For Fixed Ranking Grouping
	SELECT	D_Skill.SkillId,D_Skill.Skill SkillName, D_SKill.FixedRanking
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK) ON D_Skill.SkillId = D_SkillOU.SkillId
	WHERE	D_SkillOU.OUId	=	@OUId
	AND		D_Skill.FixedRanking IS NOT NULL

	
	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				Equipments.EquipmentName,
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1			
			LEFT JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
    AND		(C_EmployeeSkills.SkillId	IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_Skill.Skill DeployedSkillName,
					Equipments.EquipmentId,					
					--iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
					Equipments.EquipmentName,
					M_EquipmentType.EquipmentType,
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					--INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					--LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					--LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					LEFT OUTER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
					INNER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.DeployedSkillName,
			NonPrimarySkillActivity.EquipmentId,
			NonPrimarySkillActivity.EquipmentName,
			NonPrimarySkillActivity.EquipmentType
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			EquipmentWorkLoad.EquipmentScheduleId,
	        Equipments.EquipmentName,
			Equipments.EquipmentId,
			M_EquipmentType.EquipmentType,
			IsNull(J_Activity.RBRRank,'A') DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			D_Skill.Skill DeployedSkillName
	FROM    J_Activity  WITH (NOLOCK)			
			LEFT JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId  
			LEFT JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId 
			LEFT JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = M_EquipmentSchedule.EquipmentTypeId
			LEFT OUTER JOIN D_Skill  WITH (NOLOCK) ON D_Skill.SkillId = J_Activity.SkillId
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)
	--AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 

GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetStandByEmployeeDetail')
	DROP PROCEDURE prJ_GetStandByEmployeeDetail
GO

CREATE PROC prJ_GetStandByEmployeeDetail
 (
	@ShiftDate			DateTime,
	@OUId				BigInt,
	@ShiftId			BigInt,
	@ReliefBreakId		BigInt,
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS

	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @ShiftDate)		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandId,
			D_Roles.RoleId,
			StandbyEmployeeActivity.DeployedSkillId,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			C_Employee.EmployeeId id,
			C_Employee.EmployeeNumber + ' - ' + Replace(LTRIM(RTRIM(C_Employee.DisplayName)),'-','') + ' - ' + D_Roles.RoleName [text]
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId --AND C_EmployeeSkills.IsPrimary = 1  
			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 = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @ShiftDate)	
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
	AND		C_EmployeeSkills.SkillId IN (SELECT SKILLID FROM J_Activity WITH (NOLOCK) WHERE ShiftId = @ShiftId)
    AND		S_Shifts.ShiftBandId IN (SELECT ShiftBandId FROM S_Shifts WITH (NOLOCK) WHERE ShiftId = @ShiftId)
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@ShiftDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@ShiftDate)

	
	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@ShiftDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@ShiftDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId

	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 
GO


IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetStandByEmployeeDetailBySkillAndShiftBand')
	DROP PROCEDURE prJ_GetStandByEmployeeDetailBySkillAndShiftBand
GO

CREATE PROC prJ_GetStandByEmployeeDetailBySkillAndShiftBand
 (
	@ShiftDate			DateTime,
	@OUId				BigInt,
	@ShiftBandId		BigInt,
	@SkillId			BigInt,
	@ReliefBreakId		BigInt,
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS

	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @ShiftDate)		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
		
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			D_Roles.RoleName,
			D_ShiftBand.ShiftBandId,
			D_Roles.RoleId,
			StandbyEmployeeActivity.DeployedSkillId,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			C_Employee.EmployeeId id,
			C_Employee.EmployeeNumber + ' - ' + Replace(LTRIM(RTRIM(C_Employee.DisplayName)),'-','') + ' - ' + D_Roles.RoleName [text]
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId --AND C_EmployeeSkills.IsPrimary = 1  
			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 = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date, @ShiftDate)	
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
	AND		C_EmployeeSkills.SkillId = @SkillId
    AND		S_Shifts.ShiftBandId = @ShiftBandId
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@ShiftDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@ShiftDate)

	
	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@ShiftDate)
	--AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@ShiftDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId

	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 
GO


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

----------------------------------------------------------------------------
-- Insert a single record into prJ_GetWorkingRTGInLastXMins
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkingRTGInLastXMins
AS
DECLARE @WorkingRTGConfigMins int = 60;
BEGIN
	SELECT  @WorkingRTGConfigMins = Convert(int, ParamValue)
	FROM	D_SystemParams WITH (NOLOCK)
	WHERE	D_SystemParams.ParamName = 'RetriveWorkingRTGRageMins'

	SELECT DISTINCT EquipmentName 
	FROM	M_EmployeeEquipmentLogin WITH (NOLOCK)
	WHERE	Convert(DateTime,ClockOutDateTime) > Convert(DateTime,DATEADD(MINUTE, -@WorkingRTGConfigMins,GETDATE())) --Convert(DateTime,'2022-09-04 17:30:00')
	AND		Convert(DateTime,ClockInDateTime) <  Convert(DateTime,GETDATE()) --Convert(DateTime,'2022-09-04 18:30:00')
END
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,
		VesselScheduleId,
		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,
	@ShiftBandId nVarchar(max)
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))
AND		(J_Workload.ShiftBandId IN (SELECT  * From fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')

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_GetWorkloadDetailByWorkloadId')
	DROP PROC prJ_GetWorkloadDetailByWorkloadId
GO
----------------------------------------------------------------------------
-- Select a single record from J_Workload
----------------------------------------------------------------------------
CREATE PROC prJ_GetWorkloadDetailByWorkloadId
	@WorkloadId bigint
AS

SELECT	WorkloadId,
		OUId,
		SkillId,
		StartTime,
		EndTime,
		WorkType,
		CraneScheduleId,
		EquipmentScheduleId,
		ShiftBandId,
		ScheduleId,
		Imported,
		WorkloadGenerated,
		SignOffStatus
		
FROM	J_Workload WITH (NOLOCK)
WHERE 	WorkloadId = @WorkloadId

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_GetWorkloadType')
	DROP PROC prJ_GetWorkloadType
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO
CREATE PROC prJ_GetWorkloadType
AS
BEGIN
	SELECT	Id,
			WorkLoadType		
	FROM	J_WorkloadType WITH (NOLOCK)
	

END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prJ_SlashedCranesIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prJ_SlashedCranesIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prJ_SlashedCranesIns]    
(
  @SlashedCranes UJ_SlashedCranes readonly
)
AS
BEGIN
    Merge	J_SlashedCranes as Target Using @SlashedCranes AS 
			Source ON (	Target.ShiftDate = Source.ShiftDate AND Target.ShiftBandId = Source.ShiftBandId AND 
						Target.ActivityStart = Source.ActivityStart AND Target.ActivityEnd = Source.ActivityEnd 
						AND Target.CraneScheduleId = Source.CraneScheduleId 
					  )	
	When Not Matched By Target Then
	Insert (ShiftDate, ShiftBandId, WorkloadId, ActivityStart, ActivityEnd, CraneScheduleId, GroupNumber, CraneId, IsSlashed, CreatedBy, CreatedDate)
	Values (Source.ShiftDate, Source.ShiftBandId, Source.WorkloadId, Source.ActivityStart, Source.ActivityEnd, Source.CraneScheduleId, Source.GroupNumber, Source.CraneId, 
			Source.IsSlashed, Source.CreatedBy, GETDATE());

	SELECT 1;
END

GO

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

----------------------------------------------------------------------------
-- Retrieve Data From Activity Details By Allocation Details
----------------------------------------------------------------------------
CREATE PROC [dbo].[prJ_SlashedCranesUpdate]
(
	@FirstCraneSlashId				BigInt,
	@SecondCraneSlashId				BigInt,
	@GroupNumber					BigInt,
	@UpdatedBy						nVarchar(100),
	@FirstAvailableCraneSlashId		BigInt,
	@SecondAvailableCraneSlashId	BigInt,
	@ShiftBandId					BigInt,
	@ShiftDate						DateTime
)	
AS	
BEGIN
	If(@FirstCraneSlashId != 0)
	BEGIN
		UPDATE	J_SlashedCranes
		SET		GroupNumber			=	@GroupNumber,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	SlashedCraneId		=	@FirstCraneSlashId
	END

	if(@SecondCraneSlashId != 0)
	BEGIN
		UPDATE	J_SlashedCranes
		SET		GroupNumber			=	@GroupNumber,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()
		WHERE	SlashedCraneId		=	@SecondCraneSlashId
	END

	If(@FirstAvailableCraneSlashId != @FirstCraneSlashId)
	BEGIN
		UPDATE	J_SlashedCranes
		SET		GroupNumber			=	(	SELECT	IsNull(Max(GroupNumber) ,0) + 1
											FROM	J_SlashedCranes WITH (NOLOCK) 
											WHERE	Convert(Date,ShiftDate) =	Convert(Date,@ShiftDate)
											AND		ShiftBandId				=	ShiftBandId
										)
		WHERE	SlashedCraneId		=	@FirstAvailableCraneSlashId
	END

	If(@SecondAvailableCraneSlashId != @SecondCraneSlashId)
	BEGIN
		UPDATE	J_SlashedCranes
		SET		GroupNumber			=	(	SELECT	IsNull(Max(GroupNumber) ,0) + 1
											FROM	J_SlashedCranes WITH (NOLOCK) 
											WHERE	Convert(Date,ShiftDate) =	Convert(Date,@ShiftDate)
											AND		ShiftBandId				=	ShiftBandId
										)
		WHERE	SlashedCraneId		=	@SecondAvailableCraneSlashId
	END

	SELECT 1;
END
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 BigInt = NULL,
	@UpdatedBy nvarchar(100) = NULL,
	@ProgressionState Int = 0,
	@WorkloadId			BigInt = 0,
	@EquipmentId BigInt
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,
	@SelectedSkills	nVarchar(1000) = NULL
	
AS
	If(@SelectedSkills IS NULL)
	BEGIN
		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
	END
	ELSE
	BEGIN
		UPDATE J_Activity 
		SET		ShiftId = 0,
				DeployedDate = NULL,
				DeployedUser = NULL,
				UpdatedBy	= @UpdatedBy,
				UpdatedDate = GETDATE(),
				ProgresstionState = 2
		WHERE	J_Activity.SkillId = (	SELECT	Convert(BigInt,ParamValue) 
										FROM	D_SystemParams WITH (NOLOCK) 
										WHERE	ParamName='ReliefBreakId'
									 )
		AND		J_Activity.WorkloadId IN (	SELECT	WorkloadId 
											FROM	J_Workload WITH (NOLOCK) 
											WHERE	J_Workload.OUId = @OUId
											AND		J_Workload.SkillId IN (SELECT * FROM fnStringToTable(@SelectedSkills)) OR @SelectedSkills IS NULL
											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)
										)
											

		UPDATE	J_Activity
		SET		ShiftId = 0,
				ProgresstionState = 2,
				DeployedDate = null,
				DeployedUser = null,	
				UpdatedBy = @UpdatedBy,
				UpdatedDate = GETDATE()
		WHERE 	ProgresstionState = 3
		AND		ShiftId > 0
		AND		(SkillId IN (SELECT * FROM fnStringToTable(@SelectedSkills)) OR @SelectedSkills IS NULL)
		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
	END

	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	IsNull(CombinationShiftId,0) != 0
	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	CombinationShiftId <> 0
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,
	@DeploymentNotes nVarchar(500) =  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(),
			DeploymentNotes		=	@DeploymentNotes
	WHERE	ShiftId				=	@ShiftId
	AND		IsNull(CombinationShiftId,0) != 0
	--AND		(CombinationShiftId	IS NOT NULL OR CombinationShiftId != 0)
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,
	@IsOnCallShift	Bit,
	@UpdatedBy		nVarchar(50),
	@IsReconcilied	Bit = 0
AS	
	IF(@IsReconcilied = 0)
	BEGIN
		UPDATE	S_Shifts
		SET		OnCallShift					=	@IsOnCallShift,
				ReconTime					=	Null,
				Reconciled					=	@IsReconcilied,
				ReconStatusId				=	null,
				ReconFailureReasonId		=	NULL,
				ReconFailureReasonDetail	=	NULL,
				RPGId						=	NULL,
				ActualStartTime				=	ShiftStartTime,
				ActualEndTime				=	ShiftEndTime,
				UpdatedBy	=	@UpdatedBy,
				UpdatedDate =	GETDATE()
		WHERE	ShiftId		=	@ShiftId

		SELECT 1
	END
	ELSE
	BEGIN
		UPDATE	S_Shifts
		SET		OnCallShift	=	@IsOnCallShift,
				UpdatedBy	=	@UpdatedBy,
				UpdatedDate =	GETDATE()
		WHERE	ShiftId		=	@ShiftId
		
		SELECT 1
	END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prJ_UpdateEmployeeRBRForDeAllocation')
	DROP PROC prJ_UpdateEmployeeRBRForDeAllocation
GO

CREATE PROCEDURE prJ_UpdateEmployeeRBRForDeAllocation
(
	@ShiftId	BigInt
)
AS
BEGIN
	DECLARE @EmployeeId BigInt = 0, @RBRRank nVarchar(2) = NULL

	SELECT	TOP 1 @EmployeeId = IsNull(EmployeeId,0), 
			@RBRRank	= IsNull(RBRRank,NULL)
	FROM	J_EmployeeShiftRBR WITH (NOLOCK)
	WHERE	ShiftId		< @ShiftId
	ORDER BY ShiftDate DESC

	If @RBRRank IS NOT NULL
	BEGIN
		UPDATE	J_EmployeeRBR 
		SET		RBRRank		=	@RBRRank
		WHERE	EmployeeId	=	@EmployeeId

		SELECT 1
	END
	ELSE
	BEGIN
		DELETE FROM J_EmployeeRBR WHERE EmployeeId = (SELECT EmployeeId From S_Shifts WITH (NOLOCK) Where ShiftId = @ShiftId)

		SELECT 1

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

CREATE PROC prJ_UpdateShiftEndTimeByCraneScheduleId
	@CraneScheduleId	BigInt,	
	@ShiftEndTime		DateTime,
	@UpdatedBy			nVarchar(100)
AS

;WITH ShiftDetails AS 
(
	SELECT	S_Shifts.ShiftId 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN J_Activity ON S_Shifts.ShiftId						=	J_Activity.ShiftId 
			INNER JOIN J_Workload ON J_Workload.WorkloadId					=	J_Activity.WorkloadId
			INNER JOIN M_CraneSchedule ON M_CraneSchedule.CraneScheduleId	=	J_Workload.CraneScheduleId
	WHERE	M_CraneSchedule.CraneScheduleId		=	@CraneScheduleId 
	GROUP BY S_Shifts.ShiftId
)
UPDATE	S_Shifts 
SET		ActualEndTime	=	@ShiftEndTime,
		UpdatedBy		=	@UpdatedBy,
		UpdatedDate		=	GETDATE() 
FROM	S_Shifts WITH (NOLOCK) 
		INNER JOIN ShiftDetails ON S_Shifts.ShiftId =	ShiftDetails.ShiftId	

SELECT 1

GO


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

CREATE PROC prJ_UpdateShiftEndTimeByEmployeeShiftId
	@EmployeeId bigint,	
	@ShiftId bigint,	
	@ShiftEndTime		DateTime,
	@UpdatedBy nvarchar(100)
AS

update S_Shifts set S_Shifts.ActualEndTime=@ShiftEndTime,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE()  where  S_Shifts.EmployeeId =@EmployeeId and ShiftId=@ShiftId


select 1

GO


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

CREATE PROC prJ_UpdateShiftEndTimeByVesselScheduleId
	@VesselScheduleId bigint,	
	@ShiftEndTime		DateTime,
	@UpdatedBy nvarchar(100)
AS

;with ShiftDetails as(
select S_Shifts.ShiftId from S_Shifts inner join J_Activity on S_Shifts.ShiftId =J_Activity.ShiftId 
inner join J_Workload on J_Workload.WorkloadId =J_Activity.WorkloadId
inner join M_CraneSchedule on M_CraneSchedule.CraneScheduleId=J_Workload.CraneScheduleId
inner join M_VesselSchedule on M_VesselSchedule.VesselScheduleId =M_CraneSchedule.VesselScheduleId
where  M_VesselSchedule.VesselScheduleId =@VesselScheduleId
group by S_Shifts.ShiftId)
update S_Shifts set S_Shifts.ActualEndTime=@ShiftEndTime,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE() from S_Shifts inner join ShiftDetails on
S_Shifts.ShiftId =ShiftDetails.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	IsNull(CombinationShiftId,0) = 0
	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,
		UpdatedDate = GETDATE()
	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_AddEmployeePanelClinic')
	DROP PROC prL_AddEmployeePanelClinic
GO

----------------------------------------------------------------------------
-- Insert a single record into prL_AddEmployeePanelClinic
----------------------------------------------------------------------------
CREATE PROC prL_AddEmployeePanelClinic
(
	@EmployeeId				BigInt,
	@PanelClinicId       	BigInt,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN

	INSERT INTO C_EmployeePanelClinics
	(EmployeeId, PanelClinicId, CreatedBy, CreatedDate)
	VALUES(@EmployeeId, @PanelClinicId, @CreatedBy, GETDATE())

	SELECT  CAST(@@Identity AS bigint) 

END
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),
	@PanelClinicId		BigInt,
	@HalfDayType        nVarchar(50) = NULL,
	@LieuDateId			BigInt = NULL
)
AS
DECLARE @ValidateDuplicate int = 0, @ReturnLeaveId BigInt = 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,PanelClinicId,HalfDayType)
	VALUES(@OuId, @EmployeeId, @ExceptionCodeId, @LeaveStart, @LeaveEnd, @LeaveType, @NoOfDays, @ReasonId, @IsEmergency, @ApprovalStatusId,
			@ReferenceNo, @Remarks, @AppliedBy, @AppliedDate, @ApprovedBy, @ApprovedDate, @CreatedBy, GETDATE(),@PanelClinicId,@HalfDayType)
		
	SET @ReturnLeaveId =  CAST(@@Identity AS bigint) 

	IF(@LieuDateId != 0) UPDATE L_EmployeeLieuDates SET LeaveId = @ReturnLeaveId, Utilized = 1 WHERE LieuDateId = @LieuDateId

	SELECT @ReturnLeaveId;
	
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_AddLeaveBalanceDiscrepancy]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_AddLeaveBalanceDiscrepancy]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prL_AddLeaveBalanceDiscrepancy]    
(
  @LeaveBalanceDiscrepancy UL_LeaveBalanceDiscrepancy readonly
)
AS
BEGIN
    Merge L_LeaveBalanceDiscrepancy as Target Using @LeaveBalanceDiscrepancy as Source ON 
		  (Target.LeaveBalanceDiscrepancyId = Source.LeaveBalanceDiscrepancyId)	
	When  Not Matched By Target Then
	Insert (EmployeeLeaveProfileId, UsedDaysFromMYERP, LMSBalanceDays, MYERPBalanceDays, CreatedBy, CreatedDate) 
	Values (Source.EmployeeLeaveProfileId, Source.UsedDaysFromMYERP,Source.LMSBalanceDays,Source.MYERPBalanceDays,
			Source.CreatedBy,GETDATE());
	
	SELECT 1
END
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),
	@IsHRApprovalRequired	Bit = 0,
	@PrimaryApprovers		nVarchar(max),
	@IsPanelClinicRequired	Bit,
	@IsAttachmentRequired 	Bit,
	@IsFutureDateAllowed    Bit,
	@IsBackDateAllowed      Bit
)
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, IsHRApprovalRequired, PrimaryApprovers,IsPanelClinicRequired,IsAttachmentRequired,IsFutureDateAllowed,IsBackDateAllowed)
		VALUES(@LeaveProfileHeaderId, @ExceptionCodeId, @EntitlementDays, @CarryForward, @MaximumDaysPerYear, @Accural,
			   @CarryForwardDateType, @CarryForwardDate, @DayCalculation, @DaysInAdvance, @MinimumDaysRequest,
			   @MaximumDaysRequest, @RequestPerYear, @NegativeBalance, @MaximumDaysNegative, @HalfDays, 
			   @ActiveStatus, @CreatedBy, GETDATE(), @IsHRApprovalRequired, @PrimaryApprovers,@IsPanelClinicRequired,@IsAttachmentRequired,@IsFutureDateAllowed,@IsBackDateAllowed)

		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),
	@LieuDateId			BigInt = NULL
)
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	
	IF(@LieuDateId != 0) UPDATE L_EmployeeLieuDates SET  Utilized = 0 WHERE LieuDateId = @LieuDateId
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 WITH (NOLOCK)
	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
/****** Object:  StoredProcedure [dbo].[prL_DeleteEmployeePanelClinic]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prL_DeleteEmployeePanelClinic') AND type in (N'P', N'PC'))
DROP PROCEDURE prL_DeleteEmployeePanelClinic
GO

CREATE PROCEDURE prL_DeleteEmployeePanelClinic
(
	@EmployeePanelClinicId	BigInt
)
AS
BEGIN
	  DELETE FROM C_EmployeePanelClinics WHERE EmployeePanelClinicId = @EmployeePanelClinicId

	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_EmailTemplateSel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_EmailTemplateSel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_EmailTemplateSel]    
(
	@FunctionId	 bigInt 
)
AS
BEGIN
	SELECT D_EmailTemplate.FunctionId,
	       D_EmailTemplate.LanguageId,
		   D_EmailTemplate.MailBody,
		   D_EmailTemplate.MailCC,
		   D_EmailTemplate.MailFrom,
		   D_EmailTemplate.MailSubject,
		   D_EmailTemplate.SaveLog,
		   D_EmailTemplate.ActiveStatus,
		   D_EmailTemplate.AvailableOptions
	FROM   D_EmailTemplate WITH(NOLOCK)
	WHERE  D_EmailTemplate.FunctionId = @FunctionId	 
END
go


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_EmployeeLeaveProfileCreateorUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_EmployeeLeaveProfileCreateorUpdate]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prL_EmployeeLeaveProfileCreateorUpdate]    
(
  @LeaveAccrual UL_EmployeeLeaveProfiles readonly
)
AS
BEGIN
    Merge L_EmployeeLeaveProfiles as Target Using @LeaveAccrual as Source ON 
		  (Target.EmployeeId = Source.EmployeeId AND Target.ExceptionId = Source.ExceptionId AND Target.LeaveYear = Source.LeaveYear)	
	When  Not Matched By Target Then
	Insert (EmployeeId,LeaveProfileId,StartDate,EndDate, LeaveYear, ExceptionId, EntitlementDays, CarryForwardDays, EarnedDays, DaysUsed, 
	        AdjustDays, DaysLieu, UsedDays,BalanceDays,EarnedDays_Cal,EarnedDays_Adj,EarnedMonth,AdjustmentRemakrs,CreatedBy,CreatedDate) 
	Values (Source.EmployeeId, Source.LeaveProfileId,Source.StartDate,Source.EndDate,Source.LeaveYear, Source.ExceptionId, Source.EntitlementDays,
			Source.CarryForwardDays,Source.EarnedDays,Source.DaysUsed,Source.AdjustDays,Source.DaysLieu,Source.UsedDays,Source.BalanceDays,
			Source.EarnedDays_Cal,Source.EarnedDays_Adj,Source.EarnedMonth,Source.AdjustmentRemakrs,Source.CreatedBy,GETDATE()
			)
	When Matched Then
	Update Set  Target.EntitlementDays		=	Source.EntitlementDays,
				Target.CarryForwardDays		=	Source.CarryForwardDays,
				Target.EarnedMonth          =   Source.EarnedMonth,
				Target.DaysUsed             =   Source.DaysUsed,
				Target.AdjustDays           =   Source.AdjustDays,
				Target.EarnedDays           =   Source.EarnedDays,
				Target.BalanceDays          =   Source.BalanceDays,
				Target.UpdatedBy            =   Source.UpdatedBy,
	    		Target.UpdatedDate		    =	GETDATE();	
	SELECT 1
END
GO






IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_EmployeeLieuDates]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_EmployeeLieuDates]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prL_EmployeeLieuDates]  
(
  @EmployeeLieuDates UL_EmployeeLieuDates readonly
)
AS
BEGIN
    Merge L_EmployeeLieuDates as Target Using @EmployeeLieuDates as Source ON 
		  (Target.EmployeeId = Source.EmployeeId AND Convert(Date,Target.LieuDate) = Convert(Date,Source.LieuDate)	)
	When  Not Matched By Target Then
	Insert (EmployeeId, LieuDate, Utilized, CreatedBy, CreatedDate) 
	Values (Source.EmployeeId, Source.LieuDate,Source.Utilized, Source.CreatedBy, GETDATE())
	When Matched Then
	Update Set  Target.Utilized				=	Source.Utilized,
				Target.UpdatedBy            =   Source.UpdatedBy,
	    		Target.UpdatedDate		    =	GETDATE();
				
	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 WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_Leaves.EmployeeId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = L_Leaves.OUId
				LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) 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 WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_Leaves.EmployeeId
				INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = L_Leaves.OUId
				LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) 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 IN (1,7) --= @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 sysobjects WHERE name = 'prL_GetDaysInLieuByEmployeeId')
	DROP PROC prL_GetDaysInLieuByEmployeeId
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 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 OR @EmployeeId = 0)
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetDaysInLieuByEmployeeIdDate')
	DROP PROC  prL_GetDaysInLieuByEmployeeIdDate
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 PROCEDURE  [dbo].[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 D_ExceptionCodes WITH (NOLOCK) ON L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_EmployeeLeaveProfiles.EmployeeId
			INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) ON L_LeaveProfileHeader.LeaveProfileHeaderId = L_EmployeeLeaveProfiles.LeaveProfileId
			-- L_EmployeeLeaveProfiles.LeaveProfileId => LeaveProfileId  Is not L_LeaveProfiles.LeaveProfileId instead link with L_LeaveProfileHeader.LeaveProfileHeaderId
	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
	AND     L_Leaves.ExceptionCodeId = @ExceptionCodeId

	--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 WITH (NOLOCK))
		AND		D_Roles.RoleGroupId = (SELECT CurrentEmployeeRoleGroup.RoleGroupId From CurrentEmployeeRoleGroup WITH (NOLOCK))
	)
	SELECT COUNT(*) TotalEmployeesByRosterAndRoleGroups FROM EmployeeListByRosterGroupAndRoleGroups WITH (NOLOCK)

	-- 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)

	--15 Get Primary Approvers (Required to Send to HR First Before The Usual Approval Route Takes Place)
	DECLARE @PrimaryApprovers nVarchar(max)
	SELECT	@PrimaryApprovers = IsNull(L_LeaveProfiles.PrimaryApprovers,'') 
	FROM	L_EmployeeLeaveProfiles WITH (NOLOCK) 
			INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileHeaderId
			AND		L_Leaveprofiles.ExceptionCodeId = @ExceptionCodeId
	Where	EmployeeId = @EmployeeId And LeaveYear = @EntitlementYear And L_EmployeeLeaveProfiles.ExceptionId = @ExceptionCodeId

	SELECT	C_Employee.EmployeeId,
			0 RouteLevel,
			1 ApprovalRequirement,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			IsNull(C_Employee.EmailAddress,'') ApproverEmailId,
			0 RouteId,
			0 ModuleId
	FROM	C_Employee WITH (NOLOCK) 
	WHERE	EmployeeId IN (SELECT * FROM fnStringToTable(@PrimaryApprovers))

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.LeaveProfileHeaderId
		--			AND L_LeaveProfiles.ActiveStatus = 1 AND L_LeaveProfiles.ExceptionCodeId = L_EmployeeLeaveProfiles.ExceptionId
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,
		L_LeaveProfiles.DayCalculation
FROM	L_EmployeeLeaveProfiles WITH (NOLOCK) 
		INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_EmployeeLeaveProfiles.EmployeeId
		INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) ON L_LeaveProfileHeader.LeaveProfileHeaderId = L_EmployeeLeaveProfiles.LeaveProfileId
		INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_LeaveProfileHeader.LeaveProfileHeaderId = L_LeaveProfiles.LeaveProfileHeaderId
		AND L_EmployeeLeaveProfiles.ExceptionId = L_LeaveProfiles.ExceptionCodeId
		-- L_EmployeeLeaveProfiles.LeaveProfileId => LeaveProfileId  Is not L_LeaveProfiles.LeaveProfileId instead link with L_LeaveProfileHeader.LeaveProfileHeaderId
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	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_Cal,
		L_EmployeeLeaveProfiles.EarnedDays_Adj,
		L_EmployeeLeaveProfiles.EarnedMonth,
		L_EmployeeLeaveProfiles.AdjustmentRemakrs		
FROM	L_EmployeeLeaveProfiles WITH (NOLOCK) 		
WHERE 	EmpProfileId = @EmpProfileId or @EmpProfileId = 0

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 WITH (NOLOCK)
									Where	Convert(Date,EndDate) >= Convert(Date,@Date) 
									And		Convert(Date,StartDate) <= Convert(Date,@date)
									And     ExcludeAccrualProcess = 1
								)
--AND	C_Employee.EmployeeId= 1161
AND C_Employee.ActiveStatus = 1
--And C_Employee.EmployeeNumber= '14-01239' --'14-00966'--'14-01234'
--AND		C_EMployee.EmployeeNumber='14-00196'
GO

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

CREATE PROC prL_GetEmployeePanelDetailsByEmployeeId
	@EmployeeId	BigInt
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName,
		   Employee.OUId, 
		   OrgNode.OUName, 
		   PanelClinic.PanelClinicName,
           EmployeePanelClinic.PanelClinicId,
		   EmployeePanelClinic.EmployeePanelClinicId		  
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
		   LEFT OUTER JOIN C_EmployeePanelClinics EmployeePanelClinic WITH (NOLOCK) ON EmployeePanelClinic.EmployeeId = Employee.EmployeeId
	       LEFT OUTER JOIN D_PanelClinics PanelClinic WITH (NOLOCK) ON PanelClinic.PanelClinicId = EmployeePanelClinic.PanelClinicId		  
	WHERE  EmployeePanelClinic.EmployeeId = @EmployeeId
END
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,
	@ExceptionCodeId	BigInt = 0
AS
BEGIN
	--5 Get Approvers List By Employee Leave Profile
	SELECT	W_WorkflowRouteDetails.EmployeeId,
			W_WorkflowRouteDetails.RouteLevel,
			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

	DECLARE @PrimaryApprovers nVarchar(max)
	SELECT	@PrimaryApprovers = IsNull(L_LeaveProfiles.PrimaryApprovers,'') 
	FROM	L_EmployeeLeaveProfiles WITH (NOLOCK) 
			INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileHeaderId
			AND		L_Leaveprofiles.ExceptionCodeId = @ExceptionCodeId
	Where	EmployeeId = @EmployeeId And LeaveYear = YEAR(GETDATE()) And L_EmployeeLeaveProfiles.ExceptionId = @ExceptionCodeId

	SELECT	C_Employee.EmployeeId,
			0 RouteLevel,
			1 ApprovalRequirement,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			IsNull(C_Employee.EmailAddress,'') ApproverEmailId,
			0 RouteId,
			0 ModuleId
	FROM	C_Employee WITH (NOLOCK) 
	WHERE	EmployeeId IN (SELECT * FROM fnStringToTable(@PrimaryApprovers))
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_GetExceptionCodeByEmployeeId')
	DROP PROC prL_GetExceptionCodeByEmployeeId
GO

CREATE PROC prL_GetExceptionCodeByEmployeeId
(
	@EmployeeId			BigInt
)
AS
BEGIN

	SELECT Distinct	L_EmployeeLeaveProfiles.EmployeeId,
			L_LeaveProfiles.ExceptionCodeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
			D_ExceptionCodes.ExceptionCodeDesc,	
			L_LeaveProfiles.HalfDays,		
			L_LeaveProfiles.IsPanelClinicRequired,
			L_LeaveProfiles.IsAttachmentRequired,
			L_LeaveProfiles.IsFutureDateAllowed,
			L_LeaveProfiles.IsBackDateAllowed
	FROM    L_EmployeeLeaveProfiles WITH (NOLOCK) 
	        INNER JOIN L_LeaveProfiles WITH (NOLOCK) ON L_EmployeeLeaveProfiles.LeaveProfileId = L_LeaveProfiles.LeaveProfileHeaderId
			AND L_EmployeeLeaveProfiles.ExceptionId = L_LeaveProfiles.ExceptionCodeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_EmployeeLeaveProfiles.ExceptionId
			INNER JOIN C_EmployeeLeaveProfile WITH (NOLOCK) ON  C_EmployeeLeaveProfile.LeaveProfileHeaderId = L_EmployeeLeaveProfiles.LeaveProfileId
			AND C_EmployeeLeaveProfile.EmployeeId = L_EmployeeLeaveProfiles.EmployeeId 			
			AND CONVERT(date,C_EmployeeLeaveProfile.EndDate) >= Convert(date,GETDATE())
			AND CONVERT(date,C_EmployeeLeaveProfile.StartDate) <= CONVERT(date,GETDATE())
	WHERE   L_EmployeeLeaveProfiles.EmployeeId = @EmployeeId 
	        AND D_ExceptionCodes.ESS = 1
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 WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_LeaveBalanceAudit.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) 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_GetLeaveEntitlementDetail')
	DROP PROCEDURE prL_GetLeaveEntitlementDetail
GO

CREATE PROC prL_GetLeaveEntitlementDetail
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@OUId				BigInt,
	@RoleGroupId		nVarchar(100),
	@RosterGroupId		nVarchar(100)
)
AS
--AL & Other Leaves

SELECT		D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			S_EmployeeLeaves.ExceptionCodeId,
			S_EmployeeLeaves.FromDate LeaveDate,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
			Count(D_RoleGroup.RoleGroupId) TotalCount
FROM		S_EmployeeLeaves  WITH(NOLOCK)
			INNER JOIN D_ExceptionCodes WITH(NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId =  D_ExceptionCodes.ExceptionCodeId
			INNER JOIN C_Employee WITH(NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId
			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
			INNER JOIN D_RoleGroup WITH(NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			INNER JOIN S_RosterGroup WITH(NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
WHERE		Convert(Date,S_EmployeeLeaves.FromDate) >= CONVERT(Date,@StartDate)
AND			Convert(Date,S_EmployeeLeaves.EndDate) <= CONVERT(Date,@EndDate)
AND			S_EmployeeLeaves.OUId = @OUId
AND		    (D_RoleGroup.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId='0')
AND		    (S_RosterGroup.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId='0')
GROUP BY	D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			S_EmployeeLeaves.ExceptionCodeId,
			S_EmployeeLeaves.FromDate,
			D_ExceptionCodes.ExcpetionCodeName
--UCL Leave
SELECT		L_UCL.UCLDate,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			Count(D_RoleGroup.RoleGroupId) TotalCount
FROM		L_UCL WITH(NOLOCK)
			INNER JOIN D_ExceptionCodes WITH(NOLOCK) ON L_UCL.ExceptionCodeId =  D_ExceptionCodes.ExceptionCodeId
			INNER JOIN C_Employee WITH(NOLOCK) ON C_Employee.EmployeeId = L_UCL.EmployeeId
			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
			INNER JOIN D_RoleGroup WITH(NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			INNER JOIN S_RosterGroup WITH(NOLOCK) ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
WHERE		Convert(Date,L_UCL.UCLDate) >= Convert(Date,@StartDate)
AND			Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)
AND			C_Employee.OUId = @OUId
AND		    L_UCL.LeaveId IS NULL
AND		    (D_RoleGroup.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId='0')
AND		    (S_RosterGroup.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId='0')
GROUP BY	L_UCL.UCLDate,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName


--Role Group
SELECT		RoleGroupId,
			RoleGroupName
FROM		D_RoleGroup  WITH(NOLOCK)
WHERE		D_RoleGroup.OUId = @OUId

-- Shift Detail
SELECT		Convert(Date,S_Shifts.ShiftStartTime)ShiftStartTime,
			S_Shifts.OnCallShift,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName,
			Count(D_RoleGroup.RoleGroupId) TotalCount
FROM		S_Shifts WITH(NOLOCK)
			INNER JOIN D_Roles WITH(NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId			
			INNER JOIN D_RoleGroup WITH(NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			INNER JOIN S_RosterGroup WITH(NOLOCK) ON S_RosterGroup.RosterGroupId = S_Shifts.RosterGroupId
WHERE		Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date,@StartDate)
AND			Convert(Date,S_Shifts.ActualStartTime ) <= Convert(Date,@EndDate)
AND			S_Shifts.OUId = @OUId
AND		    (D_RoleGroup.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupId)) OR @RoleGroupId='0')
AND		    (S_RosterGroup.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupId)) OR @RosterGroupId='0')
GROUP BY	Convert(Date,S_Shifts.ShiftStartTime),
			S_Shifts.OnCallShift,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName

GO

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

CREATE PROC prL_GetLeaveLieuDatesByEmployeeId
(
	@EmployeeId			BigInt
)
AS
BEGIN

	SELECT L_EmployeeLieuDates.LieuDateId,
	       L_EmployeeLieuDates.LieuDate,
		   L_EmployeeLieuDates.EmployeeId,
		   L_EmployeeLieuDates.Utilized,
		   L_EmployeeLieuDates.CreatedDate,
		   L_EmployeeLieuDates.CreatedBy
	FROM   L_EmployeeLieuDates WITH (NOLOCK) 	       
	WHERE  L_EmployeeLieuDates.EmployeeId = @EmployeeId
	       AND L_EmployeeLieuDates.Utilized = 0

END
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 ExceptionCodeName,
			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,
			L_LeaveProfiles.IsHRApprovalRequired,
			L_LeaveProfiles.PrimaryApprovers,
			L_LeaveProfiles.IsPanelClinicRequired,
			L_LeaveProfiles.IsAttachmentRequired,
			L_LeaveProfiles.IsFutureDateAllowed,
			L_LeaveProfiles.IsBackDateAllowed
	FROM	L_LeaveProfiles WITH (NOLOCK)
			INNER JOIN L_LeaveProfileHeader WITH (NOLOCK) ON L_LeaveProfiles.LeaveProfileHeaderId = L_LeaveProfileHeader.LeaveProfileHeaderId
			RIGHT OUTER JOIN D_ExceptionCodes WITH (NOLOCK) 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 OR @OUId = 0)

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,
			L_Leaves.HalfDayType,
			L_Leaves.PanelClinicId,
			T_Attachments.AttachmentSavedAs AttachedFileName,
			L_EmployeeLieuDates.LieuDateId,
			L_EmployeeLieuDates.LieuDate
	FROM	L_Leaves WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_Leaves.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = L_Leaves.OUId
			LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
			LEFT OUTER JOIN T_Attachments WITH (NOLOCK) ON T_Attachments.AttachmentSourceId = L_Leaves.LeaveId 
				AND T_Attachments.ModuleName IN ('UnControlledLeave','ApplyLeave')
		    LEFT OUTER JOIN L_EmployeeLieuDates WITH (NOLOCK) ON L_EmployeeLieuDates.LeaveId = L_Leaves.LeaveId 
	WHERE	(L_Leaves.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	        AND L_Leaves.ApprovalStatusId != 4 --ApprovalStatus : Cancel
	ORDER BY L_Leaves.LeaveStart DESC
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_GetLeaveRecordsByEmployeeIdAndApprovalStatus]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_GetLeaveRecordsByEmployeeIdAndApprovalStatus]
GO
/****** Object:  StoredProcedure [dbo].[prL_GetLeaveRecordsByEmployeeIdAndApprovalStatus]    Script Date: 8/2/2018 10:16:36 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_GetLeaveRecordsByEmployeeIdAndApprovalStatus]    
(
	@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,
			L_Leaves.HalfDayType,
			L_Leaves.PanelClinicId,
			T_Attachments.AttachmentSavedAs AttachedFileName,
			L_EmployeeLieuDates.LieuDateId,
			L_EmployeeLieuDates.LieuDate
	FROM	L_Leaves WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_Leaves.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = L_Leaves.OUId
			LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) ON L_Leaves.ApprovalStatusId = W_ApprovalStatus.ApprovalStatusId
			LEFT OUTER JOIN T_Attachments WITH (NOLOCK) ON T_Attachments.AttachmentSourceId = L_Leaves.LeaveId 
				AND T_Attachments.ModuleName IN ('UnControlledLeave','ApplyLeave')
		    LEFT OUTER JOIN L_EmployeeLieuDates WITH (NOLOCK) ON L_EmployeeLieuDates.LeaveId = L_Leaves.LeaveId 
	WHERE	(L_Leaves.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	        AND L_Leaves.ApprovalStatusId IN (1,2,5,6,7)
	ORDER BY L_Leaves.LeaveStart DESC
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetLeaveRecordsByEmployeeIdDate')
	DROP PROC prL_GetLeaveRecordsByEmployeeIdDate
GO

CREATE PROC prL_GetLeaveRecordsByEmployeeIdDate
	@EmployeeId			Bigint,
	@LookUpDate			DateTime,
	@ExceptionCodeId	BigInt = 0
AS
BEGIN
	SELECT	L_Leaves.LeaveId,
			L_Leaves.LeaveStart,
			L_Leaves.LeaveEnd,
			L_Leaves.NoOfDays
	FROM	L_Leaves WITH (NOLOCK) 
	WHERE	L_Leaves.ExceptionCodeId			=	@ExceptionCodeId
	AND		L_Leaves.EmployeeId					=	@EmployeeId
	AND		Convert(Date,L_Leaves.LeaveEnd)		>=	Convert(Date,@LookUpDate)
	AND		Convert(Date,L_Leaves.LeaveStart)	<=	Convert(Date,@LookUpDate)

END
GO


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

CREATE PROC prL_GetLeaveRecordsForAccrualProcess
	@AccrualProcessDate	DateTime
AS
BEGIN
	SELECT	L_Leaves.LeaveId,
			L_Leaves.LeaveStart,
			L_Leaves.LeaveEnd,
			L_Leaves.NoOfDays,
			L_Leaves.ExceptionCodeId,
			L_Leaves.EmployeeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCode
	FROM	L_Leaves WITH (NOLOCK) INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON L_Leaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHERE	Convert(Date,L_Leaves.LeaveEnd)		>=	Convert(Date,@AccrualProcessDate)
	AND		Convert(Date,L_Leaves.LeaveStart)	<=	Convert(Date,@AccrualProcessDate)

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_GetManageUCLDetail')
	DROP PROCEDURE prL_GetManageUCLDetail
GO

CREATE PROC prL_GetManageUCLDetail
 (
    @StartDate				DateTime,
	@EndDate				DateTime,
	@EmployeeId			    BigInt,
	@DocUploadStatus		Int
)
AS
	SELECT L_UCL.UCLID,
		   L_UCL.ExceptionCodeID,
		   L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName EmployeeName,
		   C_OrganizationNode.OUName Department,
		   L_UCL.ExceptionCodeId,
		   L_UCL.UCLDate,
		   L_UCL.IsAttachedDocument,
		   L_UCL.AppliedDate,
		   L_UCL.Remarks,
		   D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
		   D_ExceptionCodes.ExceptionCodeDesc ,
		   L_UCL.LeaveId
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId
		   INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		   INNER JOIN D_ExceptionCodes   WITH (NOLOCK) ON  L_UCL.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHERE  L_UCL.UCLDate >=@StartDate
	AND	   L_UCL.UCLDate <=@EndDate
	AND	   (L_UCL.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	AND    (L_UCL.IsAttachedDocument = @DocUploadStatus OR @DocUploadStatus = 2)

	
GO

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

CREATE PROC prL_GetNumberOfDaysInPendingLeaves
	@EmployeeId			Bigint,
	@ApprovalStatusId     int
AS

SELECT	Sum(L_Leaves.NoOfDays) as NoOfDays,
        L_Leaves.ExceptionCodeId,
		D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName
FROM	L_Leaves WITH (NOLOCK)
	    INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
WHERE	L_Leaves.ApprovalStatusId =  @ApprovalStatusId AND L_Leaves.EmployeeId = @EmployeeId
Group by L_Leaves.ExceptionCodeId,D_ExceptionCodes.ExcpetionCodeName
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,
				D_Roles.RoleGroupId,
				D_RoleGroup.RoleGroupName RoleGroup
		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
				LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.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
		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 WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = L_TimeOff.EmployeeId
			LEFT OUTER JOIN W_ApprovalStatus WITH (NOLOCK) 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_GetUCLBetweenSelectedDate')
	DROP PROCEDURE prL_GetUCLBetweenSelectedDate
GO

CREATE PROC prL_GetUCLBetweenSelectedDate
 (
    @StartDate				DateTime,
	@EndDate				DateTime
)
AS
	SELECT L_UCL.UCLID,
		   L_UCL.ExceptionCodeID,
		   L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName EmployeeName,
		   C_OrganizationNode.OUName Department,
		   L_UCL.ExceptionCodeId,
		   L_UCL.UCLDate,
		   L_UCL.IsAttachedDocument,
		   L_UCL.AppliedDate,
		   L_UCL.Remarks,
		   D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
		   D_ExceptionCodes.ExceptionCodeDesc ,
		   D_ExceptionCodes.ColorCode ExceptionColor,
		   L_UCL.LeaveId,
		   D_ExceptionType.ExceptionTypeName,
		   D_ExceptionType.ExceptionTypeId
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId
		   INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		   INNER JOIN D_ExceptionCodes   WITH (NOLOCK) ON  L_UCL.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
		   INNER JOIN D_ExceptionType WITH (NOLOCK) on D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  L_UCL.UCLDate >=@StartDate
	AND	   L_UCL.UCLDate <=@EndDate	

	
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prL_GetUncontrolledLeaveDetail')
	DROP PROCEDURE prL_GetUncontrolledLeaveDetail
GO

CREATE PROC prL_GetUncontrolledLeaveDetail
 (
	@EmployeeId			    BigInt,
	@DocUploadStatus		Int
)
AS
	SELECT L_UCL.UCLID,
		   L_UCL.ExceptionCodeID,
		   L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName EmployeeName,
		   C_OrganizationNode.OUName Department,
		   L_UCL.ExceptionCodeId,
		   L_UCL.UCLDate,
		   L_UCL.IsAttachedDocument,
		   L_UCL.AppliedDate,
		   L_UCL.Remarks,
		   D_ExceptionCodes.ExcpetionCodeName ExceptionCode,
		   D_ExceptionCodes.ExceptionCodeDesc ,
		   L_UCL.LeaveId
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId
		   INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
		   INNER JOIN D_ExceptionCodes   WITH (NOLOCK) ON  L_UCL.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
	WHERE  (L_UCL.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	AND    (L_UCL.IsAttachedDocument = @DocUploadStatus OR @DocUploadStatus = 2)

	
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,
				L_Leaves.PanelClinicId,
				L_Leaves.HalfDayType,
				L_Leaves.IsEmergency,
				D_Roles.RoleGroupId,
				D_RoleGroup.RoleGroupName RoleGroup
		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
				LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.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
		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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_UCLDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_UCLDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_UCLDel] 
(
	@UCLId		BigInt	 
)
AS
BEGIN

	DELETE FROM L_UCL WHERE UCLID = @UCLId	  

	SELECT 1
END 
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_UCLIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_UCLIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_UCLIns]    
(		
	@ExceptionCodeId		Bigint, 
	@EmployeeId				Bigint,
	@UCLDate				DateTime,
	@ReferenceNo			nVarchar(50),
	@Remarks				nVarchar(max),
	@AppliedBy				nVarchar(50),	
	@AppliedDate			DateTime,
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	L_UCL WITH (NOLOCK)
	WHERE	EmployeeId =@EmployeeId AND UCLDate=@UCLDate

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO L_UCL
		(ExceptionCodeId,EmployeeId, UCLDate,ReferenceNo,Remarks,AppliedBy,AppliedDate,IsAttachedDocument,CreatedBy, CreatedDate)
		VALUES(@ExceptionCodeId, @EmployeeId,@UCLDate,@ReferenceNo,@Remarks,@AppliedBy,@AppliedDate,0,@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].[prL_UCLUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_UCLUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_UCLUpd]    
(		
	@UCLId					Bigint, 
	@LeaveId				Bigint,
	@IsAttachedDocument		Bit,
	@UploadAttachmentBy		nVarchar(50),	
	@UploadAttachmentDate	DateTime,
	@UploadedAttachmentName	nVarchar(max),
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	
	
		UPDATE L_UCL 
		SET	   IsAttachedDocument		= @IsAttachedDocument,
			   UploadAttachmentBy		= @UploadAttachmentBy,
			   UploadAttachmentDate		= @UploadAttachmentDate,
			   UploadedAttachmentName	= @UploadedAttachmentName,
			   LeaveId					= @LeaveId,
			   UpdatedBy				= @UpdatedBy,
			   UpdatedDate				= GetDate()
		WHERE  UCLID					= @UCLId

		Select 1;

	
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prL_UpdateEmailTemplate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prL_UpdateEmailTemplate]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prL_UpdateEmailTemplate]    
(
  @MailFrom   text = NULL,
  @MailCC     text = NULL,
  @MailBody   text,
  @FunctionId  BigInt,
  @LanguageId  BigInt 
)
AS
BEGIN
	Update D_EmailTemplate
	Set    MailBody  = @MailBody,
	       MailFrom  = @MailFrom,
		   MailCC    = @MailCC
	Where FunctionId = @FunctionId
	      AND LanguageId = @LanguageId
	Select 1
END
GO



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

CREATE PROC prL_UpdateEmployeeLeaveNoOfDaysById
	@LeaveId			Bigint,
	@NumberOfDays		Int = 0,
	@UpdatedBy			nVarchar(50)
AS
BEGIN
	UPDATE	L_Leaves
	SET		NoOfDays	=	NoOfDays - @NumberOfDays,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GETDATE()
	WHERE	LeaveId		=	@LeaveId

	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  @EmployeeLeaveProfileId

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_UpdateEmployeeLeaveProfileHeader')
	DROP PROC prL_UpdateEmployeeLeaveProfileHeader
GO

----------------------------------------------------------------------------
-- Update a single record in L_EmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROCEDURE prL_UpdateEmployeeLeaveProfileHeader
(
	@EmployeeLeaveProfileId	BigInt = 0,
	@LeaveProfileHeaderId	BigInt = 0,
	@UpdatedBy				nVarchar(50) = NULL
)
AS
BEGIN
	UPDATE	L_EmployeeLeaveProfiles 
	SET		LeaveProfileId	=	@LeaveProfileHeaderId,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EmpProfileId	=	@EmployeeLeaveProfileId

	SELECT 1
END
GO

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

----------------------------------------------------------------------------
-- Update a single record in prL_UpdateEmployeeLeaveProfiles
----------------------------------------------------------------------------
CREATE PROC prL_UpdateEmployeeLeaveProfiles
	@EmpProfileId bigint,
	@EmployeeId bigint = 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,
	@BalanceDays decimal(18, 2) = NULL,
	@EarnedMonth int = NULL
AS

UPDATE	L_EmployeeLeaveProfiles
SET	EmployeeId = @EmployeeId,
    LeaveYear = @LeaveYear,
	ExceptionId = @ExceptionId,
	EntitlementDays = @EntitlementDays,
	CarryForwardDays = @CarryForwardDays,
	EarnedDays = @EarnedDays,
	DaysUsed = @DaysUsed,
	AdjustDays = @AdjustDays,
	BalanceDays = @BalanceDays,
	EarnedMonth = @EarnedMonth,
	UpdatedDate = GETDATE()
WHERE 	EmpProfileId = @EmpProfileId

SELECT 1

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_UpdateEmployeeLieuDates')
	DROP PROC prL_UpdateEmployeeLieuDates
GO

CREATE PROC prL_UpdateEmployeeLieuDates
(
	@EmployeeId			BigInt,
	@LeaveStart         DateTime

)
AS

BEGIN
	Update L_EmployeeLieuDates
	Set    Utilized = 1
	Where  EmployeeId = @EmployeeId AND Convert(Date,LieuDate) = Convert(Date,@LeaveStart)

	SELECT 1
END
GO


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


CREATE PROC prL_UpdateEmployeePanelClinic
    @EmployeePanelClinicId BigInt,
	@PanelClinicId		  Int,
	@EmployeeId			  BigInt,	
	@Action               Int, 
	@UpdatedBy			  nVarchar(50)
AS

	UPDATE	C_EmployeePanelClinics
	SET		PanelClinicId		=	@PanelClinicId,
	        EmployeeId			=	@EmployeeId, 
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeePanelClinicId =	@EmployeePanelClinicId

	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  @EmployeeWorkflowId

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)

			UPDATE	L_Leaves
			SET		ApprovalStatusId	=	@ApprovalStatusId,
					ApprovedBy			=	@ApprovedBy,
					ApprovedDate		=	@ApprovedDate,
					UpdatedBy			=	@ApprovedBy,
					UpdatedDate			=	GETDATE()
			WHERE	LeaveId				=	@LeaveId
			
			--SELECT 1
		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) = NULL
)
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),
	@IsHRApprovalRequired	Bit = 0,
	@PrimaryApprovers		nVarchar(max),
	@IsPanelClinicRequired	Bit,
	@IsAttachmentRequired 	Bit,
	@IsFutureDateAllowed    Bit,
	@IsBackDateAllowed      Bit
)
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(),
				IsHRApprovalRequired	=	@IsHRApprovalRequired,
				PrimaryApprovers		=	@PrimaryApprovers,
				IsPanelClinicRequired	=	@IsPanelClinicRequired,
				IsAttachmentRequired	=	@IsAttachmentRequired,
				IsFutureDateAllowed     =   @IsFutureDateAllowed,
				IsBackDateAllowed       =   @IsBackDateAllowed
		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,
	@CranePriorityId bigint

AS

INSERT M_CraneSchedule(OUId, CraneId, VesselScheduleId, LocationId, StartDate, EndDate, Imported, WorkloadGenerated, SignOffStatus, CreatedDate, CreatedBy,CranePriorityId)
VALUES (@OUId, @CraneId, @VesselScheduleId, @LocationId, @StartDate, @EndDate, @Imported, @WorkloadGenerated, @SignOffStatus, GETDATE(), @CreatedBy,@CranePriorityId) 

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,
	@ShiftBandId	BigInt = NULL
AS

INSERT M_EquipmentSchedule
(OUId, EquipmentTypeId, EquipmentId, StartDate, EndDate, CraneScheduleId, WorkloadGenereated, SignOffStatus, 
 CreatedDate, CreatedBy, ShiftBandId)
VALUES (@OUId, @EquipmentTypeId, @EquipmentId, @StartDate, @EndDate, @CraneScheduleId, @WorkloadGenereated, 
@SignOffStatus, GETDATE(), @CreatedBy, @ShiftBandId)

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
	@StatusId	BigInt = 0,
	@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,
	@EquipmentTypes nVarchar(500) = NULL,
	@ActivityGenRuleId BigInt = NULL,
	@SignedOffSkills	nVarchar(500) = NULL
AS
DECLARE @ReliefBreakSkillId nVarchar(10) = '0'

-- Retrieve Relief Break Id From System Parameters And Add To Signed Off Skills
SELECT @ReliefBreakSkillId = ParamValue
FROM D_SystemParams WITH (NOLOCK) WHERE ParamName ='ReliefBreakId'

-- Add Relief Break Id Signed Off Skills
If (@SignedOffSkills IS NOT NULL) SET @SignedOffSkills = @SignedOffSkills + ',' + @ReliefBreakSkillId

If (@SignedOffSkills IS NULL) UPDATE J_Activity SET ProgresstionState = 2 WHERE StartTime >= @StartTime AND StartTime < @EndTime
Else UPDATE J_Activity SET ProgresstionState = 2 WHERE StartTime >= @StartTime AND StartTime < @EndTime AND SkillId IN  (SELECT * FROM fnStringToTable(@SignedOffSkills))

If (@SignedOffSkills IS NULL) UPDATE J_Workload SET SignOffStatus = 1 WHERE StartTime >= @StartTime AND StartTime < @EndTime And (ShiftBandId = @ShiftBandId OR IsNull(ShiftBandId,0) = 0)
Else UPDATE J_Workload SET SignOffStatus = 1 WHERE StartTime >= @StartTime AND StartTime < @EndTime And (ShiftBandId = @ShiftBandId OR IsNull(ShiftBandId,0) = 0) AND SkillId IN  (SELECT * FROM fnStringToTable(@SignedOffSkills))

If (@SignedOffSkills IS NULL) UPDATE M_EquipmentSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime And (ShiftBandId = @ShiftBandId OR IsNull(ShiftBandId,0) = 0)
Else UPDATE M_EquipmentSchedule SET SignOffStatus = 1 WHERE StartDate >= @StartTime AND StartDate < @EndTime And (ShiftBandId = @ShiftBandId OR IsNull(ShiftBandId,0) = 0)  AND EquipmentTypeId IN  (SELECT * FROM fnStringToTable(@EquipmentTypes))

If(CHARINDEX('0',@EquipmentTypes) > 0 OR @EquipmentTypes IS NULL) 
BEGIN
	--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_CraneSchedule SET SignOffStatus = 1 WHERE EndDate > @StartTime AND StartDate < @EndTime
	--UPDATE M_VesselSchedule SET Status = 2 WHERE EndDate > @StartTime AND StartDate < @EndTime
	UPDATE	M_CraneSchedule SET SignOffStatus = 1 
	FROM	M_CraneSchedule WITH (NOLOCK) 
			INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId
			INNER JOIN J_Activity WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId 
			AND J_Activity.StartTime >= @StartTime AND J_Activity.StartTime < @EndTime

	UPDATE M_VesselSchedule SET Status = 2 
	FROM	M_VesselSchedule WITH (NOLOCK) 
			INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.VesselScheduleId = M_VesselSchedule.VesselScheduleId
			INNER JOIN J_Activity WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
			AND J_Activity.StartTime >= @StartTime AND J_Activity.StartTime < @EndTime
END

EXEC prJ_AddPlanningRequirements @OUId, @ShiftBandId, @ShiftDate, @StartTime, @EndTime, @SignedOffBy, @SignedOffSkills

EXEC prJ_AddPlanningEquipmentRequirements @OUId, @ShiftBandId, @ShiftDate, @StartTime, @EndTime, @SignedOffBy, @EquipmentTypes


If (@StatusId = 0)
BEGIN
	INSERT M_ShiftSignOffStatus(OUId, ShiftDate, ShiftBandId, StartTime, EndTime, Status, SignedOffBy, SignedOffDate, EquipmentTypes, ActivityGenerationRuleId )
	VALUES (@OUId, @ShiftDate, @ShiftBandId, @StartTime, @EndTime, @Status, @SignedOffBy, @SignedOffDate, @EquipmentTypes, @ActivityGenRuleId)

	SELECT CAST(@@Identity AS BigInt) 
END
Else
BEGIN
	UPDATE	M_ShiftSignOffStatus 
	SET		EquipmentTypes	=	EquipmentTypes + ',' + @EquipmentTypes
	WHERE	StatusId		=	@StatusId
	SELECT CAST(@StatusId AS bigint)
END
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,
	@UpdatedBy	nVarchar(50)			
)
AS
BEGIN
	 

	Update	M_Berth  
	SET		ActiveStatus	=	0, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	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_ConeManPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ConeManPlanDetailIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_ConeManPlanDetailIns]    
(
   @ConeManPlanDetail UTM_ConeManPlanDetail readonly	
)
AS
BEGIN

	Merge M_ConeManPlanDetail as Target Using @ConeManPlanDetail as Source on(Target.ConeManPlanId =Source.ConeManPlanId and Target.CraneScheduleId=Source.CraneScheduleId)	
	When Not Matched By Target Then
	Insert (ConeManPlanId,CraneScheduleId,CreatedBy,CreatedDate) 
	Values (Source.ConeManPlanId,Source.CraneScheduleId,Source.CreatedBy,getdate());	
	select 1
END

GO
  IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ConeManPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ConeManPlanIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_ConeManPlanIns]    
(
	@PlannedDate  				DateTime,
	@ShiftBandId				BigInt,	
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_ConeManPlan
	(PlannedDate,ShiftbandId, CreatedBy, CreatedDate)
	VALUES(@PlannedDate,@ShiftBandId, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ConeManPlanningDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ConeManPlanningDel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_ConeManPlanningDel]    
(
	@ConeManPlanId				BigInt
)
AS
BEGIN

	DELETE FROM M_ConeManPlan 
	WHERE		M_ConeManPlan.ConeManPlanId = @ConeManPlanId

	DELETE FROM M_ConeManPlanDetail
	WHERE		M_ConeManPlanDetail.ConeManPlanId = @ConeManPlanId	


	SELECT @ConeManPlanId
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneConditionDetailsDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneConditionDetailsDel]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_CraneConditionDetailsDel] 
(
	@CraneConditionId  BigInt	
)
AS

BEGIN

	BEGIN
		delete from  M_CraneConditionDetails  where CraneConditionId=@CraneConditionId 
				
		SELECT @CraneConditionId
	END
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneConditionDetailsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneConditionDetailsIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_CraneConditionDetailsIns] 
(
	@CraneId		   BigInt,
	@ConditionType	   Bigint,
	@StartDate		   DateTime,	
	@EndDate		   DateTime,
	@Remarks           nvarchar(max),	
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN


	BEGIN
				insert into M_CraneConditionDetails(CraneId,ConditionType,StartDate,EndDate,Remarks,CreatedBy,CreatedDate)
				values(@CraneId,@ConditionType,@StartDate,@EndDate,@Remarks,@CreatedBy,GETDATE())
		SELECT @@IDENTITY
	END
	
END
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_CraneConditionDetailsUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_CraneConditionDetailsUpd]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_CraneConditionDetailsUpd] 
(
	@CraneConditionId  BigInt,
	@CraneId		   BigInt,
	@ConditionType	   Bigint,
	@StartDate		   DateTime,	
	@EndDate		   DateTime,
	@Remarks           nvarchar(max),	
	@UpdatedBy			nVarchar(50)
)
AS

BEGIN

	BEGIN
		update M_CraneConditionDetails set ConditionType=@ConditionType,StartDate=@StartDate,
		EndDate=@EndDate,Remarks=@Remarks,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE() where CraneConditionId=@CraneConditionId and CraneId=@CraneId
				
		SELECT @CraneConditionId
	END
	
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_CraneConditionIns')
	DROP PROC prM_CraneConditionIns
GO

----------------------------------------------------------------------------
-- INSERT Records into M_CraneConditionDetails 
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_CraneConditionIns] 
(
	@CraneId		   BigInt,
	@ConditionType	   Bigint,
	@StartDate		   DateTime,	
	@EndDate		   DateTime,
	@Remarks           nvarchar(max),	
	@CreatedBy			nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN
		insert into M_CraneConditionDetails(CraneId,ConditionType,StartDate,EndDate,Remarks,CreatedBy,CreatedDate)
		values(@CraneId,@ConditionType,@StartDate,@EndDate,@Remarks,@CreatedBy,GETDATE())
		SELECT @@IDENTITY

END
GO

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

----------------------------------------------------------------------------
-- UPDATE Records into M_CraneConditionDetails 
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_CraneConditionUpd] 
(
	@CraneConditionId  BigInt,
	@CraneId		   BigInt,
	@ConditionType	   Bigint,
	@StartDate		   DateTime,	
	@EndDate		   DateTime,
	@Remarks           nvarchar(max),	
	@UpdatedBy			nVarchar(50)
)
AS

BEGIN
		update M_CraneConditionDetails set ConditionType=@ConditionType,StartDate=@StartDate,CraneId=@CraneId,
		EndDate=@EndDate,Remarks=@Remarks,UpdatedBy=@UpdatedBy,UpdatedDate=GETDATE() where CraneConditionId=@CraneConditionId
				
		SELECT @CraneConditionId
	
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 OR @OUID = 0)
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_EmployeeEquipmentBoxMovementIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentBoxMovementIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_EmployeeEquipmentBoxMovementIns]    
(
  @EmpEqupBoxMovement UM_EmployeeEquipmentBoxMovement readonly
)
AS
BEGIN
    Merge M_EmployeeEquipmentBoxMovement as Target Using @EmpEqupBoxMovement as Source on(Target.EmployeeNumber = Source.EmployeeNumber and Target.EquipmentName = Source.EquipmentName and Target.LoginTime = Source.LoginTime AND Target.LogoutTime = Source.LogoutTime And Target.NoOfMoves = Source.NoOfMoves)	
	When Not Matched By Target Then
	Insert (EquipmentName,EmployeeNumber, LoginTime,LogoutTime,NoOfMoves, Remarks,Source,CreatedBy,CreatedDate,EmployeeId, EquipmentType) 
	Values (Source.EquipmentName,Source.EmployeeNumber, Source.LoginTime,Source.LogoutTime, Source.NoOfMoves, Source.Remarks,Source.Source,Source.CreatedBy,GETDATE(),Source.EmployeeId, Source.EquipmentType);

	SELECT 1
END

GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginIns]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginUpd]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginUpd]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_EmployeeEquipmentLoginIns]    
(
  @EmployeeEquipmentLogin UM_EmployeeEquipmentLogin readonly,
  @InterfaceType int
)
AS
BEGIN
    IF @InterfaceType = 16
	BEGIN
    Merge M_EmployeeEquipmentLogin as Target Using @EmployeeEquipmentLogin as Source on(Target.EmployeeNumber =Source.EmployeeNumber and Target.EquipmentName = Source.EquipmentName and Target.ClockInDateTime = Source.ClockInDateTime and Target.TypeId = Source.TypeId)	
	When Not Matched By Target Then
	Insert (EquipmentName,EmployeeNumber,EmployeeId,ClockInDateTime,TypeId,PickupPoint,Remarks,Source,CreatedBy,CreatedDate, LastLocation) 
	Values (Source.EquipmentName,Source.EmployeeNumber,Source.EmployeeId,Source.ClockInDateTime,Source.TypeId,Source.PickupPoint,Source.Remarks,Source.Source,Source.CreatedBy,getdate(), Source.LastLocation)
	When Matched Then
	Update Set Target.Remarks=Source.Remarks,
			   Target.Source =Source.Source,	   
			   Target.LastLocation = Source.LastLocation,
	           Target.PickupPoint = Source.PickupPoint;
	select 1
	END
    ELSE	
	BEGIN
    Merge M_EmployeeEquipmentLogin as Target Using @EmployeeEquipmentLogin as Source on(Target.EmployeeNumber =Source.EmployeeNumber and Target.EquipmentName = Source.EquipmentName and Target.ClockInDateTime = Source.ClockInDateTime and Target.ClockOutDateTime = source.ClockOutDateTime)	
	When Not Matched By Target Then
	Insert (EquipmentName,EmployeeNumber,EmployeeId,ClockInDateTime,PickupPoint,Remarks,Source,CreatedBy,CreatedDate,ClockOutDateTime, LastLocation) 
	Values (Source.EquipmentName,Source.EmployeeNumber,Source.EmployeeId,Source.ClockInDateTime,Source.PickupPoint,Source.Remarks,Source.Source,Source.CreatedBy,getdate(),Source.ClockOutDateTime, Source.LastLocation)
	When Matched Then
	Update Set	Target.Remarks=Source.Remarks,
				Target.Source =Source.Source,	  
				Target.LastLocation = Source.LastLocation,
				Target.PickupPoint = Source.PickupPoint;
	select 1
	END
END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_EmployeeEquipmentLoginUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EmployeeEquipmentLoginUpd]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_EmployeeEquipmentLoginUpd]    
(
  @EmployeeEquipmentLogin UTM_EmployeeEquipmentLogin readonly
)
AS
BEGIN
   
	BEGIN
    Merge M_EmployeeEquipmentLogin as Target Using @EmployeeEquipmentLogin as Source on(Target.ClockingId =Source.ClockingId)	

	When Matched Then
	Update Set Target.IsClockInPicked	= Source.IsClockInPicked,
			   Target.IsClockOutPicked  = Source.IsClockOutPicked,	   
	           Target.ActivityId		= Source.ActivityId;
	select 1
	END
   
END

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 sysobjects WHERE name = 'prM_EquipmentBrandDel')
	DROP PROC prM_EquipmentBrandDel
GO
----------------------------------------------------------------------------
-- delete Records from M_EquipmentBrands
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_EquipmentBrandDel]    
(	
	@BrandNameId	BigInt,
	@UpdatedBy	nVarchar(50)			
)
AS
BEGIN
	 

	Update	M_EquipmentBrandNames  
	SET		IsActive	=	0, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	BrandNameId			=	@BrandNameId

	SELECT 1
	 
END
GO

 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentBrandIns')
	DROP PROC prM_EquipmentBrandIns
GO
----------------------------------------------------------------------------
-- Insert Records into M_EquipmentBrandNames
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_EquipmentBrandIns]    
(		
	@OUId				Bigint, 
	@BrandName			nvarchar(50),
	@BrandDesc			nvarchar(50),
	@EquipmentTypeId     Bigint,
	@IsActive		INT,	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentBrandNames WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(BrandName))) = LTrim(RTrim(Upper(@BrandName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentBrandNames
		(OUID,BrandName,BrandDesc,EquipmentTypeId,IsActive,CreatedBy, CreatedDate)
		VALUES(@OUId,@BrandName,@BrandDesc,@EquipmentTypeId,@IsActive,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO


 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentBrandTypeDel')
	DROP PROC prM_EquipmentBrandTypeDel
GO
----------------------------------------------------------------------------
-- delete Records from M_EquipmentBrands
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_EquipmentBrandTypeDel]
(
	@BrandNameId		BigInt ,
	@EquipmentId		BigInt
)
AS
BEGIN
	DELETE FROM 	M_EquipmentBrands 
	WHERE	BrandNameId	=	@BrandNameId and EquipmentId =@EquipmentId

	SELECT 1
END
GO

 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentBrandTypeIns')
	DROP PROC prM_EquipmentBrandTypeIns
GO
----------------------------------------------------------------------------
-- Insert Records from M_EquipmentBrands
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_EquipmentBrandTypeIns]    
(		
	@BrandNameId			Bigint, 
	@EquipmentId			bigint , 
	@CreatedBy					nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentBrands WITH (NOLOCK)
	WHERE	BrandNameId=@BrandNameId and EquipmentId=@EquipmentId 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentBrands
		( BrandNameId,EquipmentId,CreatedBy, CreatedDate)
		VALUES(@BrandNameId,@EquipmentId,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO

 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentBrandUpd')
	DROP PROC prM_EquipmentBrandUpd
GO
----------------------------------------------------------------------------
---- Update Records into M_EquipmentBrandNames
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_EquipmentBrandUpd]    
(
	@BrandNameId	  BigInt,
	@OUId				  Bigint, 
	@BrandName	  nvarchar(50),	 
	@BrandDesc	  nvarchar(50),
	@IsActive	  INT,	
	@UpdatedBy			  nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentBrandNames WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(BrandName))) = LTrim(RTrim(Upper(@BrandName)))
	AND		BrandNameId	!=	@BrandNameId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_EquipmentBrandNames		SET		
				OUId		 =	@OUId,	
				BrandName	 =	@BrandName,
				BrandDesc	 = 	 @BrandDesc,
				IsActive	 =	@IsActive, 			 
				UpdatedBy	 =	@UpdatedBy,
				UpdatedDate	 =	GETDATE()				
		WHERE	BrandNameId		=	@BrandNameId

		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_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),
	@IsCrane            BIT
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentMaintenance WITH (NOLOCK)
	WHERE   EquipmentId=@EquipmentId And (EndDate > @StartDate and StartDate  < @EndDate)
	        AND IsCrane = @IsCrane

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_EquipmentMaintenance
		(EquipmentId,StartDate, EndDate,Reason,Notes,CreatedBy, CreatedDate,IsCrane)
		VALUES(@EquipmentId, @StartDate,@EndDate,@Reason,@Notes,@CreatedBy, GETDATE(),@IsCrane)

		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,
		    CASE IsCrane WHEN 0 THEN M_Equipments.EquipmentId ELSE M_Cranes.CraneId END EquipmentId,
		    M_EquipmentMaintenance.StartDate,
		    M_EquipmentMaintenance.EndDate,
		    IsNull(M_EquipmentMaintenance.Reason,'') Reason,
		    IsNull(M_EquipmentMaintenance.Notes,'') Notes,
			M_EquipmentMaintenance.CreatedBy, 
			M_EquipmentMaintenance.CreatedDate,
			M_EquipmentMaintenance.UpdatedBy,
			M_EquipmentMaintenance.UpdatedDate,
			M_EquipmentMaintenance.IsCrane,
		    CASE IsCrane WHEN 0 THEN M_Equipments.EquipmentName ELSE M_Cranes.CraneNumber END EquipmentName,
			M_Equipments.EquipmentTypeId
    FROM	M_EquipmentMaintenance with (nolock) 
		    LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentMaintenance.EquipmentId = M_Equipments.EquipmentId And IsCrane = 0
		    LEFT OUTER JOIN M_Cranes WITH (NOLOCK) ON M_EquipmentMaintenance.EquipmentId = M_Cranes.CraneId And IsCrane = 1 
   	WHERE	(M_EquipmentMaintenance.MaintenanceId = @MaintenanceId OR @MaintenanceId = 0)
	AND		M_EquipmentMaintenance.IsCrane IS NOT NULL
	 
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),
	@IsCrane            BIT
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_EquipmentMaintenance WITH (NOLOCK)
	WHERE	MaintenanceId != @MaintenanceId 
	AND     (EndDate > @StartDate and StartDate < @EndDate)   
	AND     EquipmentId = @EquipmentId
	AND     IsCrane = @IsCrane

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	M_EquipmentMaintenance
		SET		EquipmentId			=	@EquipmentId, 
				StartDate			=	@StartDate, 				 
				EndDate				=	@EndDate, 
				Reason				=	@Reason,  
				Notes				=	@Notes,
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE(),
				IsCrane             =   @IsCrane			
		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_EquipmentScheduleBulkUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_EquipmentScheduleBulkUpdate]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_EquipmentScheduleBulkUpdate]    
(
   @EquipmentSchedule UTM_EquipmentScheduleUpdate readonly	
)
AS
BEGIN

	Merge M_EquipmentSchedule as Target Using @EquipmentSchedule as Source on(Target.EquipmentScheduleId = Source.EquipmentScheduleId)	
	When Matched Then
	Update Set Target.EquipmentId	=	Source.EquipmentId,
			   Target.UpdatedBy		=	Source.UpdatedBy,
			   Target.UpdatedDate	=	GETDATE();
	select 1
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 sysobjects WHERE name = 'prM_EquipmentsDel')
	DROP PROC prM_EquipmentsDel
GO
 
 
Create PROCEDURE [dbo].[prM_EquipmentsDel]    
(	
	@EquipmentId	BigInt,
	@UpdatedBy		nVarchar(50)			
)
AS
BEGIN
	 

	Update	M_Equipments
	SET		ActiveStatus	=	0,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	EquipmentId		=	@EquipmentId

	SELECT 1 
END
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 OR @OUID = 0)
END
go
 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentsTypeSel')
	DROP PROC prM_EquipmentsTypeSel
GO
----------------------------------------------------------------------------
-- Select Records into M_Equipments
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_EquipmentsTypeSel]    
(
	@EquipmentId		bigint,
	@OUID				BigInt,
	@BrandNameId        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
			INNER JOIN M_EquipmentBrandNames  with (NOLOCK) ON M_EquipmentBrandNames.equipmentTypeId = M_Equipments.equipmentTypeId
	WHERE	(M_Equipments.EquipmentId = @EquipmentId OR @EquipmentId = 0) AND M_EquipmentBrandNames.BrandNameId = @BrandNameId
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
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 OR @OUID = 0)
END
go
 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_EquipmentTypesSel')
	DROP PROC prM_EquipmentTypesSel
GO
----------------------------------------------------------------------------
-- Get Records into M_EquipmentBrands
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_EquipmentTypesSel]   
(
	@BrandNameId		bigint 
)
AS
BEGIN
	SELECT	M_EquipmentBrands.EquipmentBrandId,
			M_EquipmentBrands.EquipmentId,
			M_EquipmentBrands.BrandNameId,  
			M_EquipmentBrands.IsActive, 			
			M_EquipmentBrands.CreatedDate,
			M_EquipmentBrands.CreatedBy, 
			M_Equipments.EquipmentName 
	FROM	M_EquipmentBrands	  WITH (NOLOCK)
	LEFT OUTER JOIN M_Equipments WITH (NOLOCK) on M_Equipments.EquipmentId= M_EquipmentBrands.EquipmentId 			 
	WHERE	(M_EquipmentBrands.BrandNameId = @BrandNameId )
	 
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 WITH (NOLOCK) 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,
		IsNull(M_AuxiliaryWork.LocationId, 0) LocationId
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,
	IsNull(LocationId,0) LocationId
FROM	M_AuxiliaryWork WITH (NOLOCK)
WHERE 	ScheduleId = @ScheduleId

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

CREATE  PROC [dbo].[prM_GetActivitiesByScheduledList]
	@WorkloadList	nVarchar(max),
	@ReliefBreakId	BigInt
AS
BEGIN
	WITH Activities AS
	(SELECT	J_Activity.ActivityId,
			J_Activity.SkillId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.GroupNo,
			J_Activity.AllocationNo,
			J_Activity.WorkloadId,
			IIF(IsNull(J_Workload.CraneScheduleId,0) = 0,IsNull(J_Workload.EquipmentScheduleId,0), IsNull(J_Workload.CraneScheduleId,0)) ScheduleId,
			J_Workload.VesselScheduleId,
			J_Activity.ShiftBandId,
			J_Activity.OUId,
			J_Activity.WorkType,
			J_Activity.RuleId,
			J_Activity.ProgresstionState,
			ROW_NUMBER() OVER(PARTITION BY J_Activity.WorkloadId ORDER BY J_Activity.EndTime DESC) RowId 
	FROM	J_Activity WITH (NOLOCK)
			INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
	WHERE	J_Activity.WorkloadId IN (SELECT * FROM fnStringToTable(@WorkloadList))
	AND		J_Activity.SkillId != @ReliefBreakId -- Exclude Relief Break Id
	)
	SELECT	*
	FROM	Activities WITH (NOLOCK) 
	WHERE	RowId = 1
	
END

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, 
		M_Cranes.LocationId
FROM	M_cranes WITH (NOLOCK) 
where	M_cranes.ActiveStatus=1 
AND		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)
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,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int,
	@ShiftBandId		nVarchar(max)
	
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 Convert(DateTime,ActualStartTime) >= CONVERT(DATETIME, @StartDate)  
--AND  Convert(DateTime,ActualEndTime) <= CONVERT(DATETIME, @EndDate)  
  WHERE Convert(Date,ShiftStartTime) >= CONVERT(DATE, @StartDate)  
  AND   Convert(Date,ShiftEndTime) <= CONVERT(DATE, @EndDate)
  AND	S_Shifts.OUId = @OUId  
  AND	(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) = Convert(Date,@StartDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) = Convert(Date,@StartDate)

	
	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) = Convert(Date,@StartDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId

	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 

go



IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetConeManPlanDetail')
	DROP PROCEDURE prM_GetConeManPlanDetail
GO

CREATE PROC prM_GetConeManPlanDetail
 (
	@PlannedDate		DateTime,
	@ShiftBandId		BigInt
)
AS
  -- Cone Man Plan
		SELECT	M_ConeManPlan.ConeManPlanId,
				M_ConeManPlan.PlannedDate,
				M_ConeManPlan.ShiftbandId,
				M_ConeManPlan.CreatedBy,
				M_ConeManPlan.CreatedDate
		FROM	M_ConeManPlan   WITH (NOLOCK) 
		WHERE   M_ConeManPlan.PlannedDate = @PlannedDate
		AND		M_ConeManPlan.ShiftbandId = @ShiftBandId

 -- Cone Man Plan Detail
		SELECT	M_ConeManPlanDetail.Id,
				M_ConeManPlanDetail.ConeManPlanId,
				M_ConeManPlanDetail.CraneScheduleId,
				M_ConeManPlanDetail.CreatedBy,
				M_ConeManPlanDetail.CreatedDate,
				M_Cranes.CraneId,
				M_Cranes.CraneNumber
		FROM	M_ConeManPlanDetail   WITH (NOLOCK) 
				INNER JOIN M_ConeManPlan WITH (NOLOCK) ON M_ConeManPlan.ConeManPlanId = M_ConeManPlanDetail.ConeManPlanId
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = M_ConeManPlanDetail.CraneScheduleId
				INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
		WHERE   M_ConeManPlan.PlannedDate = @PlannedDate
		AND		M_ConeManPlan.ShiftbandId = @ShiftBandId


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,
		M_CraneSchedule.CranePriorityId
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_GetCranesSel')
	DROP PROC prM_GetCranesSel
GO
----------------------------------------------------------------------------
-- Select Records into M_Cranes
---------------------------------------------------------------------------- 
CREATE PROCEDURE [dbo].[prM_GetCranesSel]    
(
	@CraneId            bigint,
	@EquipmentTypeId    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,
			ISNULL ( M_Equipmentbrandnames.EquipmentTypeId , 0 ) EquipmentTypeId ,
			case when M_Cranes.craneid  is not null then 'selected' else null end  as Sel_craneid	 
	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
			left join M_EquipmentBrands on M_EquipmentBrands.EquipmentId = M_Cranes.craneid  
			left join M_Equipments on M_Equipments.EquipmentId = M_EquipmentBrands.EquipmentId
			left JOIN M_Equipmentbrandnames WITH (NOLOCK)  on M_Equipmentbrandnames.EquipmentTypeId =M_Equipments.EquipmentTypeId 
	WHERE	(M_Cranes.CraneId = 0 OR 0 = 0)
	 AND	case when M_EquipmentBrands.EquipmentId  is not null then 'selected' else '' end <> 'selected'
	and     ISNULL ( M_Equipmentbrandnames.EquipmentTypeId , 0 ) = @EquipmentTypeId
	AND		(C_OrganizationNode.OUId = @OUID OR @OUID = 0)
END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetEmployeeByCraneScheduleId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetEmployeeByCraneScheduleId]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO 
 
Create PROCEDURE [dbo].[prM_GetEmployeeByCraneScheduleId]    
(
	@CraneScheduleId		bigint,
	@CraneNumber	        nvarchar(50),
	@ShiftDate			    DateTime
)
AS
BEGIN
	;with EquipmentDetails as (
	SELECT ActivityId,  ShiftId, EquipmentName, Min(RowNumber) FirstRowNumber, Max(TotalRowsCount) LastRowNumber, EquipmentType, EquipmentId
	FROM (
		SELECT J_Activity.ActivityId, J_Activity.StartTime, J_Activity.EndTime, S_Shifts.ShiftId,
		CraneWorkLoad.CraneScheduleId EquipmentType,
		Cranes.CraneId EquipmentId,
		Cranes.CraneNumber EquipmentName,
		ROW_NUMBEr() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
		COUNT(*) over (PARTITION BY J_Activity.ShiftId) as TotalRowsCount
		FROM J_Activity WITH (NOLOCK)
		INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
		INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
		Inner JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		Inner  JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId		
		--INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
		--left JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
		--left JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		where Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date,@ShiftDate)
		) Activities
	WHERE RowNumber = 1 or RowNumber = TotalRowsCount   
	GROUP BY ActivityId,  ShiftId, EquipmentName, EquipmentType, EquipmentId),

	EmployeeDetails as(
	Select C_Employee.EmployeeId,C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,D_Roles.RoleName PrimaryRole,C_Employee.ActiveStatus,
	S_Shifts.ShiftStartTime,S_Shifts.ShiftEndTime,S_Shifts.ShiftId,
	(select Equipment.EquipmentName where Equipment.FirstRowNumber=1)FirstEquipment,
	(select Equipment.EquipmentName where Equipment.FirstRowNumber=Equipment.LastRowNumber)LastEquipment,
	S_SHifts.ActualStartTime,S_SHifts.ActualEndTime,D_ShiftBand.ShiftBandCode
	from J_Workload with (NoLock) inner join J_Activity with (NoLock) on  J_Workload.WorkloadId=J_Activity.WorkloadId 
	inner join S_Shifts with (NoLock) on S_Shifts.ShiftId =J_Activity.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
	INNER JOIN D_Roles  with (NoLock) ON C_EmployeeRoles.RoleId = D_Roles.RoleId
	left join EquipmentDetails Equipment with (NoLock) ON Equipment.ShiftId =S_Shifts.ShiftId	
	Inner join D_ShiftBand on D_ShiftBand.ShiftBandId=S_SHifts.ShiftBandId
	where J_Workload.CraneScheduleId=@CraneScheduleId), 

	CraneDetails as(
	select EmployeeId,EmployeeNumber,EmployeeName,PrimaryRole,ActiveStatus,ShiftStartTime,ShiftEndTime,
	ShiftId,max(FirstEquipment)FirstEquipment,max(LastEquipment)LastEquipment,ActualStartTime,ActualEndTime,ShiftBandCode from EmployeeDetails with (NoLock)
	group by EmployeeId,EmployeeNumber,EmployeeName,PrimaryRole,ActiveStatus,ShiftStartTime,ShiftEndTime,ShiftId,ActualStartTime,ActualEndTime,ShiftBandCode)

	select * from CraneDetails where FirstEquipment=@CraneNumber or LastEquipment=@CraneNumber

END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEmployeeEquipmentBoxMovementDetail')
	DROP PROCEDURE prM_GetEmployeeEquipmentBoxMovementDetail
GO

CREATE PROC prM_GetEmployeeEquipmentBoxMovementDetail
 (
	@StartDate		DateTime,
	@EndDate		DateTime,
	@EmployeeId		BigInt
)
AS

  --- Box Movement

 SELECT		M_EmployeeEquipmentBoxMovement.BoxMovementId,
			M_EmployeeEquipmentBoxMovement.EquipmentName,
			M_EmployeeEquipmentBoxMovement.EmployeeId,
			M_EmployeeEquipmentBoxMovement.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			M_EmployeeEquipmentBoxMovement.LoginTime,
			M_EmployeeEquipmentBoxMovement.LogoutTime,
			M_EmployeeEquipmentBoxMovement.NoOfMoves,
			M_EmployeeEquipmentBoxMovement.EquipmentType
 FROM		M_EmployeeEquipmentBoxMovement WITH(NOLOCK)
			INNER JOIN C_Employee WITH(NOLOCK) ON C_Employee.EmployeeId = M_EmployeeEquipmentBoxMovement.EmployeeId
 WHERE		Convert(Date,M_EmployeeEquipmentBoxMovement.LoginTime) >= @StartDate
 AND		Convert(Date,M_EmployeeEquipmentBoxMovement.LogoutTime) <= @EndDate
 AND		(M_EmployeeEquipmentBoxMovement.EmployeeId = @EmployeeId OR @EmployeeId = 0)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEmployeeEquipmentLoginDetail')
	DROP PROCEDURE prM_GetEmployeeEquipmentLoginDetail
GO

CREATE PROC prM_GetEmployeeEquipmentLoginDetail
 (
	@StartDate		DateTime,
	@EndDate		DateTime,
	@EmployeeId		BigInt,
	@EquipmentId    BigInt
)
AS

 --- Employee Equipment Login
 BEGIN
 SELECT		M_EmployeeEquipmentLogin.ClockingId,
			M_EmployeeEquipmentLogin.EquipmentName,
			M_EmployeeEquipmentLogin.EmployeeId,
			M_EmployeeEquipmentLogin.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			M_EmployeeEquipmentLogin.ClockInDateTime,
			M_EmployeeEquipmentLogin.ClockOutDateTime,
			M_EmployeeEquipmentLogin.Source,
			M_EmployeeEquipmentLogin.Remarks,
			M_EmployeeEquipmentLogin.LastLocation,
			M_EmployeeEquipmentLogin.CreatedBy,
			M_EmployeeEquipmentLogin.CreatedDate,
			M_Equipments.EquipmentId
 FROM		M_EmployeeEquipmentLogin WITH(NOLOCK)
			INNER JOIN C_Employee WITH(NOLOCK) ON C_Employee.EmployeeId = M_EmployeeEquipmentLogin.EmployeeId
			INNER JOIN M_Equipments WITH(NOLOCK) ON M_Equipments.EquipmentName = M_EmployeeEquipmentLogin.EquipmentName
 WHERE		(Convert(Date,M_EmployeeEquipmentLogin.ClockInDateTime) >= @StartDate OR @StartDate = CONVERT(varchar(10),GETDATE(),120))
 AND		(Convert(Date,M_EmployeeEquipmentLogin.ClockOutDateTime) <= @EndDate OR @StartDate = CONVERT(varchar(10),GETDATE(),120))
 AND		(M_EmployeeEquipmentLogin.EmployeeId = @EmployeeId OR @EmployeeId = 0)
 AND        (M_Equipments.EquipmentId = @EquipmentId OR @EquipmentId = 0)
 END
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prM_GetEquipmentsByEquipmentType') AND type in (N'P', N'PC'))
DROP PROCEDURE prM_GetEquipmentsByEquipmentType
GO
 
Create PROCEDURE prM_GetEquipmentsByEquipmentType 
(
	@EquipmentTypeId	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.EquipmentTypeId = @EquipmentTypeId OR @EquipmentTypeId = 0)
	AND		(C_OrganizationNode.OUId = @OUID)
END
GO




 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetEquipmentsByEquipmentTypeId')
	DROP PROC prM_GetEquipmentsByEquipmentTypeId
GO
----------------------------------------------------------------------------
-- Select Records into M_Equipments
---------------------------------------------------------------------------- 
CREATE PROCEDURE prM_GetEquipmentsByEquipmentTypeId
(
	@EquipmentTypeId	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 ,
			M_Equipmentbrandnames.BrandNameId,
		--	M_EquipmentBrands.EquipmentId,
			case when M_EquipmentBrands.EquipmentId  is not null then 'selected' else null end  as Sel_EquipmentId

	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
			left join M_EquipmentBrands  with (nolock) on M_EquipmentBrands.EquipmentId = M_Equipments.EquipmentId  
			LEFT join M_Equipmentbrandnames with (NOLOCK) ON M_Equipmentbrandnames.BrandNameId = M_EquipmentBrands.BrandNameId
	WHERE	(M_Equipments.EquipmentTypeId = @EquipmentTypeId OR @EquipmentTypeId = 0) 
	AND case when M_EquipmentBrands.EquipmentId  is not null then 'selected' else '' end <> 'selected'
	AND		(C_OrganizationNode.OUId = @OUID)
END
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),
	@ShiftBandId	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 @EquipmentTypes = '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)
	AND		(M_EquipmentSchedule.ShiftBandId IN (SELECT  * From fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')
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,
		M_EquipmentSchedule.ShiftBandId
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,
		M_EquipmentSchedule.ShiftBandId
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 sysobjects WHERE name = 'prM_GetEquipmentScheduleByVesselScheduleId')
	DROP PROC prM_GetEquipmentScheduleByVesselScheduleId
GO


CREATE PROC prM_GetEquipmentScheduleByVesselScheduleId
	@VesselScheduleId bigint
AS

SELECT 	M_EquipmentSchedule.EquipmentScheduleId,
		M_EquipmentSchedule.EquipmentTypeId,
		M_EquipmentSchedule.EquipmentId
FROM	M_EquipmentSchedule WITH (NOLOCK)
		INNER JOIN J_Workload WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
WHERE  	J_Workload.VesselScheduleId = @VesselScheduleId

SELECT 1

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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetEquipmentsForScheduleByEquipmentTypeId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetEquipmentsForScheduleByEquipmentTypeId]
GO
 
 
 
create PROC [dbo].[prM_GetEquipmentsForScheduleByEquipmentTypeId]
	@OUId bigint,
	@StartDate DateTime,
	@EndDate DateTime,
	@EquipmentTypeId nVarchar(max) = NULL
	
AS


SELECT	M_Equipments.EquipmentId,
		M_Equipments.EquipmentName, 
		M_Equipments.LocationId, 
		M_Locations.LocationName, 
		M_Equipments.EquipmentTypeId,
		M_EquipmentType.EquipmentType EquipmentTypeName,
		ISNULL(M_EquipmentSchedule.EquipmentScheduleId,0)EquipmentScheduleId
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
		LEFT JOIN M_EquipmentSchedule WITH (NOLOCK) ON  M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
		AND		M_EquipmentSchedule.EndDate > @StartDate AND M_EquipmentSchedule.StartDate < @EndDate
WHERE	(M_Equipments.EquipmentTypeId  IN (SELECT * FROM fnStringToTable(@EquipmentTypeId)) OR IsNull(@EquipmentTypeId,'0') = '0') 
AND		M_Equipments.ActiveStatus=1 and M_Equipments.OUId = @OUId 
AND		M_Equipments.EquipmentId  not in (select equipmentid from M_EquipmentMaintenance WITH (NOLOCK)
	   where EndDate > @StartDate AND StartDate < @EndDate)

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetLasherPlanDetail')
	DROP PROCEDURE prM_GetLasherPlanDetail
GO

CREATE PROC prM_GetLasherPlanDetail
 (
	@PlannedDate		DateTime,
	@ShiftBandId		BigInt
)
AS
  -- Lasher Plan
		SELECT	M_LasherPlan.LasherPlanId,
				M_LasherPlan.PlannedDate,
				M_LasherPlan.ShiftbandId,
				M_LasherPlan.CreatedBy,
				M_LasherPlan.CreatedDate
		FROM	M_LasherPlan   WITH (NOLOCK) 
		WHERE   M_LasherPlan.PlannedDate = @PlannedDate
		AND		M_LasherPlan.ShiftbandId = @ShiftBandId

 -- Lasher Plan Detail
		SELECT	M_LasherPlanDetail.Id,
				M_LasherPlanDetail.LasherPlanId,
				M_LasherPlanDetail.LocationId,
				M_LasherPlanDetail.Requirement,
				M_LasherPlanDetail.CreatedBy,
				M_LasherPlanDetail.CreatedDate,		
				M_VesselSchedule.VesselScheduleId,
				M_VesselSchedule.VesselName 
		FROM	M_LasherPlanDetail   WITH (NOLOCK) 
				INNER JOIN M_LasherPlan WITH (NOLOCK) ON M_LasherPlan.LasherPlanId = M_LasherPlanDetail.LasherPlanId
				INNER JOIN M_VesselSchedule  WITH (NOLOCK) ON M_VesselSchedule.VesselName = M_LasherPlanDetail.VesselName				
		WHERE   M_LasherPlan.PlannedDate = @PlannedDate
		AND		M_LasherPlan.ShiftbandId = @ShiftBandId


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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_GetLocationsByLocationType]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_GetLocationsByLocationType]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_GetLocationsByLocationType]    
(
	@LocationType		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,
			M_Locations.LocationType
	FROM	M_Locations	  WITH (NOLOCK) 
			INNER JOIN C_OrganizationNode with (NOLOCK) ON M_Locations.OUId = C_OrganizationNode.OUId
	WHERE	(M_Locations.LocationType = @LocationType)
	AND		(C_OrganizationNode.OUId = @OUID)
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetResourceSetShiftBands')
	DROP PROC prM_GetResourceSetShiftBands
GO

----------------------------------------------------------------------------
-- Retrieve Available Resource Set ShiftBands 
----------------------------------------------------------------------------
CREATE PROCEDURE prM_GetResourceSetShiftBands
(
	@ResourceSetId	BigInt
)
AS
BEGIN
	SELECT	ResourceSetShiftBandsId,
			ResourceSetId,
			ShiftBandId,
			ActiveStatus,
			CreatedBy,
			CreatedDate,
			UpdatedBy,
			UpdatedDate
	FROM	M_ResourceSetShiftBands
	WHERE	(ResourceSetId = @ResourceSetId OR @ResourceSetId = 0)
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetRTGPlanning')
	DROP PROCEDURE prM_GetRTGPlanning
GO

CREATE PROC prM_GetRTGPlanning
 (
	@PlanDate		DateTime,
	@ShiftBandId	BigInt
)
AS

 ---RTG Plan
 SELECT		M_RTGPlan.RTGPlanId,
			M_RTGPlan.PlanDate,
			M_RTGPlan.ShiftBandId
 FROM		M_RTGPlan WITH(NOLOCK)
 WHERE		Convert(Date,M_RTGPlan.PlanDate) = @PlanDate
 AND		M_RTGPlan.ShiftBandId = @ShiftBandId

 --RTG Plan Detail
 SELECT			M_RTGPlanDetail.RTGPlanDetailId,
				M_RTGPlanDetail.RTGPlanId,
				M_RTGPlanDetail.EquipmentId
 FROM			M_RTGPlanDetail  WITH(NOLOCK)
				INNER JOIN	M_RTGPlan  WITH(NOLOCK) ON M_RTGPlan.RTGPlanId =  M_RTGPlanDetail.RTGPlanId
 WHERE			Convert(Date,M_RTGPlan.PlanDate) = @PlanDate
 AND			M_RTGPlan.ShiftBandId = @ShiftBandId


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetScreenConfiguration')
	DROP PROCEDURE prM_GetScreenConfiguration
GO

   
CREATE PROC prM_GetScreenConfiguration  
 (  
	@ConfigType   BigInt,
	@Id			  BigInt
)  
AS  
  -- Retireve Screen Configuration  
   SELECT M_ScreenConfiguration.Id,  
    M_ScreenConfiguration.ConfigType,  
    M_ScreenConfiguration.ConfigScreen,  
    M_ScreenConfiguration.ConfigName,  
    M_ScreenConfiguration.ConfigValue,  
    M_ScreenConfiguration.ConfigAdditionalValue,
	M_ScreenConfiguration.FieldType  
   FROM   M_ScreenConfiguration WITH (NOLOCK)  
   WHERE  (M_ScreenConfiguration.ConfigType = @ConfigType  OR @ConfigType = 0)
   AND	  (M_ScreenConfiguration.Id = @Id OR @Id = 0)

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

----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_GetShiftAssembleTempleGroup]    
(	
	@ShiftBandId	BigInt,
	@PlanDate		DateTime
)
AS
BEGIN	
   -- M_ShiftAssemble_TemplateGroup
	SELECT  ShiftAssembleId,
			PlanDate,
			ShiftBandId,
			AllocationTemplateId,
			ReliefRuleId,
			ResourceSetId,
			SignOffStatus
	FROM	M_ShiftAssemble_TemplateGroup WITH(NOLOCK)
	WHERE	Convert(Date,PlanDate) = CONVERT(Date,@PlanDate)
	AND		ShiftBandId = @ShiftBandId

	--M_ShiftAssemble_TemplateGroupDetail
	SELECT  ShiftAssembleDetId,
			M_ShiftAssemble_TemplateGroupDetail.ShiftAssembleId,
			TypeId,
			SkillId,
			EquipmentTypeId,
			Requirement,
			LocationId,
			Remarks
	 FROM   M_ShiftAssemble_TemplateGroupDetail WITH(NOLOCK)
			INNER JOIN M_ShiftAssemble_TemplateGroup WITH(NOLOCK) ON M_ShiftAssemble_TemplateGroup.ShiftAssembleId = M_ShiftAssemble_TemplateGroupDetail.ShiftAssembleId
	 WHERE	Convert(Date,PlanDate) = CONVERT(Date,@PlanDate)
	 AND	ShiftBandId = @ShiftBandId
END
GO
 

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

----------------------------------------------------------------------------
-- Returns List of Signed Off Shifts By Selected Dates Shift Bands And Equipment Type
----------------------------------------------------------------------------
CREATE PROC prM_GetShiftSignOffByDateShiftBandsEqTypes
(
	@OUId			BigInt,
	@ShiftDate		DateTime,
	@ShiftBands		nVarchar(500),
	@EquipmentTypes	nVarchar(1000) = NULL
)
AS
	IF(@EquipmentTypes IS NULL)
	BEGIN
		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, 
				EquipmentTypes,
				ActivityGenerationRuleId,
				AllocationRuleId
		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,ShiftDate) = Convert(Date, @ShiftDate)
		AND		(M_ShiftSignOffStatus.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
	END
	ELSE 
	BEGIN
			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, 
					EquipmentTypes,
					ActivityGenerationRuleId,
					AllocationRuleId
			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,ShiftDate) = Convert(Date, @ShiftDate)
			AND		(M_ShiftSignOffStatus.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
			AND		M_ShiftSignOffStatus.EquipmentTypes IN (@EquipmentTypes)
	END
	--ORDER BY M_ShiftSignOffStatus.StartTime DESC
GO





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

----------------------------------------------------------------------------
-- Retrieve Shift Sign Off Status Between Dates By OU
----------------------------------------------------------------------------
CREATE PROC prM_GetShiftSignOffStatusBetweenDates
	@OUId		BigInt,
	@StartDate	DateTime,
	@EndDate	DateTime
AS
	SELECT	StatusId,
			M_ShiftSignOffStatus.ShiftBandId,
			D_ShiftBand.ShiftBandName,
			M_ShiftSignOffStatus.ShiftDate,
			M_ShiftSignOffStatus.StartTime,
			M_ShiftSignOffStatus.EndTime
	FROM	M_ShiftSignOffStatus WITH (NOLOCK) 
			INNER JOIN D_ShiftBand WITH (NOLOCK) ON M_ShiftSignOffStatus.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE	M_ShiftSignOffStatus.OUId			=	@OUId	
	AND		M_ShiftSignOffStatus.ShiftDate		>=	@StartDate
	AND		M_ShiftSignOffStatus.ShiftDate		<=	@EndDate
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,
	@EquipmentTypes nVarchar(100) = 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,
			EquipmentTypes,
			ActivityGenerationRuleId,
			AllocationRuleId
	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
	AND		(M_ShiftSignOffStatus.EquipmentTypes	=	@EquipmentTypes OR @EquipmentTypes = '')
GO

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

----------------------------------------------------------------------------
-- Retrieve Shift Sign off Status By Date And OU
----------------------------------------------------------------------------
CREATE PROC prM_GetShiftSignOffStatusByDateAndOU
	@SelectedDate	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,
			EquipmentTypes
	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)
	AND		M_ShiftSignOffStatus.OUId = @OUId
	ORDER BY M_ShiftSignOffStatus.EndTime DESC
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,
	@SearchCondition	Int = 0 -- 1 = Start, 2 = End, 0 = Both
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.StartTime,120) >= Convert(DateTime,@DateTimeToValidate,120)
	AND		Convert(DateTime,M_ShiftSignOffStatus.EndTime,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_GetStackersPlanning')
	DROP PROCEDURE prM_GetStackersPlanning
GO

CREATE PROC prM_GetStackersPlanning
 (
	@PlanDate		 DateTime,
	@ShiftBandId	 BigInt,
	@EquipmentTypeId BigInt
)
AS

 ---Stackers Plan
 SELECT		M_StackersPlan.StackersPlanId,
			M_StackersPlan.PlanDate,
			M_StackersPlan.ShiftBandId,
			M_StackersPlan.EquipmentTypeId
 FROM		M_StackersPlan WITH(NOLOCK)
 WHERE		Convert(Date,M_StackersPlan.PlanDate) = @PlanDate
 AND		M_StackersPlan.ShiftBandId = @ShiftBandId
 AND		(M_StackersPlan.EquipmentTypeId = @EquipmentTypeId OR @EquipmentTypeId = 0) 

 --Stackers Plan Detail
 SELECT			M_StackersPlanDetail.StackersPlanDetailId,
				M_StackersPlanDetail.StackersPlanId,
				M_StackersPlanDetail.EquipmentId
 FROM			M_StackersPlanDetail  WITH(NOLOCK)
				INNER JOIN	M_StackersPlan  WITH(NOLOCK) ON M_StackersPlan.StackersPlanId =  M_StackersPlanDetail.StackersPlanId
 WHERE			Convert(Date,M_StackersPlan.PlanDate) = @PlanDate
 AND			M_StackersPlan.ShiftBandId = @ShiftBandId
 AND			(M_StackersPlan.EquipmentTypeId = @EquipmentTypeId OR @EquipmentTypeId = 0) 


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetTabReaderPlanDetail')
	DROP PROCEDURE prM_GetTabReaderPlanDetail
GO

CREATE PROC prM_GetTabReaderPlanDetail
 (
	@PlannedDate		DateTime,
	@ShiftBandId		BigInt
)
AS
  -- Top Man Plan
		SELECT	M_TabReaderPlan.TabReaderPlanId,
				M_TabReaderPlan.PlannedDate,
				M_TabReaderPlan.ShiftbandId,
				M_TabReaderPlan.CreatedBy,
				M_TabReaderPlan.CreatedDate
		FROM	M_TabReaderPlan   WITH (NOLOCK) 
		WHERE   M_TabReaderPlan.PlannedDate = @PlannedDate
		AND		M_TabReaderPlan.ShiftbandId = @ShiftBandId

 -- Top Man Plan Detail
		SELECT	M_TabReaderPlanDetail.Id,
				M_TabReaderPlanDetail.TabReaderPlanId,
				M_TabReaderPlanDetail.VesselScheduleId,
				M_TabReaderPlanDetail.Requirement,
				M_TabReaderPlanDetail.CreatedBy,
				M_TabReaderPlanDetail.CreatedDate,
				M_VesselSchedule.VesselName,
				M_VesselSchedule.VisitId,
				M_Berth.Berth,
				M_VesselSchedule.StartDate,
				M_VesselSchedule.EndDate
		FROM	M_TabReaderPlanDetail   WITH (NOLOCK) 
				INNER JOIN M_TabReaderPlan WITH (NOLOCK) ON M_TabReaderPlan.TabReaderPlanId = M_TabReaderPlanDetail.TabReaderPlanId
				INNER JOIN M_VesselSchedule WITH (NOLOCK) ON M_VesselSchedule.VesselScheduleId = M_TabReaderPlanDetail.VesselScheduleId
				INNER JOIN M_Berth  WITH (NOLOCK) ON M_VesselSchedule.BerthId = M_Berth.BerthId
		WHERE   M_TabReaderPlan.PlannedDate = @PlannedDate
		AND		M_TabReaderPlan.ShiftbandId = @ShiftBandId


GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_GetTopManPlanDetail')
	DROP PROCEDURE prM_GetTopManPlanDetail
GO

CREATE PROC prM_GetTopManPlanDetail
 (
	@PlannedDate		DateTime,
	@ShiftBandId		BigInt
)
AS
  -- Top Man Plan
		SELECT	M_TopManPlan.TopManPlanId,
				M_TopManPlan.PlannedDate,
				M_TopManPlan.ShiftbandId,
				M_TopManPlan.CreatedBy,
				M_TopManPlan.CreatedDate
		FROM	M_TopManPlan   WITH (NOLOCK) 
		WHERE   M_TopManPlan.PlannedDate = @PlannedDate
		AND		M_TopManPlan.ShiftbandId = @ShiftBandId

 -- Top Man Plan Detail
		SELECT	M_TopManPlanDetail.Id,
				M_TopManPlanDetail.TopManPlanId,
				M_TopManPlanDetail.CraneScheduleId,
				M_TopManPlanDetail.CreatedBy,
				M_TopManPlanDetail.CreatedDate,
				M_Cranes.CraneId,
				M_Cranes.CraneNumber
		FROM	M_TopManPlanDetail   WITH (NOLOCK) 
				INNER JOIN M_TopManPlan WITH (NOLOCK) ON M_TopManPlan.TopManPlanId = M_TopManPlanDetail.TopManPlanId
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON M_CraneSchedule.CraneScheduleId = M_TopManPlanDetail.CraneScheduleId
				INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
		WHERE   M_TopManPlan.PlannedDate = @PlannedDate
		AND		M_TopManPlan.ShiftbandId = @ShiftBandId


GO

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

----------------------------------------------------------------------------
-- Retrieve Shift Sign Off Status By Selected Date And Time
----------------------------------------------------------------------------
CREATE PROC prM_GetValidateShiftSignOffStatusByDate
	@StartDateTime	DateTime,
	@EndDateTime	DateTime
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, 
			EquipmentTypes,
			ActivityGenerationRuleId,
			AllocationRuleId
	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) > Convert(DateTime,@StartDateTime)
	AND		Convert(DateTime,M_ShiftSignOffStatus.StartTime) < Convert(DateTime,@EndDateTime)
	ORDER BY M_ShiftSignOffStatus.StartTime DESC
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,
	@ShiftBandId	BigInt = 0
	--@SignOffShiftStatus	Bit
AS
BEGIN
	DECLARE @ReliefBreakId BigInt = 0

	SELECT	@ReliefBreakId = CAST(IsNull(ParamValue,0) AS bigint) 
	FROM	D_SystemParams WITH (NOLOCK) 
	Where ParamName ='ReliefBreakId'

	-- 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,
				IsNull(D_MasterCodes.CodeValue,'') AS CranePriority,
				IsNull(J_Workload.LocationId,0) LocationId
		FROM	J_Workload WITH (NOLOCK)
				INNER JOIN M_CraneSchedule WITH (NOLOCK) ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON M_CraneSchedule.CranePriorityId = D_MasterCodes.CodeId
		WHERE	J_Workload.OUId =	@OUId 
		AND		SkillId			=	@SkillId 
		AND		WorkType		=	@WorkType 
		--AND		J_Workload.SignOffStatus	=	@SignOffShiftStatus
		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, D_MasterCodes.CodeValue

		 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_Activity.ProgresstionState = 1
		 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 != @ReliefBreakId
		 GROUP BY J_Activity.WorkloadId
	end
	else if @WorkType = 2
	begin

		SELECT	WorkloadId, 
				SkillId,
				StartTime,
				EndTime,
				IsNull(M_EquipmentSchedule.EquipmentId,0) 'EquipmentId', 
				J_Workload.OUId,
				DATEDIFF ( MINUTE, StartTime , EndTime ) 'Duration',
				J_Workload.EquipmentScheduleId 'ScheduleId',
				'' AS CranePriority,
				IsNull(J_Workload.LocationId,0) LocationId
		FROM	J_Workload WITH (NOLOCK) 
				--INNER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
		WHERE	J_Workload.OUId			=	@OUId 
		AND		SkillId					=	@SkillId 
		AND		WorkType				=	@WorkType 
		--AND		J_Workload.SignOffStatus = @SignOffShiftStatus
		AND		(J_Workload.ShiftBandId =	@ShiftBandId OR J_Workload.ShiftBandId = 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) 
		 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.ShiftBandId = @ShiftBandId OR J_Workload.ShiftBandId = 0) 
		 AND	J_Activity.ProgresstionState = 1
		 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 != @ReliefBreakId
		 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, '' AS CranePriority
		from J_Workload WITH (NOLOCK)
			where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType 
		--AND	J_Workload.SignOffStatus = @SignOffShiftStatus
		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_Activity.ProgresstionState = 1
		 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 != @ReliefBreakId
		 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', '' AS CranePriority,
		IsNull(J_Workload.LocationId,0) LocationId
		from J_Workload WITH (NOLOCK)
		LEFT OUTER join M_VesselSchedule WITH (NOLOCK) on J_Workload.VesselScheduleId = M_VesselSchedule.VesselScheduleId
		where J_Workload.OUId =@OUId and SkillId=@SkillId and WorkType=@WorkType 
		--AND J_Workload.SignOffStatus = @SignOffShiftStatus
		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_Activity.ProgresstionState = 1
		 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 != @ReliefBreakId
		 GROUP BY J_Activity.WorkloadId
	end

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_LasherPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LasherPlanDetailIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_LasherPlanDetailIns]    
(
   @LasherPlanDetail UTM_LasherPlanDetail readonly	
)
AS
BEGIN
	Merge M_LasherPlanDetail as Target Using @LasherPlanDetail as Source on(Target.LasherPlanId =Source.LasherPlanId and Target.LocationId=Source.LocationId)	
	When Not Matched By Target Then
	Insert (LasherPlanId,LocationId,Requirement,VesselName,CreatedBy,CreatedDate) 
	Values (Source.LasherPlanId,Source.LocationId,Source.Requirement,Source.VesselName,Source.CreatedBy,getdate());	
	select 1
END

GO
  IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LasherPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LasherPlanIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_LasherPlanIns]    
(
	@PlannedDate  				DateTime,
	@ShiftBandId				BigInt,	
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_LasherPlan
	(PlannedDate,ShiftbandId, CreatedBy, CreatedDate)
	VALUES(@PlannedDate,@ShiftBandId, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_LasherPlanningDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_LasherPlanningDel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_LasherPlanningDel]    
(
	@LasherPlanId				BigInt
)
AS
BEGIN

	DELETE FROM M_LasherPlan 
	WHERE		M_LasherPlan.LasherPlanId = @LasherPlanId

	DELETE FROM M_LasherPlanDetail
	WHERE		M_LasherPlanDetail.LasherPlanId = @LasherPlanId	


	SELECT @LasherPlanId
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),	
	@LocationType			bigint
)
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,LocationType)
		VALUES(@LocationName, @LocationDesc,@OUId,@ActiveStatus,@CreatedBy, GETDATE(),@LocationType)

		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,
			M_Locations.LocationType
	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),
	@LocationType			bigint
)
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(),
				LocationType			=   @LocationType				
		WHERE	LocationId				=	@LocationId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
go
 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_MatrixTemplateGroupDel')
	DROP PROC prM_MatrixTemplateGroupDel
GO
----------------------------------------------------------------------------
-- delete Records from E_EqipmentMatrixGroupTemplDet
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_MatrixTemplateGroupDel]
(
	@TemplateGroupId		BigInt ,
	@MatrixId		BigInt
)
AS
BEGIN
	DELETE FROM 	E_EqipmentMatrixGroupTemplDet 
	WHERE	TemplateGroupId	=	@TemplateGroupId and MatrixId =@MatrixId

	SELECT 1
END
GO



 
 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_MatrixTemplateGroupIns')
	DROP PROC prM_MatrixTemplateGroupIns
GO
----------------------------------------------------------------------------
-- Insert Records into E_EqipmentMatrixGroupTemplDet
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_MatrixTemplateGroupIns]    
(		
	@TemplateGroupId			Bigint, 
	@MatrixId					bigint , 
	@CreatedBy					nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EqipmentMatrixGroupTemplDet WITH (NOLOCK)
	WHERE	TemplateGroupId=@TemplateGroupId and MatrixId=@MatrixId 

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EqipmentMatrixGroupTemplDet
		( TemplateGroupId,MatrixId,CreatedBy, CreatedDate)
		VALUES(@TemplateGroupId,@MatrixId,@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_PMPlanningDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningDel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_PMPlanningDel]    
(
	@PMPlanningId				BigInt
)
AS
BEGIN

	DELETE FROM M_PMPlanningSkills 
	WHERE		M_PMPlanningSkills.PMPlanningId = @PMPlanningId

	DELETE FROM M_PMPlanningLocation
	WHERE		M_PMPlanningLocation.PMPlanningId = @PMPlanningId	

	DELETE FROM M_PMPlanning 
	WHERE		M_PMPlanning.PMPlanningId = @PMPlanningId

	

	SELECT @PMPlanningId
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningIns]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningUpd]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_PMPlanningIns]    
(
	@PlanningDate  				DateTime,
	@ShiftBandId				nVarchar(100),
	@ActivityGenerationRuleId	BigInt,
	@AllocationRuleId			BigInt,
	@OUId						BigInt,
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_PMPlanning
	(PlanningDate,ShiftBandId, CreatedBy, CreatedDate,ActivityGenerationRuleId,AllocationRuleId,OUId)
	VALUES(@PlanningDate,@ShiftBandId, @CreatedBy, GETDATE(),@ActivityGenerationRuleId,@AllocationRuleId,@OUId)

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningLocationIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningLocationIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_PMPlanningLocationIns]    
(
   @PMPlanningLocation UTM_PMPlanningLocation readonly	
)
AS
BEGIN

	Merge M_PMPlanningLocation as Target Using @PMPlanningLocation as Source on(Target.PMPlanningLocationId =Source.PMPlanningLocationId and Target.PMPlanningId =Source.PMPlanningId)
	When Not Matched By Target Then
	Insert (PMPlanningId,LocationId,SkillId,Requirement,CreatedBy,CreatedDate) 
	Values (Source.PMPlanningId,Source.LocationId,Source.SkillId,Source.Requirement,Source.CreatedBy,getdate())
	When Matched Then
	Update Set	Target.LocationId=Source.LocationId,
				Target.SkillId=Source.SkillId,
				Target.Requirement=Source.Requirement,
				Target.UpdatedBy=Source.UpdatedBy,
				Target.UpdatedDate=getdate()
	When Not Matched By Source and Target.PMPlanningId in (select PMPlanningId from @PMPlanningLocation) Then
	delete;

	select 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_PMPlanningSkillIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_PMPlanningSkillIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_PMPlanningSkillIns]    
(
   @PMPlanningSkills UTM_PMPlanningSkills readonly	
)
AS
BEGIN

	Merge M_PMPlanningSkills as Target Using @PMPlanningSkills as Source on(Target.PMPlanningSkillId =Source.PMPlanningSkillId and Target.PMPlanningId =Source.PMPlanningId)	
	When Not Matched By Target Then
	Insert (PMPlanningId,SkillId,Requirement,CreatedBy,CreatedDate) 
	Values (Source.PMPlanningId,Source.SkillId,Source.Requirement,Source.CreatedBy,getdate())
	When Matched Then
	Update Set Target.Requirement=Source.Requirement,
			   Target.SkillId =Source.SkillId,	
			   Target.UpdatedBy=Source.UpdatedBy,
			   Target.UpdatedDate=getdate()
	When Not Matched By Source and Target.PMPlanningId in (select PMPlanningId from @PMPlanningSkills) Then
	delete;

	select 1
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),
	@EquipmentTypes			nVarchar(500) = NULL,
	@UpdateEquipmentTypes	nVarchar(500) = NULL,
	@StatusId				BigInt = 0,
	@SkillsToRevoke			nVarchar(500) = NULL
)
AS
BEGIN 
	DECLARE @SkillIds nVarchar(500) = NULL
	-- Get Required Skills By Selected Equipment Types.
	If (@EquipmentTypes IS NOT NULL)
	BEGIN
		IF (CHARINDEX('0', @EquipmentTypes) > 0)
		BEGIN
			SELECT @SkillIds = COALESCE(@SkillIds + ',', '') + Convert(nVarchar(10),M_Crane_Requirement.SkillId)
			FROM	M_Crane_Requirement WITH (NOLOCK)
					INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_Crane_Requirement.SkillId
			WHERE	M_Crane_Requirement.OUId	=	@OUId
		END

		IF (@SkillsToRevoke IS NULL OR @SkillsToRevoke = '')
		BEGIN
			SELECT @SkillIds = COALESCE(@SkillIds + ',', '') + Convert(nVarchar(10),M_EquipmentType_Requirement.SkillId)
			FROM	M_EquipmentType_Requirement WITH (NOLOCK) 
					INNER JOIN M_EquipmentType WITH (NOLOCK) 
						ON M_EquipmentType_Requirement.EquipmentTypeId = M_EquipmentType.EquipmentTypeId
					INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = M_EquipmentType_Requirement.SkillId
			WHERE	M_EquipmentType.OUId	=	@OUId
			AND		M_EquipmentType.EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes))
		END
		ELSE SET @SkillIds = @SkillsToRevoke;
	END


	If(@EquipmentTypes IS NULL)
	BEGIN
		DELETE FROM J_ActivityAttributes  
		WHERE ActivityId IN (SELECT Activityid FROM J_Activity WITH (NOLOCK)
							 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 OR IsNull(ShiftBandId,0) = 0)
		AND		OUId		=	@OUId;

		-- Revoke By Equipment Types
		UPDATE	M_EquipmentSchedule SET SignOffStatus = 0
		WHERE	StartDate	>=	@StartTime 
		AND		StartDate	<	@EndTime 
		AND		(ShiftBandId	=	@ShiftBandId OR IsNull(ShiftBandId,0) = 0)
		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		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 StatusId		=	@StatusId
		--StartTime	>=	@StartTime 
		--AND		StartTime	<	@EndTime 
		--AND		ShiftBandId =	@ShiftBandId 
		--AND		OUId		=	@OUId;

	END
	Else
	BEGIN
		DECLARE @ReliefBreakSkillId nVarchar(10) = '0'

		-- Retrieve Relief Break Id From System Parameters And Add To Signed Off Skills
		SELECT @ReliefBreakSkillId = ParamValue
		FROM D_SystemParams WITH (NOLOCK) WHERE ParamName ='ReliefBreakId'

		-- Add Relief Break Id Signed Off Skills
		If (@SkillIds IS NOT NULL) SET @SkillIds = @SkillIds + ',' + @ReliefBreakSkillId
		IF(CHARINDEX('0',@EquipmentTypes) > 0)
		BEGIN
			DELETE FROM J_ActivityAttributes  
			WHERE ActivityId IN (SELECT Activityid FROM J_Activity WITH (NOLOCK)
								 WHERE	ShiftBandId =	@ShiftBandId 
								 AND	OUId		=	@OUId
								 AND		WorkloadId IN (SELECT WorkLoadId FROM J_Workload  WITH (NOLOCK)
															WHERE	Convert(DateTime,EndTime)	>	Convert(DateTime,@StartTime)
															AND		Convert(DateTime,StartTime)	<	Convert(DateTime,@EndTime)
															AND		OUId		=	@OUId
															AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds))
														  )
								 AND	SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)));

			DELETE FROM J_Activity
			WHERE		ShiftBandId =	@ShiftBandId 
			AND		OUId		=	@OUId
			AND		WorkloadId IN (SELECT WorkLoadId FROM J_Workload  WITH (NOLOCK)
									WHERE	Convert(DateTime,EndTime)	>	Convert(DateTime,@StartTime)
									AND		Convert(DateTime,StartTime)	<	Convert(DateTime,@EndTime)
									AND		OUId		=	@OUId
									AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds))
								  )
			AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));

		
			UPDATE J_Workload  SET SignOffStatus = 0
			WHERE	Convert(DateTime,EndTime)		>	Convert(DateTime,@StartTime)
			AND		Convert(DateTime,StartTime)		<	Convert(DateTime,@EndTime)
			AND		OUId		=	@OUId
			AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));	
		END
		ELSE
		BEGIN
			DELETE FROM J_ActivityAttributes  
			WHERE ActivityId IN (SELECT Activityid FROM J_Activity WITH (NOLOCK)
								 --WHERE	StartTime	>=	@StartTime 
								 --AND	StartTime	<	@EndTime 
								 WHERE	ShiftBandId =	@ShiftBandId 
								 AND	OUId		=	@OUId
								 AND		WorkloadId IN (SELECT WorkLoadId FROM J_Workload  WITH (NOLOCK)
															WHERE	Convert(DateTime,StartTime)	>=	Convert(DateTime,@StartTime)
															AND		Convert(DateTime,EndTime)	<=	Convert(DateTime,@EndTime)
															AND		OUId		=	@OUId
															AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds))
														  )
								 AND	SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)));

			DELETE FROM J_Activity
			--WHERE	StartTime	>=	@StartTime 
			--AND		StartTime	<	@EndTime 
			WHERE		ShiftBandId =	@ShiftBandId 
			AND		OUId		=	@OUId
			AND		WorkloadId IN (SELECT WorkLoadId FROM J_Workload  WITH (NOLOCK)
									WHERE	Convert(DateTime,StartTime)	>=	Convert(DateTime,@StartTime)
									AND		Convert(DateTime,EndTime)	<=	Convert(DateTime,@EndTime)
									AND		OUId		=	@OUId
									AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds))
								  )
			AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));


			DELETE FROM J_Workload 
			WHERE	Convert(DateTime,StartTime)		>=	Convert(DateTime,@StartTime)
			AND		Convert(DateTime,EndTime)		<=	Convert(DateTime,@EndTime)
			AND		OUId		=	@OUId
			AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));

			DELETE FROM M_EquipmentSchedule
			WHERE	Convert(DateTime,StartDate)	>=	Convert(DateTime,@StartTime)
			AND		Convert(DateTime,EndDate)	<=	Convert(DateTime,@EndTime)
			AND		ShiftBandId = @ShiftBandId
			AND		OUId		=	@OUId
			AND		EquipmentTypeId IN (SELECT * FROM fnStringToTable(@EquipmentTypes));
		END
		-- Update Only If Crane Equipment Type Is Selected
		IF(CHARINDEX('0',@EquipmentTypes) > 0)
		BEGIN
			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;
		END

		DELETE	FROM  M_AuxiliaryWork --SET SignOffStatus = 0
		WHERE	Convert(DateTime,StartDate)	>=	Convert(DateTime,@StartTime)
		AND		Convert(DateTime,EndDate)	<=	Convert(DateTime,@EndTime)
		AND		ShiftBandId	=	@ShiftBandId
		AND		OUId		=	@OUId
		AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));

		DELETE	FROM  J_Workload --SET SignOffStatus = 0
		WHERE	Convert(DateTime,EndTime)		>	Convert(DateTime,@StartTime)
		AND		Convert(DateTime,StartTime)	<	Convert(DateTime,@EndTime)
		AND		WorkType	=	3	-- Delete Auxiliary Work
		AND		OUId		=	@OUId
		AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));

		If (@UpdateEquipmentTypes IS NULL)
			DELETE FROM  M_ShiftSignOffStatus
			WHERE	StatusId	=	@StatusId
		Else
			Update	M_ShiftSignOffStatus
			SET		EquipmentTypes	=	@UpdateEquipmentTypes
			WHERE	StatusId		=	@StatusId


		DELETE FROM J_Activity WHERE EndTime < StartTime

		DELETE FROM J_SlashedCranes 
		WHERE	Convert(date,ShiftDate) = Convert(date,@StartTime)
		--AND		Convert(DateTime,ActivityEnd) <= Convert(DateTime,@EndTime)
		AND		J_SlashedCranes.ShiftBandId	= @ShiftBandId
		--AND		SkillId IN (SELECT * FROM fnStringToTable(@SkillIds));
		--StartTime	>=	@StartTime 
		--AND		StartTime	<	@EndTime 
		--AND		ShiftBandId =	@ShiftBandId 
		--AND		OUId		=	@OUId;

	END

	-- Change Status By Equipment Types
	SELECT 1;
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_RTGPlanDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_RTGPlanDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_RTGPlanDel]    
(	
	 @RTGPlanId BigInt,
	 @EquipmentTyeId BigInt,
	 @ShiftBandId BigInt,
	 @OuId BigInt,
	 @PlanDate DateTime
)
AS
BEGIN
-- Delete RTG Plan
		DELETE FROM M_RTGPlan WHERE RTGPlanId = @RTGPlanId
-- Delete RTG Plan Detail
		DELETE FROM M_RTGPlanDetail WHERE RTGPlanId = @RTGPlanId
--Delete WorkLoad
		DELETE FROM J_Workload WHERE EquipmentScheduleId IN
				(SELECT EquipmentScheduleId FROM M_EquipmentSchedule  WITH(NOLOCK)
					WHERE EquipmentTypeId = @EquipmentTyeId
					AND	  ShiftBandId	 = @ShiftBandId
					AND   OuId			 = @OuId
					AND	  Convert(Date,StartDate) = @PlanDate )
  --Delete Equipment Schedule
       DELETE FROM M_EquipmentSchedule
					WHERE EquipmentTypeId = @EquipmentTyeId
					AND	  ShiftBandId	 = @ShiftBandId
					AND   OuId			 = @OuId
					AND	  Convert(Date,StartDate) = @PlanDate
		SELECT 1
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_RTGPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_RTGPlanDetailIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_RTGPlanDetailIns]    
(
	 @RTGPlanDetail UTM_RTGPlanDetail readonly	
)
AS
BEGIN
	
	Merge M_RTGPlanDetail as Target Using @RTGPlanDetail as Source on(Target.EquipmentId = Source.EquipmentId 
									and Target.RTGPlanId = Source.RTGPlanId)
	When Not Matched By Target Then
	Insert (RTGPlanId,EquipmentId,CreatedBy,CreatedDate) 
	Values (Source.RTGPlanId,Source.EquipmentId,Source.CreatedBy,getdate());
	
	
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_RTGPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_RTGPlanIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_RTGPlanIns]    
(	
	 @PlanDate DateTime,
	 @ShiftBandId BigInt,
	 @CreatedBy nVarchar(100)
)
AS
BEGIN

	Insert Into M_RTGPlan (PlanDate,ShiftBandId,CreatedBy,CreatedDate)
			Values (@PlanDate,@ShiftBandId,@CreatedBy,GETDATE())

	SELECT SCOPE_IDENTITY();
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ScreenConfigurationIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ScreenConfigurationIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_ScreenConfigurationIns]    
(
	@ConfigType				Bigint,
	@ConfigScreen			nVarchar(1000),
	@ConfigName				nVarchar(2000),
	@ConfigValue			nVarchar(2000),	
	@ConfigAdditionalValue  nVarchar(100),		
	@CreatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_ScreenConfiguration WITH (NOLOCK)
	WHERE	ConfigType =@ConfigType AND ConfigName=@ConfigName AND ConfigValue =@ConfigValue

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO M_ScreenConfiguration
		(ConfigType,ConfigScreen, ConfigName,ConfigValue,ConfigAdditionalValue,CreatedBy, CreatedDate)
		VALUES(@ConfigType, @ConfigScreen,@ConfigName,@ConfigValue,@ConfigAdditionalValue,@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_ScreenConfigurationUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ScreenConfigurationUpd]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_ScreenConfigurationUpd]    
(
	@Id						Bigint, 
	@ConfigType				Bigint,
	@ConfigScreen			nVarchar(1000),
	@ConfigName				nVarchar(2000),
	@ConfigValue			nVarchar(2000),	
	@ConfigAdditionalValue  nVarchar(100),		
	@UpdatedBy				nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	M_ScreenConfiguration WITH (NOLOCK)
	WHERE	Id !=@Id AND ConfigType = @ConfigType AND ConfigName=@ConfigName AND ConfigValue =@ConfigValue

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE M_ScreenConfiguration 
		SET	   M_ScreenConfiguration.ConfigValue			= @ConfigValue,
			   M_ScreenConfiguration.ConfigAdditionalValue  = @ConfigAdditionalValue,
			   M_ScreenConfiguration.UpdatedBy				= @UpdatedBy,
			   M_ScreenConfiguration.UpdatedDate		    = GetDate()
		WHERE  M_ScreenConfiguration.Id = @Id

		SELECT @Id;

	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_ShiftAssemble_TemplateGroupDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupDetailIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupDetailIns]    
(
   @ShiftAssembleTemplateGroupDetail UTM_ShiftAssemble_TemplateGroupDetail readonly	
)
AS
BEGIN

	Merge M_ShiftAssemble_TemplateGroupDetail as Target Using @ShiftAssembleTemplateGroupDetail as Source on(Target.ShiftAssembleDetId = Source.ShiftAssembleDetId and Target.ShiftAssembleId =Source.ShiftAssembleId)	
	When Not Matched By Target Then
	Insert (ShiftAssembleId,TypeId,EquipmentTypeId,SkillId,Requirement,LocationId,CreatedBy,CreatedDate,Remarks) 
	Values (Source.ShiftAssembleId,Source.TypeId,Source.EquipmentTypeId,Source.SkillId,Source.Requirement,Source.LocationId,Source.CreatedBy,getdate(),Source.Remarks)
	When Matched Then
	Update Set Target.TypeId				=	Source.TypeId,
			   Target.EquipmentTypeId		=	Source.EquipmentTypeId,	
			   Target.SkillId				=	Source.SkillId,	
			   Target.Requirement			=	Source.Requirement,
			   Target.LocationId			=	Source.LocationId,
			   Target.UpdatedBy				=	Source.UpdatedBy,
			   Target.UpdatedDate			=	getdate(),			   
			   Target.Remarks				=	Source.Remarks
	When Not Matched By Source and Target.ShiftAssembleId in (select ShiftAssembleId from @ShiftAssembleTemplateGroupDetail) Then
	delete;

	select 1
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ShiftAssemble_TemplateGroupIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupIns]    
(
	@PlanDate  					DateTime,
	@ShiftBandId				BigInt,
	@ResourceSetId				BigInt,
	@AllocationTemplateId		BigInt,
	@ReliefRuleId				BigInt,
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_ShiftAssemble_TemplateGroup
	(PlanDate,ShiftBandId,ResourceSetId, AllocationTemplateId,ReliefRuleId,SignOffStatus,CreatedBy,CreatedDate)
	VALUES(@PlanDate,@ShiftBandId,@ResourceSetId,@AllocationTemplateId,@ReliefRuleId,1,@CreatedBy,GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_ShiftAssemble_TemplateGroupUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupUpd]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_ShiftAssemble_TemplateGroupUpd]    
(
	@ShiftAssembleId			BigInt,
	@PlanDate  					DateTime,
	@ShiftBandId				BigInt,
	@ResourceSetId				BigInt,
	@AllocationTemplateId		BigInt,
	@ReliefRuleId				BigInt,
	@UpdatedBy					nVarchar(50)
)
AS
BEGIN

	UPDATE M_ShiftAssemble_TemplateGroup
	SET	   PlanDate				= @PlanDate,
		   ShiftBandId			= @ShiftBandId,
		   ResourceSetId		= @ResourceSetId,
		   AllocationTemplateId = @AllocationTemplateId,
		   ReliefRuleId			= @ReliefRuleId,
		   UpdatedBy			= @UpdatedBy,
		   UpdatedDate			= GETDATE()
	WHERE  ShiftAssembleId		= @ShiftAssembleId

	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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_StackersPlanDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_StackersPlanDel]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_StackersPlanDel]    
(	
	 @StackersPlanId BigInt,
	 @EquipmentTyeId BigInt,
	 @ShiftBandId BigInt,
	 @OuId BigInt,
	 @PlanDate DateTime
)
AS
BEGIN
-- Delete Stackers Plan
		DELETE FROM M_StackersPlan WHERE StackersPlanId = @StackersPlanId
-- Delete Stackers Plan Detail
		DELETE FROM M_StackersPlanDetail WHERE StackersPlanId = @StackersPlanId
--Delete WorkLoad
		DELETE FROM J_Workload WHERE EquipmentScheduleId IN
				(SELECT EquipmentScheduleId FROM M_EquipmentSchedule  WITH(NOLOCK)
					WHERE EquipmentTypeId = @EquipmentTyeId
					AND	  ShiftBandId	 = @ShiftBandId
					AND   OuId			 = @OuId
					AND	  Convert(Date,StartDate) = @PlanDate )
  --Delete Equipment Schedule
       DELETE FROM M_EquipmentSchedule
					WHERE EquipmentTypeId = @EquipmentTyeId
					AND	  ShiftBandId	 = @ShiftBandId
					AND   OuId			 = @OuId
					AND	  Convert(Date,StartDate) = @PlanDate
		SELECT 1
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_StackersPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_StackersPlanDetailIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_StackersPlanDetailIns]    
(
	 @StackersPlanDetail UTM_StackersPlanDetail readonly	
)
AS
BEGIN
	
	Merge M_StackersPlanDetail as Target Using @StackersPlanDetail as Source on(Target.EquipmentId = Source.EquipmentId 
									and Target.StackersPlanId = Source.StackersPlanId)
	When Not Matched By Target Then
	Insert (StackersPlanId,EquipmentId,CreatedBy,CreatedDate) 
	Values (Source.StackersPlanId,Source.EquipmentId,Source.CreatedBy,getdate());	

END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_StackersPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_StackersPlanIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_StackersPlanIns]    
(	
	 @PlanDate DateTime,
	 @ShiftBandId BigInt,
	 @CreatedBy nVarchar(100),
	 @EquipmentTypeId BigInt
)
AS
BEGIN
	Insert Into M_StackersPlan (PlanDate,ShiftBandId,CreatedBy,CreatedDate,EquipmentTypeId)
			Values (@PlanDate,@ShiftBandId,@CreatedBy,GETDATE(),@EquipmentTypeId)

	SELECT SCOPE_IDENTITY();
END
go
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TabReaderPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TabReaderPlanDetailIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_TabReaderPlanDetailIns]    
(
   @TabReaderPlanDetail UTM_TabReaderPlanDetail readonly	
)
AS
BEGIN

	Merge M_TabReaderPlanDetail as Target Using @TabReaderPlanDetail as Source on(Target.TabReaderPlanId =Source.TabReaderPlanId and Target.VesselScheduleId=Source.VesselScheduleId)	
	When Not Matched By Target Then
	Insert (TabReaderPlanId,VesselScheduleId,Requirement,CreatedBy,CreatedDate) 
	Values (Source.TabReaderPlanId,Source.VesselScheduleId,Source.Requirement,Source.CreatedBy,getdate());	
	select 1
END

GO
  IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TabReaderPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TabReaderPlanIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_TabReaderPlanIns]    
(
	@PlannedDate  				DateTime,
	@ShiftBandId				BigInt,	
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_TabReaderPlan
	(PlannedDate,ShiftbandId, CreatedBy, CreatedDate)
	VALUES(@PlannedDate,@ShiftBandId, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TabReaderPlanningDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TabReaderPlanningDel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_TabReaderPlanningDel]    
(
	@TabReaderPlanId				BigInt
)
AS
BEGIN

	DELETE FROM M_TabReaderPlan 
	WHERE		M_TabReaderPlan.TabReaderPlanId = @TabReaderPlanId

	DELETE FROM M_TabReaderPlanDetail
	WHERE		M_TabReaderPlanDetail.TabReaderPlanId = @TabReaderPlanId	


	SELECT @TabReaderPlanId
END

GO
  IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_TemplateGroupDel')
	DROP PROC prM_TemplateGroupDel
GO
----------------------------------------------------------------------------
-- delete Records from E_EqipmentMatrixGroupTemplates
----------------------------------------------------------------------------
 
Create PROCEDURE [dbo].[prM_TemplateGroupDel]    
(	
	@TemplateGroupId	BigInt,
	@UpdatedBy	nVarchar(50)			
)
AS
BEGIN
	 

	Update	E_EqipmentMatrixGroupTemplates  
	SET		IsActive	=	0, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	TemplateGroupId			=	@TemplateGroupId

	SELECT 1
	 
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_TemplateGroupIns')
	DROP PROC prM_TemplateGroupIns
GO
----------------------------------------------------------------------------
-- Insert Records into E_EqipmentMatrixGroupTemplates
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[prM_TemplateGroupIns]    
(		
	@OUId				Bigint, 
	@TemplateGroupName			nvarchar(50),
	@IsActive		INT,	 
	@CreatedBy			nVarchar(50)
)
AS
BEGIN
	DECLARE @ValidateDuplicate int = 0

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EqipmentMatrixGroupTemplates WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateGroupName))) = LTrim(RTrim(Upper(@TemplateGroupName)))

	If (@ValidateDuplicate = 0)
	BEGIN
		INSERT INTO E_EqipmentMatrixGroupTemplates
		(OUId,TemplateGroupName,IsActive,CreatedBy, CreatedDate)
		VALUES(@OUId,@TemplateGroupName,@IsActive,@CreatedBy, GETDATE())

		SELECT SCOPE_IDENTITY();
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
	 
END
GO

 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_TemplateGroupUpd')
	DROP PROC prM_TemplateGroupUpd
GO
----------------------------------------------------------------------------
-- Update Records into E_EqipmentMatrixGroupTemplates
----------------------------------------------------------------------------

CREATE PROCEDURE [dbo].[prM_TemplateGroupUpd]    
(
	@TemplateGroupId	  BigInt,
	@OUId				  Bigint, 
	@TemplateGroupName	  nvarchar(50),	 
	@IsActive	  INT,	
	@UpdatedBy			  nVarchar(50)
)
AS
DECLARE @ValidateDuplicate int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	E_EqipmentMatrixGroupTemplates WITH (NOLOCK)
	WHERE	LTrim(RTrim(Upper(TemplateGroupName))) = LTrim(RTrim(Upper(@TemplateGroupName)))
	AND		TemplateGroupId	!=	@TemplateGroupId

	If (@ValidateDuplicate = 0)
	BEGIN
		UPDATE	E_EqipmentMatrixGroupTemplates
		SET		TemplateGroupName	=	@TemplateGroupName,
				OUId			    =	@OUId,			 
				IsActive		    =	@IsActive, 			 
				UpdatedBy			=	@UpdatedBy,
				UpdatedDate			=	GETDATE()				
		WHERE	TemplateGroupId		=	@TemplateGroupId

		SELECT 1;
	END
	Else
	BEGIN
		SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END
END
GO

 IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prM_TemplateMatrixsSel')
	DROP PROC prM_TemplateMatrixsSel
GO
----------------------------------------------------------------------------
-- Get Records from E_EqipmentMatrixGroupTemplDet Based on Id
----------------------------------------------------------------------------
Create PROCEDURE [dbo].[prM_TemplateMatrixsSel]   
(
	@TemplateGroupId		bigint 
)
AS
BEGIN
	SELECT	E_EqipmentMatrixGroupTemplDet.TemplateGroupDetId,
			E_EqipmentMatrixGroupTemplDet.TemplateGroupId,
			E_EqipmentMatrixGroupTemplDet.MatrixId,  
			E_EqipmentMatrixGroupTemplDet.OUId, 
			E_EqipmentMatrixGroupTemplDet.CreatedBy, 
			E_EqipmentMatrixGroupTemplDet.CreatedDate,
			E_EquipmentMatrix.TemplateName as TemplateName
	FROM	E_EqipmentMatrixGroupTemplDet	  WITH (NOLOCK)
	left outer join E_EquipmentMatrix WITH (NOLOCK) on E_EquipmentMatrix.MatrixId= E_EqipmentMatrixGroupTemplDet.MatrixId 			 
	WHERE	(E_EqipmentMatrixGroupTemplDet.TemplateGroupId = @TemplateGroupId )
	 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TopManPlanDetailIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TopManPlanDetailIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_TopManPlanDetailIns]    
(
   @TopManPlanDetail UTM_TopManPlanDetail readonly	
)
AS
BEGIN

	Merge M_TopManPlanDetail as Target Using @TopManPlanDetail as Source on(Target.TopManPlanId =Source.TopManPlanId and Target.CraneScheduleId=Source.CraneScheduleId)	
	When Not Matched By Target Then
	Insert (TopManPlanId,CraneScheduleId,CreatedBy,CreatedDate) 
	Values (Source.TopManPlanId,Source.CraneScheduleId,Source.CreatedBy,getdate());	
	select 1
END

GO
  IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TopManPlanIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TopManPlanIns]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prM_TopManPlanIns]    
(
	@PlannedDate  				DateTime,
	@ShiftBandId				BigInt,	
	@CreatedBy					nVarchar(50)
)
AS
BEGIN

	INSERT INTO M_TopManPlan
	(PlannedDate,ShiftbandId, CreatedBy, CreatedDate)
	VALUES(@PlannedDate,@ShiftBandId, @CreatedBy, GETDATE())

	SELECT SCOPE_IDENTITY();
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_TopManPlanningDel]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_TopManPlanningDel]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prM_TopManPlanningDel]    
(
	@TopManPlanId				BigInt
)
AS
BEGIN

	DELETE FROM M_TopManPlan 
	WHERE		M_TopManPlan.TopManPlanId = @TopManPlanId

	DELETE FROM M_TopManPlanDetail
	WHERE		M_TopManPlanDetail.TopManPlanId = @TopManPlanId	


	SELECT @TopManPlanId
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,
	@UpdateType Int = 0,
	@CranePriorityId bigint
	
AS
BEGIN
	If (@UpdateType = 3 OR @UpdateType = 0)
	BEGIN
		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(),
			CranePriorityId=@CranePriorityId
		WHERE 	CraneScheduleId = @CraneScheduleId
	END
	Else if (@UpdateType = 1)
	BEGIN
		UPDATE	M_CraneSchedule
		SET		StartDate			=	@StartDate,
				CranePriorityId=@CranePriorityId
		WHERE	CraneScheduleId		=	@CraneScheduleId
	END
	Else If (@UpdateType = 2)
	BEGIN
		UPDATE	M_CraneSchedule
		SET		EndDate				=	@EndDate,
				CranePriorityId=@CranePriorityId
		WHERE	CraneScheduleId		=	@CraneScheduleId
	END
	SELECT 1
END

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,
	@ShiftBandId	BigInt = 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(),
		ShiftBandId	=	@ShiftBandId
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,
	@AllocationRuleId			BigInt = 0
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,
			AllocationRuleId			=	@AllocationRuleId
	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		EndDate				=	@EndDate
		WHERE	VesselScheduleId	=	@VesselScheduleId

	SELECT @VesselScheduleId
GO



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselMiscellaneousColumnsIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselMiscellaneousColumnsIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_VesselMiscellaneousColumnsIns]    
(
	 @VesselMiscData UTM_VesselMiscellaneousColumns readonly	
)
AS
BEGIN
	
	Merge M_VesselMiscellaneousColumns as Target Using @VesselMiscData as Source on(Target.VesselScheduleId = Source.VesselScheduleId)
	When Not Matched By Target Then
	Insert (VesselScheduleId,MiscValues,CreatedBy,CreatedDate,WorkloadTypeId) 

	Values (Source.VesselScheduleId,Source.MiscValues,Source.CreatedBy,getdate(),Source.WorkloadTypeId)
	When Matched Then
	Update Set Target.MiscValues		 = Source.MiscValues,
			   Target.WorkloadTypeId	 = Source.WorkloadTypeId,
			   Target.UpdatedBy			 = Source.UpdatedBy,
			   Target.UpdatedDate		 = getdate();

END
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
	DECLARE @vScheduleId BigInt = @VesselScheduleId, @orgID BigInt = @OUId
	-- 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 = @vScheduleId OR @vScheduleId = 0)
	AND		(M_VesselSchedule.OUId = @orgID OR @orgID = 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 = @vScheduleId
	--Group By J_WorkLoad.SkillId, D_Skill.Skill 

	SELECT	M_VesselScheduleResourceSet.VesselScheduleResourceSetId,
			M_VesselScheduleResourceSet.VesselScheduleId,
			M_VesselScheduleResourceSet.ResourceSetId,
			M_VesselScheduleResourceSet.TypeId,
			--iif(M_VesselScheduleResourceSet.SkillId = 0,M_VesselScheduleResourceSet.EquipmentTypeId,M_VesselScheduleResourceSet.SkillId)SkillId,
			M_VesselScheduleResourceSet.SkillId,
			M_VesselScheduleResourceSet.EquipmentTypeId,
			M_VesselScheduleResourceSet.Requirement,
			M_VesselScheduleResourceSet.LocationId,
			D_Skill.Skill SkillName
	FROM	M_VesselScheduleResourceSet WITH (NOLOCK)
			LEFT JOIN  D_Skill WITH (NOLOCK) ON M_VesselScheduleResourceSet.SkillId = D_Skill.SkillId 
			LEFT JOIN  M_EquipmentType WITH (NOLOCK) ON M_VesselScheduleResourceSet.EquipmentTypeId = M_EquipmentType.EquipmentTypeId 
	WHERE	M_VesselScheduleResourceSet.VesselScheduleId = @VesselScheduleId

	-- Retrieve Vessel Schedule Misc Column
	SELECT  M_VesselMiscellaneousColumns.VesselScheduleId ReferenceId,
			M_VesselMiscellaneousColumns.MiscValues MiscValue,
		    M_VesselMiscellaneousColumns.WorkloadTypeId 
	FROM	M_VesselMiscellaneousColumns	WITH (NOLOCK)
	WHERE	M_VesselMiscellaneousColumns.VesselScheduleId = @VesselScheduleId

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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prM_VesselScheduleResourceSetIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prM_VesselScheduleResourceSetIns]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prM_VesselScheduleResourceSetIns]    
(
	 @VesselScheduleResourceSet UTM_VesselScheduleResourceSet readonly	
)
AS
BEGIN
	
	Merge M_VesselScheduleResourceSet as Target Using @VesselScheduleResourceSet as Source on(Target.VesselScheduleId = Source.VesselScheduleId 
									and Target.VesselScheduleResourceSetId = Source.VesselScheduleResourceSetId)
	When Not Matched By Target Then
	Insert (VesselScheduleId,ResourceSetId,TypeId,SkillId,EquipmentTypeId,Requirement,LocationId,CreatedBy,CreatedDate) 

	Values (Source.VesselScheduleId,Source.ResourceSetId,Source.TypeId,Source.SkillId,Source.EquipmentTypeId,Source.Requirement,Source.LocationId,Source.CreatedBy,getdate())
	When Matched Then
	Update Set  Target.TypeId			= Source.TypeId,
				Target.SkillId			= Source.SkillId,
				Target.EquipmentTypeId  = Source.EquipmentTypeId,
				Target.Requirement		= Source.Requirement,
				Target.LocationId		= Source.LocationId,
			    Target.UpdatedBy		= Source.UpdatedBy,
			    Target.UpdatedDate		= getdate()
   When Not Matched By Source And Target.VesselScheduleId in (select VesselScheduleId from @VesselScheduleResourceSet)  Then
   delete;

END
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 = 3)
	BEGIN
		SELECT	C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmpName,
				C_OrganizationNode.OUName Department,
				S_EmployeeLeaves.CreatedDate TransDate,
				ExceptionCodeDesc LeaveCode,
				0 ReasonCode,
				FromDate FromDate,
				EndDate ToDate,
				Convert(decimal,1) NoOfDays,
				W_ApprovalStatus.ApprovalStatus ApprovalStatusName
		FROM	S_EmployeeLeaves	 WITH (NOLOCK) 
				INNER JOIN	C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.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
				INNER JOIN W_ApprovalStatus WITH (NOLOCK) ON W_ApprovalStatus.ApprovalStatusId = Convert(BigInt,@ApplicationStatus)
		WHERE	Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@StartDate) 
		AND		Convert(Date,S_EmployeeLeaves.FromDate) <= 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
	else 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		Decimal(18,2)	= NULL,
	@ApprovalRequired	Bit				= 0,
	@DayNightOvertime	Bit				= 0,
	@CreatedBy			nvarchar(100)	= NULL,
	@MaxOvrTimeSettings Decimal(18,2)   = 0,
	@ActiveStatus		Bit				= 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, ActiveStatus)
		VALUES (@OUId, @OvertimeName, @OvertimeDesc, COALESCE(@PeriodUnit, (1)), @PeriodLength, @ApprovalRequired, @DayNightOvertime, @CreatedBy, GETDATE(),@MaxOvrTimeSettings, @ActiveStatus)

		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,
	@AuditActionId	Int = 0,
	@AuditAction	nVarchar(100),
	@Remarks		nVarchar(1000)
AS
DECLARE @ShiftCostId BigInt = 0
BEGIN

	INSERT P_ShiftCosts(ShiftId, PayCodeId, StartTime, EndTime, ActualHour, ApprovedHours, ApprovalStatus, ShiftCost, AdjustmentCost, TotalCost, CreatedBy, CreatedDate, Remarks)
	VALUES (@ShiftId, @PayCodeId, @StartTime, @EndTime, @ActualHour, @ApprovedHours, @ApprovalStatus, @ShiftCost, @AdjustmentCost, @TotalCost, @CreatedBy, GETDATE(), @Remarks)

	SET @ShiftCostId = CAST(@@Identity AS INTEGER)

	-- Insert Into Shift Costs Audit Table
	EXEC prA_AddShiftCostsById @ShiftCostId, @AuditActionId, @AuditAction, @CreatedBy

	--INSERT INTO A_ShiftCosts
	--(ShiftCostId, ShiftId, PayCodeId, StartTime, EndTime, ActualHour, ApprovedHours, ApprovalStatus, ShiftCost, AdjustmentCost, TotalCost, CreatedBy, CreatedDate,
	-- [Action], ActionDate, ActionBy)
	--SELECT	ShiftCostId, ShiftId, PayCodeId, StartTime, EndTime, ActualHour, ApprovedHours, ApprovalStatus, ShiftCost, AdjustmentCost, TotalCost, CreatedBy, CreatedDate,
	--		@AuditAction, GETDATE(), @CreatedBy
	--FROM	P_ShiftCosts WITH (NOLOCK) 
	--WHERE	ShiftCostId = @ShiftCostId

	SELECT @ShiftCostId
END
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 = 0,
	@AuditActionId	Int = 0,
	@AuditAction	nVarchar(100),
	@DeletedBy		nVarchar(50)
)
AS
BEGIN
	-- Insert Into Shift Costs Audit Table
	EXEC prA_AddShiftCostsById @ShiftCostId, @AuditActionId, @AuditAction, @DeletedBy

	DELETE	P_ShiftCosts
	WHERE 	ShiftCostId = @ShiftCostId

	SELECT 1
END
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 WITH (NOLOCK)
inner join D_MasterCodes WITH (NOLOCK) 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 WITH (NOLOCK)
where shiftid =@ShiftId
and SkillId in (
select SkillId from C_EmployeeSkills WITH (NOLOCK)
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,
		P_OvertimeSettings.ActiveStatus,
		P_OvertimeSettings.MaxOvertimeHours
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,
	@ProcessDate	DateTime
AS
BEGIN
	If (@ProcessType = 1)
	BEGIN
		SELECT PublicHolidayId,HolidayDate,IsLeaveProcess,IsShiftProcess, HolidayName from D_PublicHolidays
		WHERE	IsLeaveProcess = 0 
		AND		Convert(Date,HolidayDate) < Convert(Date,@ProcessDate)
		ORDER BY HolidayDate
	END
	Else If (@ProcessType = 2)
	BEGIN
		SELECT	PublicHolidayId,HolidayDate,IsLeaveProcess,IsShiftProcess, HolidayName from D_PublicHolidays
		WHERE	IsShiftProcess = 0 
		AND		Convert(Date,HolidayDate) < Convert(Date,@ProcessDate)
		ORDER BY HolidayDate		
	END
END

GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prP_GetShiftCost')
	DROP PROCEDURE prP_GetShiftCost
GO

CREATE PROC prP_GetShiftCost
	@CreatedBy	nVarchar(2000)
AS
	
	SELECT		ShiftCostId,
				ShiftId,
				P_ShiftCosts.PayCodeId,
				StartTime,
				EndTime,
				ActualHour,
				ShiftCost,
				AdjustmentCost,
				TotalCost,
				ApprovalStatus
				ApprovedHours,
				Remarks ShiftCostRemarks,
				P_ShiftCosts.CreatedBy,
				D_PayCodes.PayCodeDesc PayCodeDescription
	FROM		P_ShiftCosts WITH (NOLOCK)
				INNER JOIN D_PayCodes  WITH (NOLOCK) ON P_ShiftCosts.PayCodeId = D_PayCodes.PayCodeId					
	WHERE		P_ShiftCosts.CreatedBy  =  @CreatedBy

	
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) INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId 
	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.EmployeeId = 1741
END

GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prP_ShiftCostIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prP_ShiftCostIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prP_ShiftCostIns]    
(
	@ShiftCost UTP_ShiftCosts readonly
)
AS
BEGIN
 
	--Insert P_ShiftCost Records
	Merge P_ShiftCosts as Target Using @ShiftCost as Source on(Target.ShiftId = Source.ShiftId and Target.PayCodeId=Source.PayCodeId )
	When Not Matched then
	Insert (ShiftId,PayCodeId,StartTime,EndTime,ActualHour,ShiftCost,AdjustmentCost,TotalCost,CreatedBy,CreatedDate,
	ApprovalStatus,ApprovedHours,Remarks) values(
	Source.ShiftId,Source.PayCodeId,Source.StartTime,Source.EndTime,Source.ActualHour,Source.ShiftCost,Source.AdjustmentCost,
	Source.TotalCost,Source.CreatedBy,getdate(),Source.ApprovalStatus,Source.ApprovedHours,Source.Remarks);

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,
		P_ShiftCosts.Remarks ShiftCostRemarks
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
		INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId AND C_Employee.PayGroupId = D_PaygroupCodes.PayGroupId
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,
	@IsReturnLeave	Bit = 0
)
AS
BEGIN

	If(@IsReturnLeave = 0)
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		BalanceDays		=	BalanceDays + @DaysToAdd,
				EarnedDays		=	EarnedDays + @DaysToAdd
		WHERE	EmployeeId		=	@EmployeeId
		AND		LeaveYear		=	@LeaveYear
		AND		ExceptionId		=	@ExceptionCodeId
	END
	Else If (@IsReturnLeave = 1)
	BEGIN
		UPDATE	L_EmployeeLeaveProfiles
		SET		BalanceDays		=	BalanceDays + @DaysToAdd,
				DaysUsed		=	DaysUsed - @DaysToAdd
		WHERE	EmployeeId		=	@EmployeeId
		AND		LeaveYear		=	@LeaveYear
		AND		ExceptionId		=	@ExceptionCodeId
	END

	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		Decimal(18,2)	= NULL,
	@ApprovalRequired	Bit				= 0,
	@DayNightOvertime	Bit				= 0,
	@UpdatedBy			nvarchar(100)	= NULL,
	@MaxOvrTimeHours    decimal(18, 2)  = NULL,
	@ActiveStatus		Bit				= 0
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,
					ActiveStatus		=	@ActiveStatus
		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,
	@AuditActionId	Int = 0,
	@AuditAction	nVarchar(100),
	@Remarks		nVarchar(1000)
AS
BEGIN
	UPDATE	P_ShiftCosts 
	SET		AdjustmentCost	=	@AdjustmentCost, 
			TotalCost		=	ShiftCost + @AdjustmentCost,
			ApprovedHours	=	@ApprovedHours,
			ApprovalStatus	=	@ApprovalStatus,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE(),
			Remarks			=	@Remarks
	WHERE	ShiftCostId		=	@ShiftCostId

	-- Insert Into Shift Costs Audit Table
	EXEC prA_AddShiftCostsById @ShiftCostId, @AuditActionId, @AuditAction, @UpdatedBy

	SELECT 1
END
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,
	@AuditActionId	Int = 0,
	@AuditAction	nVarchar(100),
	@Remarks		nVarchar(1000)
AS
BEGIN
	UPDATE	P_ShiftCosts
	SET		PayCodeId		=	@PayCodeId, 
			StartTime		=	@StartTime, 
			EndTime			=	@EndTime, 
			ActualHour		=	@ActualHour, 
			ApprovedHours	=	@ApprovedHours, 
			ApprovalStatus	=	@ApprovalStatus, 
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE(),
			Remarks			=	@Remarks
	WHERE	ShiftCostId		=	@ShiftCostId;

	-- Insert Into Shift Costs Audit Table
	EXEC prA_AddShiftCostsById @ShiftCostId, @AuditActionId, @AuditAction, @UpdatedBy

	SELECT 1;
END
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



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

CREATE PROCEDURE prRpt_GetUserLoginActivities
(
	@EmployeeNumber		nVarchar(50),
	@StartDate			DateTime,
	@EndDate			DateTime,
	@SecurityRoles		nVarchar(max),
	@ViewType			Int
)
AS
BEGIN
	If (@ViewType = 1)
	BEGIN
		SELECT	C_Employee.EmployeeNumber, 
				C_Employee.DisplayName EmployeeName, 
				C_OrganizationNode.OUName Department, 
				C_UserAudit.ActionDate ActivityDateTime,
				Convert(nVarchar(max),C_UserAudit.ActionDescription) ActionDescription
		FROM	C_UserAudit WITH (NOLOCK) 
				INNER JOIN C_User WITH (NOLOCK) ON C_User.UserID = C_UserAudit.UserId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
				INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
		WHERE	Convert(Date,C_UserAudit.ActionDate) >= Convert(Date,@StartDate)
		AND		Convert(Date,C_UserAudit.ActionDate) <= Convert(Date,@EndDate)
		AND		C_Employee.EmployeeNumber LIKE (@EmployeeNumber)
		AND		(C_UserSecurityRole.SecurityRoleId IN (SELECT * FROM fnStringToTable(@SecurityRoles)) OR @SecurityRoles = '')
		ORDER BY C_OrganizationNode.OUName, C_Employee.EmployeeNumber, C_UserAudit.ActionDate
	END
	Else If (@ViewType = 2)
	BEGIN
		SELECT	C_Employee.EmployeeNumber, 
				C_Employee.DisplayName EmployeeName, 
				C_OrganizationNode.OUName Department, 
				Min(C_UserAudit.ActionDate) ActivityDateTime
		FROM	C_UserAudit WITH (NOLOCK) 
				INNER JOIN C_User WITH (NOLOCK) ON C_User.UserID = C_UserAudit.UserId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
				INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
		WHERE	Convert(Date,C_UserAudit.ActionDate) >= Convert(Date,@StartDate)
		AND		Convert(Date,C_UserAudit.ActionDate) <= Convert(Date,@EndDate)
		AND		C_Employee.EmployeeNumber LIKE (@EmployeeNumber)
		AND		C_UserAudit.ActionType = 1
		AND		(C_UserSecurityRole.SecurityRoleId IN (SELECT * FROM fnStringToTable(@SecurityRoles)) OR @SecurityRoles = '')
		Group By C_Employee.EmployeeNumber, C_Employee.DisplayName, C_OrganizationNode.OUName
		ORDER BY C_OrganizationNode.OUName, C_Employee.EmployeeNumber, Min(C_UserAudit.ActionDate)
	END
	Else 
	BEGIN
		SELECT	C_Employee.EmployeeNumber, 
				C_Employee.DisplayName EmployeeName, 
				C_OrganizationNode.OUName Department, 
				Max(C_UserAudit.ActionDate) ActivityDateTime
		FROM	C_UserAudit WITH (NOLOCK) 
				INNER JOIN C_User WITH (NOLOCK) ON C_User.UserID = C_UserAudit.UserId
				INNER JOIN C_Employee WITH (NOLOCK) ON C_User.EmployeeID = C_Employee.EmployeeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_Employee.OUId = C_OrganizationNode.OUId
				INNER JOIN C_UserSecurityRole WITH (NOLOCK) ON C_User.UserID = C_UserSecurityRole.UserId
		WHERE	Convert(Date,C_UserAudit.ActionDate) >= Convert(Date,@StartDate)
		AND		Convert(Date,C_UserAudit.ActionDate) <= Convert(Date,@EndDate)
		AND		C_Employee.EmployeeNumber LIKE (@EmployeeNumber)
		AND		C_UserAudit.ActionType = 1
		AND		(C_UserSecurityRole.SecurityRoleId IN (SELECT * FROM fnStringToTable(@SecurityRoles)) OR @SecurityRoles = '')
		Group By C_Employee.EmployeeNumber, C_Employee.DisplayName, C_OrganizationNode.OUName
		ORDER BY C_OrganizationNode.OUName, C_Employee.EmployeeNumber, Max(C_UserAudit.ActionDate)
	END
END
GO
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),
	@AttendanceStatus	nVarchar(max)
)
	
AS
BEGIN
	If (Len(@ShiftBand) = 0) SET @ShiftBand = '0'

	If (LEN(@AttendanceStatus) = 0) SET @AttendanceStatus = '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'
				WHEN S_Shifts.InStatus  = 10 Then 'Training'
			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'
				WHEN S_Shifts.InStatus  = 10 Then 'Training'
			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		(S_Shifts.InStatus IN (SELECT * FROM fnStringToTable(@AttendanceStatus)) OR S_Shifts.OutStatus IN (SELECT * FROM fnStringToTable(@AttendanceStatus)) OR @AttendanceStatus = '0')
	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),
	@AttendanceStatus	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'

	if len(@AttendanceStatus) = 0 SET @AttendanceStatus = '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,
			C_Employee.EmployeeId,
		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'
				WHEN S_Shifts.InStatus  = 10 Then 'Training'
			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'
				WHEN S_Shifts.OutStatus  = 10 Then 'Training'
			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.InStatus IN (SELECT * FROM fnStringToTable(@AttendanceStatus)) OR S_Shifts.OutStatus IN (SELECT * FROM fnStringToTable(@AttendanceStatus)) OR @AttendanceStatus = '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,
		L_EmployeeLeaveProfiles.EarnedDays DAYS_EARNED,
		L_EmployeeLeaveProfiles.DaysUsed UsedDays ,
		L_EmployeeLeaveProfiles.BalanceDays DAYS_BALANCE,
		L_EmployeeLeaveProfiles.CarryForwardDays PendingLeaves,
		ExceptionCodeDesc LeaveName,
		L_EmployeeLeaveProfiles.LeaveYear,
		C_OrganizationNode.OUName OrganizationName,
		Convert(Decimal(18,2),(IsNull(NULLIF(IIF(L_EmployeeLeaveProfiles.DaysUsed < 0,0,L_EmployeeLeaveProfiles.DaysUsed),0),0) / (NULLIF(L_EmployeeLeaveProfiles.EarnedDays,0) + NULLIF(L_EmployeeLeaveProfiles.CarryForwardDays,0)) * 100)) Utilization
		--isnull((NULLIF(L_EmployeeLeaveProfiles.BalanceDays,0)/NULLIF(L_EmployeeLeaveProfiles.DaysUsed,0)),0)*100 Utilization
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
					AND L_LeaveProfiles.ActiveStatus = 1
		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
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)	
		--And C_Employee.EmployeeId = 1414
		order by EmployeeNumber



		select S_Shifts.EmployeeId,P_ShiftCosts.PayCodeId,Sum(ApprovedHours) ActualHour, D_PaygroupCodes.PaycodeType, IsNull(P_ShiftCosts.Remarks,'') ShiftCostRemarks
		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 S_Shifts.EmployeeId = 1414
		And ActualHour >= 0 
			group by EmployeeId,P_ShiftCosts.PayCodeId,D_PaygroupCodes.PaycodeType, IsNull(P_ShiftCosts.Remarks,'')
			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')
	AND		(Convert(Date,Employee.TerminationDate) > Convert(Date, @StartDate) OR Employee.TerminationDate IS NULL)
	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)
	UNION 
	SELECT  S_Shifts.EmployeeId , D_ExceptionCodes.ExcpetionCodeName LeaveCode, 
			S_ShiftExceptions.StartTime LeaveDate, D_ExceptionCodes.ColorCode LeaveColor
	FROM    S_ShiftExceptions WITH (NOLOCK)
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_ShiftExceptions.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
			INNER JOIN D_ExceptionType WITH (NOLOCK) ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
			LEFT OUTER JOIN S_RosterGroup WITH (NOLOCK)  ON S_RosterGroup.RosterGroupId = C_Employee.RosterGroupId
			LEFT OUTER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId
			LEFT OUTER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = C_EmployeeRoles.RoleId			
	WHERE	(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupItems)) OR @RosterGroupItems = '0')
	AND     (D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupItems)) OR @RoleGroupItems = '0')
	AND		Convert(Date,S_ShiftExceptions.StartTime) >= Convert(Date, @StartDate) 
	AND		Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date, @EndDate)
	

	
  -- 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_AddDeploymentTHPEmployeeDetails')
	DROP PROC prS_AddDeploymentTHPEmployeeDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeDetails
----------------------------------------------------------------------------
CREATE PROCEDURE prS_AddDeploymentTHPEmployeeDetails
	@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())

	SELECT CAST(@@Identity AS INTEGER) 

END

GO


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

CREATE PROC prS_AddEmployeeRosterLeave
(
	@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)
)
AS
BEGIN
	If (@ShiftId != 0 And @ChangeReconStatus = 1)
	BEGIN
		UPDATE	S_Shifts 
		SET		ReconTime = Null,
				Reconciled = 0,
				ReconStatusId = null, --null,
				ReconFailureReasonId = NULL,
				ReconFailureReasonDetail= NULL,
				RPGId = null,
				InStatus = null,
				OutStatus = null,
				InTime = null,
				OutTime = null,
				ActualStartTime = ShiftStartTime,
				ActualEndTime = ShiftEndTime,
				UpdatedBy	=	@CreatedBy
		WHERE	ShiftId = @ShiftId 
	END

	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())

	SELECT SCOPE_IDENTITY();
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, null

		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, @ValidateDuplicate int = 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	

    SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	S_ShiftExceptions WITH (NOLOCK)
	WHERE	ShiftId	= @ShiftId

	If (@ExceptionCodeId != 0 AND @ShiftId != 0 AND @ValidateDuplicate = 0)
	BEGIN
		INSERT INTO S_ShiftExceptions
		(ShiftId, ExceptionCodeId, StartTime, EndTime, ApprovalStatus, Remarks, CreatedBy, CreatedDate)
		VALUES(@ShiftId, @ExceptionCodeId, @StartTime, @EndTime, @ApprovalStatus, @Remarks, @CreatedBy, GETDATE())

		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	=	@CreatedBy
		WHERE	ShiftId		= @ShiftId 

		SELECT @ShiftId
		--SELECT  CAST(@@Identity AS INTEGER)  
	END
	Else If (@ShiftId = 0)
	BEGIN
		 SELECT 1 
    END
	Else If (@ValidateDuplicate != 0)
	BEGIN
	SET @ValidateDuplicate = -1;
		SELECT @ValidateDuplicate;
	END	
	Else
	BEGIN 
	    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_AddTHPEmployeeSkillDetails')
	DROP PROC prS_AddTHPEmployeeSkillDetails
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeSkillDetails
----------------------------------------------------------------------------
CREATE PROC [dbo].[prS_AddTHPEmployeeSkillDetails]
	@THPPeriodId		BigInt,
	@EmployeeId			BigInt,
	@ShiftId			BigInt,
	@SkillId			BigInt,
	@ShiftDate			DateTime,
	@ActivityCounter	Numeric(18,0),
	@THPProcessDate		DateTime,
	@THPNotes			Text = NULL,
	@CreatedBy			nVarchar(50) = NULL
AS
BEGIN

	DELETE FROM S_THPEmployeeSkillDetails 
	Where	EmployeeId				=	@EmployeeId
	And		Convert(Date,ShiftDate)	=	Convert(Date,@ShiftDate)

	INSERT INTO S_THPEmployeeSkillDetails
	(THPPeriodId, EmployeeId, ShiftId, SkillId, ShiftDate, ActivityCounter, THPProcessDate, THPNotes, CreatedBy, CreatedDate)
	VALUES(@THPPeriodId, @EmployeeId, @ShiftId, @SkillId, @ShiftDate, @ActivityCounter, @THPProcessDate, @THPNotes, @CreatedBy, GETDATE())
	
	SELECT CAST(@@Identity AS INTEGER) 

END

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,
	@ActiveStatus	Bit = 0
AS

INSERT S_THPSettings(OUId, THPSettingsName, StartDate, PeriodUnit, PeriodLength, CreatedBy, CreatedDate, ActiveStatus)
VALUES (@OUId, @THPSettingsName, @StartDate, COALESCE(@PeriodUnit, (1)), @PeriodLength, @CreatedBy, GETDATE(), @ActiveStatus)

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
	DECLARE @ShiftId BigInt = 0

	SELECT	@ShiftId = ISNull(ShiftId,0) 
	FROM	S_EmployeeLeaves WITH (NOLOCK)
	Where	EmployeeId	=	@EmployeeId
	AND		Convert(Date,FromDate) = Convert(Date,@LeaveDate)
	AND		ExceptionCodeId	=	@ExceptionCodeId

	If(@ShiftId != 0)
	BEGIN
		DECLARE @GranularityEarlyINMin int = 0,@GranularityLateOutMin int = 0

		SELECT 	@GranularityEarlyINMin = TA_RPGConfig.ReconGranularShiftInEarly,
				@GranularityLateOutMin = TA_RPGConfig.ReconGranularShiftOutLate
		FROM	TA_RPGConfig  WITH (NOLOCK)
				INNER JOIN TA_RPGRoles WITH (NOLOCK) ON TA_RPGConfig.RPGId = TA_RPGRoles.RPGId 
				INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.RoleId = TA_RPGRoles.RoleId 
				INNER JOIN TA_RPGOU WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId AND S_Shifts.OUId = TA_RPGOU.OUId
		WHERE	S_Shifts.ShiftId = @ShiftId

		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
				ActualStartTime =  IIF(DATEDIFF(minute,0,ShiftStartTime) % @GranularityEarlyINMin > 0, 
										DATEADD(minute,(@GranularityEarlyINMin- DATEDIFF(minute,0,ShiftStartTime) % @GranularityEarlyINMin),ShiftStartTime),ShiftStartTime),
				ActualEndTime = IIF(OTEndTime > ShiftEndTime,  IIF(DATEDIFF(minute,0,OTEndTime) % @GranularityLateOutMin > 0, 
									DATEADD(minute,(@GranularityLateOutMin- DATEDIFF(minute,0,OTEndTime) % @GranularityLateOutMin),OTEndTime),OTEndTime),
									IIF(DATEDIFF(minute,0,ShiftEndTime) % @GranularityLateOutMin > 0, 
									DATEADD(minute,(@GranularityLateOutMin- DATEDIFF(minute,0,ShiftEndTime) % @GranularityLateOutMin),ShiftEndTime),ShiftEndTime))
		WHERE ShiftId = @ShiftId 
	END

	DELETE FROM S_EmployeeLeaves WHERE EmployeeId = @EmployeeId 
	AND Convert(Date,FromDate) = Convert(Date,@LeaveDate) 
	AND ExceptionCodeId = @ExceptionCodeId

	SELECT 1
END 
GO

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

----------------------------------------------------------------------------
-- Delete Selected Exceptions And Employee Roster Leave By Employee And Shift Id
----------------------------------------------------------------------------
CREATE PROC prS_DeleteExceptionsFromRoster
	@EmployeeLeaveId	BigInt,
	@ShiftId			BigInt,
	@DeleteActionBy		nVarchar(50)
AS
	--DELETE	FROM	S_EmployeeLeaves  WHERE	LeaveId = @EmployeeLeaveId

	DELETE	FROM S_ShiftExceptions WHERE	ShiftId	= @ShiftId

	DELETE	FROM	S_EmployeeLeaves   WHERE	ShiftId	= @ShiftId

	SELECT 1
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 Form THP Employee Details
	DELETE FROM S_THPEmployeeDetails 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	AND		S_THPEmployeeDetails.EmployeeId	=	@EmployeeId

	-- Delete Form THP Employee Equipment Details
	DELETE	FROM S_THPEmployeeEquipmentDetails
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	AND		S_THPEmployeeEquipmentDetails.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_DeleteShiftsBetweenDatesByRosterGroup')
	DROP PROC prS_DeleteShiftsBetweenDatesByRosterGroup
GO

----------------------------------------------------------------------------
-- Delete Existing Shifts Between Defined Dates By Roster Group Id
----------------------------------------------------------------------------
CREATE PROC prS_DeleteShiftsBetweenDatesByRosterGroup
(
	@StartDate		DateTime,
	@EndDate		DateTime,
	@RosterGroupId	BigInt
)
AS
BEGIN
	-- Delete Available THP Details From Between Start And End Dates
	DELETE FROM S_THPEmployeeDetails 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	AND		S_THPEmployeeDetails.EmployeeId	IN 
			( 
				SELECT EmployeeId From C_Employee WITH (NOLOCK) 
				Where RosterGroupId = @RosterGroupId
			)

	-- DELETE Available THP Employee Equipments Details Between Start And End Dates
	DELETE FROM S_THPEmployeeEquipmentDetails 
	WHERE	Convert(Date,ShiftDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,ShiftDate) <= Convert(Date,@EndDate)
	AND		S_THPEmployeeEquipmentDetails.EmployeeId	IN 
			( 
				SELECT EmployeeId From C_Employee WITH (NOLOCK) 
				Where RosterGroupId = @RosterGroupId
			)
	
	-- Delete Available Shifts From Between Start And End Dates
	DELETE FROM S_Shifts
	WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime) <= Convert(Date,@EndDate)
	AND		S_Shifts.EmployeeId	IN 
			(
				SELECT EmployeeId From C_Employee WITH (NOLOCK) 
				WHERE	RosterGroupId = @RosterGroupId
			)

	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_DeleteTHPEmployeeSkillDetails')
	DROP PROC prS_DeleteTHPEmployeeSkillDetails
GO
----------------------------------------------------------------------------
-- Delete Records From S_THPEmployeeSkillDetails By Shift Id Between Selected Date And ShiftBand
----------------------------------------------------------------------------
CREATE PROCEDURE prS_DeleteTHPEmployeeSkillDetails
	@OUId			BigInt,
	@ShiftDate		DateTime,
	@ShiftBandId	BigInt,
	@SelectedSkills	nVarchar(100) = NULL
AS
BEGIN
	DELETE FROM S_THPEmployeeSkillDetails
	WHERE	ShiftId IN (SELECT	S_Shifts.ShiftId
						FROM	S_Shifts WITH (NOLOCK) 
								INNER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
						WHERE	S_Shifts.ShiftBandId			=	@ShiftBandId
						AND		Convert(Date,ActualStartTime)	=	Convert(Date,@ShiftDate)
						AND		S_Shifts.OUId					=	@OUId
						AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SelectedSkills)) OR @SelectedSkills IS NULL)
						)


	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)
AND		C_Employee.ActiveStatus = 1
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,
			C_Employee.MobilePhone,
			C_Employee.HomePhone
	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_EmployeeLeaveCreateOrUpdate]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_EmployeeLeaveCreateOrUpdate]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_EmployeeLeaveCreateOrUpdate]    
(
  @EmployeeLeave US_EmployeeLeaves readonly
)
AS
BEGIN
    Merge S_EmployeeLeaves as Target Using @EmployeeLeave as Source ON 
		( Target.EmployeeId = Source.EmployeeId AND Convert(Date,Target.FromDate) = Convert(Date,Source.FromDate))	
	When Not Matched then --AND (Source.ApprovalStatus = 'Pending' OR Source.ApprovalStatus IS NULL OR Source.ApprovalStatus = '' OR Source.ApprovalStatus like '%Approved%')Then
	Insert (EmployeeId,OUId, ExceptionCodeId, FromDate, EndDate, ApprovedBy, LeaveHours, ShiftId, Remarks, PickedTHP, Note, CreatedBy, CreatedDate,ApprovalStatus) 
	VALUES (Source.EmployeeId, Source.OUId,Source.ExceptionCodeId, Source.FromDate, Source.EndDate, Source.ApprovedBy, Source.LeaveHours,
			(SELECT ShiftId From S_Shifts WITH (NOLOCK) WHERE EmployeeId = Source.EmployeeId And Convert(Date,ActualStartTime) = Convert(Date,Source.FromDate)),
			Source.Remarks, Source.PickedTHP, Source.Note, Source.CreatedBy, GETDATE(),Source.ApprovalStatus);
	--When Matched AND Source.ApprovalStatus like '%Approved%' Then
	--Update Set	Target.Remarks			=	Source.Remarks,
	--			Target.ExceptionCodeId	=	Source.ExceptionCodeId,
	--			Target.ApprovalStatus   =   Source.ApprovalStatus,
	--			Target.ApprovedBy		=	Source.ApprovedBy,	   
	--			Target.UpdatedBy		=	Source.UpdatedBy,
	--			Target.UpdatedDate		=	GETDATE()
	--When Matched And (Source.ApprovalStatus = 'Rejected' OR Source.ApprovalStatus = 'Cancel' OR Source.ApprovalStatus = 'Withdrawn') then
	----When Not Matched by Source AND  Target.EmployeeId in (Select EmployeeId from @EmployeeLeave) AND 
	--  --  Convert(Date,Target.FromDate) in (Select Convert(Date,FromDate) from @EmployeeLeave)  AND Target.ApprovalStatus in (Select ApprovalStatus from @EmployeeLeave)Then 
	--Delete;
	SELECT 1
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,
			D_ExceptionType.ExceptionTypeName,
			D_ExceptionType.ExceptionTypeId
	FROM	S_EmployeeLeaves WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId=S_EmployeeLeaves.EmployeeId
			LEFT OUTER 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
			INNER JOIN D_ExceptionType WITH (NOLOCK) on D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
			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
		If (@ShiftId != 0 And @ChangeReconStatus = 1)
		BEGIN
			UPDATE	S_Shifts 
			SET		ReconTime = Null,
					Reconciled = 0,
					ReconStatusId = null, --null,
					ReconFailureReasonId = NULL,
					ReconFailureReasonDetail= NULL,
					RPGId = null,
					InStatus = null,
					OutStatus = null,
					InTime = null,
					OutTime = null,
					ActualStartTime = ShiftStartTime,
					ActualEndTime = ShiftEndTime,
					UpdatedBy	=	@CreatedBy
			WHERE	ShiftId = @ShiftId 
		END--EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, @CreatedBy, null

		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())

		
		SELECT SCOPE_IDENTITY();
		--INSERT INTO A_Shifts 
		--(ShiftId, EmployeeId, [Action], ActionDate, ShiftBandName, ShiftStartTime, ShiftEndTime, LeaveType, LeaveAppliedBy, 
		-- LeaveApprovedBy,  LeaveAppliedDate, LeaveApprovedDate, ActionBy, RBRRank)
		--SELECT	@ShiftId, @EmployeeID, 'LeaveApproved', GETDATE(), D_ShiftBand.ShiftBandCode, 
		--		S_SHifts.ActualStartTime, S_Shifts.ActualEndTime, D_ExceptionCodes.ExcpetionCodeName,
		--		S_EmployeeLeaves.CreatedBy, @CreatedBy, S_EmployeeLeaves.A
		--FROM	S_Shifts WITH (NOLOCK) 
		--		INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
		--		INNER JOIN S_EmployeeLeaves WITH (NOLOCK) ON S_EmployeeLeaves.ShiftId = S_Shifts.ShiftId 
		--		INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId


		 
		
	--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, null
					
		SELECT -1;
		 
	END
	else 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 OR @OUId = 0)
    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_EmployeeShiftByShiftId') AND type in (N'P', N'PC'))
DROP PROCEDURE prS_EmployeeShiftByShiftId
GO
 
CREATE PROCEDURE prS_EmployeeShiftByShiftId
(
	@ShiftId	BigInt
)
AS
BEGIN	 
	;WITH FirstActivity as 
	(
		SELECT	J_Activity.ActivityId, J_Activity.StartTime, S_Shifts.ShiftId, 
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName,
				--CASE CraneWorkLoad.CraneScheduleId WHEN CraneWorkLoad.CraneScheduleId != 0 THEN M_Cranes.CraneNumber ELSE Equipments.EquipmentName END EquipmentName,
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	S_Shifts.ShiftId = @ShiftId	--Convert(Date,ActualStartTime) = Convert(Date,'2021-02-09')
	)
	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,
			IsNull(S_Shifts.RBRRank,'') LiveRank,
			S_Shifts.Reconciled Reconciled,
			S_Shifts.ReconStatusId,
			RTrim(LTrim(IsNull(FirstActivity.EquipmentName,'') + ' ' + IsNull(Convert(nVarchar(5),FirstActivity.StartTime, 108),''))) ActivityInfo
	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
			LEFT OUTER JOIN FirstActivity WITH (NOLOCK) ON FirstActivity.ShiftId = S_Shifts.ShiftId And RowNumber = 1
	WHERE	S_Shifts.ShiftId = @ShiftId
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),
	@ShiftBands nVarchar(max) = '0'
)
AS
BEGIN	 
	;WITH FirstActivity as 
	(
		SELECT	J_Activity.ActivityId, J_Activity.StartTime, S_Shifts.ShiftId, 
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName,
				--CASE CraneWorkLoad.CraneScheduleId WHEN CraneWorkLoad.CraneScheduleId != 0 THEN M_Cranes.CraneNumber ELSE Equipments.EquipmentName END EquipmentName,
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ShiftEndTime) > Convert(Date,@StartDate)
		AND		Convert(Date,S_Shifts.ShiftStartTime) < Convert(Date,@EndDate)	--Convert(Date,ActualStartTime) = Convert(Date,'2021-02-09')
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
	)
	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.ShiftStartTime ActualStartTime, 
			S_Shifts.ShiftEndTime 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,
			IsNull(S_Shifts.RBRRank,'') LiveRank,
			S_Shifts.Reconciled Reconciled,
			S_Shifts.ReconStatusId,
			RTrim(LTrim(IsNull(FirstActivity.EquipmentName,''))) ActivityInfo,
			--CAST(FirstActivity.StartTime AS Time(0)) FirstActivityTime
			FirstActivity.StartTime FirstActivityTime,
			D_RoleGroup.RoleGroupId,
			D_RoleGroup.RoleGroupName
	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 D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
			--INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = S_Shifts.EmployeeId 
			--			AND D_Roles.RoleId = C_EmployeeRoles.RoleId And C_EmployeeRoles.IsPrimaryRole = 1
			INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
			LEFT OUTER JOIN FirstActivity WITH (NOLOCK) ON FirstActivity.ShiftId = S_Shifts.ShiftId And RowNumber = 1
	WHERE	C_Employee.ActiveStatus = 1
	AND		D_ShiftBand.ActiveStatus = 1
	AND		Convert(Date,S_Shifts.ShiftEndTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_Shifts.ShiftStartTime) <= Convert(Date,@EndDate)
	AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
	AND		(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '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_GetAvailableShiftsByDateSkill]') AND type in (N'P', N'PC'))
	DROP PROCEDURE [dbo].[prS_GetAvailableShiftsByDateSkill]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_GetAvailableShiftsByDateSkill]    
(
	@ShiftDate		DateTime,
	@ShiftBands		nVarchar(100),
	@RequiredSkills	nVarchar(500),
	@OUId			BigInt
)
AS
BEGIN
	SELECT	S_Shifts.ShiftId, 
			S_Shifts.OUId,
			S_Shifts.EmployeeId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftBandId,
			C_EmployeeSkills.IsPrimary,
			C_Employee.EmploymentBasisId,
			C_Employee.EmployeeNumber,
			IsNull(C_Employee.ContractedHours,0) ContractedHours,
			C_Employee.EmploymentBasisId, 
			D_EmploymentBasis.EmploymentBasisCode,
			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, 
			Convert(Date,S_Shifts.ActualStartTime) ShiftDate,
			D_Roles.RoleGroupId, 
			IsNull(S_Shifts.RBRRank,'D') RBRRank, 
			IsNull(C_EmployeeSkills.SkillRating,0) SkillRating
	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_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 D_EmploymentBasis WITH (NOLOCK) ON C_Employee.EmploymentBasisId = D_EmploymentBasis.EmploymentBasisId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.SkillId = D_RoleSkill.SkillId  AND C_Employee.EmployeeId = C_EmployeeSkills.EmployeeId-- To Retrieve SKill Rating
	WHERE	Convert(Date,ActualStartTime)	=	Convert(Date,@ShiftDate)
	AND		C_EmployeeSkills.SkillId		IN (SELECT * FROM fnStringToTable(@RequiredSkills))
	AND		S_Shifts.ShiftBandId			IN (SELECT * FROM fnStringToTable(@ShiftBands))
	AND		S_SHifts.ShiftId	NOT IN	(
											SELECT ShiftId FROM J_Activity WITH (NOLOCK) 
											WHERE	ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))
											AND		Convert(Date,StartTime) = Convert(Date,@ShiftDate)
											AND		J_Activity.OUId	= @OUId
											AND		ShiftId IS NOT NULL
										) -- Exclude Employees who are already allocated to work
	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
										)  -- Exclude employees who are on leave
	AND		S_Shifts.ShiftId NOT  IN (
											SELECT	ShiftId
											FROM	S_ShiftExceptions WITH (NOLOCK)
											WHERE	Convert(Date, StartTime) = Convert(Date, @ShiftDate)
									 ) -- Exclude If Available in Shift Exceptions


	-- Retrieve Shift And Activity Counters Between Selected Shift Date
	SELECT	IsNull(SUM(ShiftCounter),0) ShiftCounter, IsNull(SUM(ActivityCounter),0) ActivityCounter, EmployeeId 	 
	FROM	S_THPEmployeeDetails WITH (NOLOCK)
	WHERE	CONVERT(date,ShiftDate) >= (SELECT	TOP 1 PeriodStart FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate And OUId	=	@OUId)
	AND		CONVERT(date,ShiftDate) <= (SELECT	TOP 1 PeriodEnd FROM	S_THPEmployeePeriods WITH (NOLOCK)
										WHERE	PeriodStart <=  @ShiftDate and PeriodEnd >= @ShiftDate And OUId	=	@OUId)
	GROUP BY EmployeeId
END
GO

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

----------------------------------------------------------------------------
-- Retrieve List of Available Shifts From Given Date
----------------------------------------------------------------------------
CREATE PROC prS_GetAvailableShiftsFromSelectedDate
	@ShiftDate		DateTime,
	@EmployeeId		BigInt,
	@SelectionType	Int
AS
	If (@SelectionType = 1)
	BEGIN
		SELECT	ShiftId
		FROM	S_Shifts WITH (NOLOCK)
		WHERE	Convert(Date,ActualStartTime) >= Convert(Date,@ShiftDate)
		AND		EmployeeId		=	@EmployeeId
		ORDER BY Convert(Date,ActualStartTime)
	END
	ELSE
	BEGIN
		SELECT	ShiftId
		FROM	S_Shifts WITH (NOLOCK)
		WHERE	Convert(Date,ActualStartTime) = Convert(Date,@ShiftDate)
		AND		EmployeeId		=	@EmployeeId
		ORDER BY Convert(Date,ActualStartTime)
	END
GO

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

CREATE PROC prS_GetEmployeeDetailsByLeaveProfileId
	@OUID	          BigInt
	
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   Employee.CreatedBy,
		   OrgNode.OUName, 
		   LeaveProfileHeader.ProfileName RuleName,
		   LeaveProfileHeader.LeaveProfileHeaderId RuleId,
		   LeaveProfileHeader.Remarks RuleDesc,
		   LeaveProfileHeader.UpdatedBy,		
		   CONVERT(bit,0) [MarkasDelete],
		   IsNull(EmployeeLeaveProfile.EmployeeLeaveProfileId,0) EmployeeLeaveProfileId,
		   Convert(Date,EmployeeLeaveProfile.StartDate,120) StartDate,
		   Convert(Date,EmployeeLeaveProfile.EndDate,120) EndDate  
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
		   LEFT OUTER JOIN C_EmployeeLeaveProfile EmployeeLeaveProfile WITH (NOLOCK) ON Employee.EmployeeId = EmployeeLeaveProfile.EmployeeId
	       LEFT OUTER JOIN L_LeaveProfileHeader LeaveProfileHeader WITH (NOLOCK) ON EmployeeLeaveProfile.LeaveProfileHeaderId = LeaveProfileHeader.LeaveProfileHeaderId		  
	WHERE  Employee.OUId = @OUID
END
GO

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

CREATE PROC prS_GetEmployeeDetailsByOverTimeId
	@OUID	BigInt
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   OrgNode.OUName, 
		   OvertimeSettings.OTName RuleName,
		   OvertimeSettings.OvertimeId RuleId,
		   OvertimeSettings.OTDesc RuleDesc,
		   OvertimeSettings.UpdatedBy,
		   CONVERT(bit,0) [MarkasDelete]	
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
	       LEFT OUTER JOIN P_OvertimeSettings OvertimeSettings WITH (NOLOCK) ON Employee.OvertimeId = OvertimeSettings.OvertimeId		  
	WHERE  Employee.OUId = @OUID
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetEmployeeDetailsByPanelClinicId')
	DROP PROC prS_GetEmployeeDetailsByPanelClinicId
GO

CREATE PROC prS_GetEmployeeDetailsByPanelClinicId
	@OUID	BigInt
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   OrgNode.OUName, 
		   PanelClinic.PanelClinicName RuleName,
		   PanelClinic.PanelClinicId RuleId,
		   EmployeePanelClinic.EmployeePanelClinicId,
		   CONVERT(bit,0) [MarkasDelete]	
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
		   LEFT OUTER JOIN C_EmployeePanelClinics EmployeePanelClinic WITH (NOLOCK) ON EmployeePanelClinic.EmployeeId = Employee.EmployeeId
	       LEFT OUTER JOIN D_PanelClinics PanelClinic WITH (NOLOCK) ON PanelClinic.PanelClinicId = EmployeePanelClinic.PanelClinicId		  
	WHERE  Employee.OUId = @OUID
END
GO


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

CREATE PROC prS_GetEmployeeDetailsByPayGroupId
	@OUID	BigInt
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   OrgNode.OUName, 
		   PayGroup.PayGroupCode RuleName,
		   PayGroup.PayGroupId RuleId,
		   PayGroup.PayGroupDesc RuleDesc,
		   PayGroup.UpdatedBy,
		   CONVERT(bit,0) [MarkasDelete]	
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
	       LEFT OUTER JOIN D_PayGroup PayGroup WITH (NOLOCK) ON Employee.PayGroupId = PayGroup.PayGroupId		  
	WHERE  Employee.OUId = @OUID
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetEmployeeDetailsByScheduleId')
	DROP PROC prS_GetEmployeeDetailsByScheduleId
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC prS_GetEmployeeDetailsByScheduleId
	@OUID                           BigInt
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   OrgNode.OUName, 
		   ScheduleRules.Name RuleName,
		   ScheduleRules.ScheduleRuleId RuleId,
		   ScheduleRules.Description RuleDesc,
		   ScheduleRules.UpdatedBy,
		   CONVERT(bit,0) [MarkasDelete]	
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
	       LEFT OUTER JOIN S_ScheduleRules ScheduleRules WITH (NOLOCK) ON Employee.ScheduleRuleId = ScheduleRules.ScheduleRuleId		  
	WHERE  Employee.OUId = @OUID
END
GO

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

CREATE PROC prS_GetEmployeeDetailsByUserRoleId
	@OUID	          BigInt
AS
BEGIN
		SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   Employee.CreatedBy,
		   OrgNode.OUName, 
		   SecurityRole.SecurityRoleCode RuleName,
		   SecurityRole.SecurityRoleID RuleId,
		   SecurityRole.Description RuleDesc,
		   SecurityRole.UpdatedBy,	
		   Users.IsActive ActiveStatus,	
		   Users.UserId,
		   CONVERT(bit,0) [MarkasDelete],
		   IsNull(UserSecurityRole.UserSecurityRoleId,0) UserSecurityRoleId,
		   Convert(Date,UserSecurityRole.StartDate,120) StartDate,
		   Convert(Date,UserSecurityRole.EndDate,120) EndDate  
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
		   LEFT OUTER JOIN C_User Users WITH (NOLOCK) ON Employee.EmployeeId=Users.EmployeeId
		   LEFT OUTER JOIN C_UserSecurityRole UserSecurityRole WITH (NOLOCK) ON Users.UserID = UserSecurityRole.UserId
	       LEFT OUTER JOIN C_SecurityRole SecurityRole WITH (NOLOCK) ON UserSecurityRole.SecurityRoleId = SecurityRole.SecurityRoleID		  
	WHERE  Employee.OUId = @OUID
END
GO


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

CREATE PROC prS_GetEmployeeDetailsByWorkFlowRouteId
	@OUID	          BigInt,
	@WorkflowModuleId Int
AS
BEGIN
	SELECT Employee.EmployeeId,
		   Employee.EmployeeNumber, 
	       Employee.DisplayName EmployeeName,
		   Employee.OUId, 
		   Employee.CreatedBy,
		   OrgNode.OUName, 
		   WorkflowRoute.RouteName RuleName,
		   WorkflowRoute.RouteId RuleId,
		   WorkflowRoute.RouteDesc RuleDesc,
		   WorkflowRoute.UpdatedBy,		
		   CONVERT(bit,0) [MarkasDelete],
		   IsNull(EmployeeWorkflow.EmployeeWorkflowId,0) EmployeeWorkflowId,
		   EmployeeWorkflow.ModuleId,
		   Convert(Date,EmployeeWorkflow.StartDate,120) StartDate,
		   Convert(Date,EmployeeWorkflow.EndDate,120) EndDate  
    FROM   C_Employee Employee WITH (NOLOCK) 
	       INNER JOIN C_OrganizationNode OrgNode WITH (NOLOCK) ON Employee.OUId = OrgNode.OUId
		   LEFT OUTER JOIN C_EmployeeWorkflow EmployeeWorkflow WITH (NOLOCK) ON Employee.EmployeeId = EmployeeWorkflow.EmployeeId
	       LEFT OUTER JOIN W_WorkflowRoute WorkflowRoute WITH (NOLOCK) ON EmployeeWorkflow.RouteId = WorkflowRoute.RouteId		  
	WHERE  Employee.OUId = @OUID
	AND	   (EmployeeWorkflow.ModuleId = @WorkflowModuleId OR EmployeeWorkflow.ModuleId IS NULL)
END
GO

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

CREATE PROCEDURE prS_GetEmployeeInitialLiveRank
(
	@EmployeeId		BigInt,
	@OUId			BigInt
)
AS
BEGIN	
	SELECT	LiveRankId,
			TT_EmployeeInitialLiveRank.EmployeeId,
			RBRRank
	FROM	TT_EmployeeInitialLiveRank WITH (NOLOCK) 
			INNER JOIN C_Employee WITH (NOLOCK) ON TT_EmployeeInitialLiveRank.EmployeeId = C_Employee.EmployeeId
	WHERE	(TT_EmployeeInitialLiveRank.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	AND		C_Employee.OUId = @OUId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_GetEmployeeLastShiftLiveRankByDate')
	DROP PROC prS_GetEmployeeLastShiftLiveRankByDate
GO

CREATE PROCEDURE prS_GetEmployeeLastShiftLiveRankByDate
(
	@OUId			BigInt,
	@EmployeeId		BigInt,
	@ShiftDate		DateTime
)
AS
BEGIN	
	WITH LastRbrRankByEmployee as (
		SELECT	EmployeeId,  RBRRank, 
				ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY ActualStartTime DESC) as RowNumber
		FROM	S_Shifts WITH (NOLOCK) 
		WHERE	RBRRank IS NOT NULL 
		AND		OUId	=	@OUId
		AND		Convert(Date,ActualStartTime) < Convert(Date,@ShiftDate)
		AND		(S_Shifts.EmployeeId = @EmployeeId OR @EmployeeId = 0)
	)
	SELECT	EmployeeId, RBRRank
	FROM	LastRbrRankByEmployee
	WHERE	RowNumber = 1
END
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 sysobjects WHERE name = 'prS_GetEmployeeLiveRankBetweenDates')
	DROP PROC prS_GetEmployeeLiveRankBetweenDates
GO

CREATE PROCEDURE prS_GetEmployeeLiveRankBetweenDates
(
	@EmployeeIds		nVarchar(max) = NULL,
	@StartDate		DateTime,
	@EndDate		DateTime,
	@OUId			BigInt
)
AS
BEGIN	
	
	--DECLARE	@LiveRankRoleParamsValue nVarchar(Max) = ''

	--SELECT	@LiveRankRoleParamsValue = IsNull(ParamValue,'')
	--FROM	D_SystemParams WITH (NOLOCK) WHERE ParamName = 'LiveRankingRoles'
 With ShiftDetails as(
	SELECT	Convert(Date,S_Shifts.ShiftStartTime) ShiftDate, S_Shifts.ShiftId,
			C_Employee.EmployeeId, C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
			D_ShiftBand.ShiftBandName ShiftBand,
			S_Shifts.ActualStartTime StartTime, S_Shifts.ActualEndTime EndTime, S_Shifts.RBRRank LiveRank, D_Roles.RoleName,
			Isnull(J_Activity.RBRRank,'') DeployedRank,
			ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId   
	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 D_ShiftBand WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
			LEFT JOIN J_Activity  WITH (NOLOCK) ON S_Shifts.ShiftId = J_Activity.ShiftId
	WHERE	(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeIds)) OR @EmployeeIds  = '0')
	--AND		(D_Roles.RoleName IN (SELECT * FROM fnStringToTable(@LiveRankRoleParamsValue)) OR @LiveRankRoleParamsValue = '')
	AND		Convert(Date,S_Shifts.ShiftStartTime) >= Convert(Date,@StartDate)
	--AND		Convert(Date,S_Shifts.ShiftEndTime) <= Convert(Date, @EndDate)
	AND  Convert(Date,S_Shifts.ShiftStartTime) <= Convert(Date,@EndDate)  
	AND		S_Shifts.OUId = @OUId)

	Select * from ShiftDetails where RowId=1

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

----------------------------------------------------------------------------
-- Retrieve List of Employee With Probation Expiry Dates
----------------------------------------------------------------------------
CREATE PROC prS_GetEmployeeProbationExpiryDetails
AS
BEGIN
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			C_OrganizationNode.OUName Department,
			C_Employee.Position Designation,
			C_Employee.ProbationExpiryDate,
			DateDiff(DAY, GETDATE(), C_Employee.ProbationExpiryDate) + 1 ExipiresInDays 
	FROM	C_Employee WITH (NOLOCK) INNER JOIN C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = C_Employee.OUId
	Where ProbationExpiryDate IS NOT NULL AND ProbationExpiryDate > GETDATE()
	--ORDER BY EmployeeNumber
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetEmployeeRosterDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetEmployeeRosterDetail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].prS_GetEmployeeRosterDetail
(
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeIds		nVarchar(max),
	@RosterGroupIds		nVarchar(max),
	@RoleGroupIds		nVarchar(max),
	@ShiftBandId		nVarchar(max),
	@OUID				BigInt	
)
AS
	BEGIN	
	
	SELECT S_Shifts.EmployeeId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName EmployeeName,
		   S_RosterGroup.GroupName RosterGroupName,
		   MIN(Convert(Date,S_Shifts.ShiftStartTime))EffectiveFrom,
		   MAX(Convert(Date,S_Shifts.ShiftStartTime))EffectiveTo
	FROM   S_Shifts WITH(NOLOCK)
		   INNER JOIN S_RosterGroup WITH(NOLOCK) ON S_Shifts.RosterGroupId = S_RosterGroup.RosterGroupId
		   INNER JOIN C_Employee WITH(NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
		   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 
		   INNER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
	WHERE  Convert(Date,ShiftStartTime) >= CONVERT(Date,@StartDate)
	AND	   Convert(Date,ShiftEndTime) <= CONVERT(Date,@EndDate)
	AND	   S_Shifts.OUId = @OUID
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroupIds)) OR @RosterGroupIds = '0')
	AND		(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeIds)) OR @EmployeeIds  = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroupIds)) OR @RoleGroupIds = '0')
	AND		( S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')
	GROUP BY S_Shifts.EmployeeId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName,
		   S_RosterGroup.RosterGroupId,
		   S_RosterGroup.GroupName
	END
go



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

----------------------------------------------------------------------------
-- Retrieve Summary Of Shifts Between Date Range
----------------------------------------------------------------------------
CREATE PROCEDURE prS_GetEmployeeRosterSummaryByDateRange
(
	@StartDate		DateTime,
	@EndDate		DateTime,
	@ShiftBands		nVarchar(max),
	@OUId			BigInt,
	@ExcludedSkill	BigInt,
	@RosterGroups	nVarchar(max),
	@RoleGroups		nVarchar(max),
	@Employees		nVarchar(max)
)
AS
BEGIN
	-- Retrieve Shift Count Summary Group By Primary SkillId
	SELECT	Count(*) ResourceCount, D_Roles.PrimarySkillId ResourceId, Convert(Date,S_Shifts.ActualStartTime) ShiftDate
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN D_Roles WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
	WHERE	Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date, @StartDate)
	AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date, @EndDate)
	AND		S_Shifts.OUId = @OUId
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
	AND		D_Roles.PrimarySkillId != @ExcludedSkill
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroups)) OR @RosterGroups = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroups)) OR @RoleGroups = '0')
	AND		(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@Employees)) OR @Employees = '0')
	GROUP BY D_Roles.PrimarySkillId, Convert(Date,S_Shifts.ActualStartTime)
	ORDER BY  Convert(Date,S_Shifts.ActualStartTime), D_ROles.PrimarySkillId

	-- Retreive Leave Count Summary Group By Exception Codes
	SELECT	Count(*) ResourceCount, D_ExceptionCodes.ExceptionCodeId ResourceId, Convert(Date,FromDate) ShiftDate
	FROM	S_EmployeeLeaves WITH (NOLOCK) 
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON S_EmployeeLeaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_EmployeeLeaves.EmployeeId 
	WHERE	Convert(Date,FromDate) >= Convert(Date, @StartDate)
	AND		Convert(Date,FromDate) <= Convert(Date, @EndDate)
	AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroups)) OR @RosterGroups = '0')
	AND		S_EmployeeLeaves.OUId = @OUId
	AND		S_EmployeeLeaves.ShiftId IN 
			( 
				SELECT	ShiftId 
				From	S_Shifts WITH (NOLOCK) 
						INNER JOIN D_Roles WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId
						INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
				WHERE	Convert(Date,S_Shifts.ActualStartTime) >= Convert(Date, @StartDate)
				AND		Convert(Date,S_Shifts.ActualStartTime) <= Convert(Date, @EndDate)
				AND		S_Shifts.OUId = @OUId
				AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
				AND		(C_Employee.RosterGroupId IN (SELECT * FROM fnStringToTable(@RosterGroups)) OR @RosterGroups = '0')
				AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroups)) OR @RoleGroups = '0')
				AND		(C_Employee.EmployeeId IN (SELECT * FROM fnStringToTable(@Employees)) OR @Employees = '0')
			)
	GROUP	BY D_ExceptionCodes.ExceptionCodeId, Convert(Date,FromDate)

	-- Retrieve Required Resources Count Summary Between Dates And OrgUnit
	SELECT	Count(Distinct AllocationNo) ResourceCount, D_Skill.SkillId ResourceId, Convert(Date,J_Activity.StartTime) ShiftDate
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN D_SKill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
	WHERE	Convert(Date,J_Activity.StartTime) >= Convert(Date, @StartDate)
	AND		Convert(Date,J_Activity.StartTime) <= Convert(Date, @EndDate)
	AND		J_Activity.OUId = @OUId
	AND		J_Activity.SkillId != @ExcludedSkill
	AND		(J_Activity.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
	GROUP BY D_Skill.SkillId, Convert(Date,J_Activity.StartTime)

	-- Retrieve Un-Assigned Work Count By Skill Id Between Dates And OrgUnit
	SELECT	Count(Distinct AllocationNo) ResourceCount, D_Skill.SkillId ResourceId, Convert(Date,J_Activity.StartTime) ShiftDate
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN D_SKill WITH (NOLOCK) ON J_Activity.SkillId = D_Skill.SkillId
	WHERE	Convert(Date,J_Activity.StartTime) >= Convert(Date, @StartDate)
	AND		Convert(Date,J_Activity.StartTime) <= Convert(Date, @EndDate)
	AND		J_Activity.OUId = @OUId
	AND		J_Activity.SkillId != @ExcludedSkill
	AND		(J_Activity.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
	AND		J_Activity.ShiftId IS NULL
	GROUP BY D_Skill.SkillId, Convert(Date,J_Activity.StartTime)

END
GO

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

CREATE PROC prS_GetEmployeeShiftsBetweenDates
(
	@EmployeeId		BigInt,
	@StartDate		DateTime,
	@EndDate		DateTime
)
AS
BEGIN
	SELECT	S_Shifts.ShiftId,
			S_Shifts.OUId,
			S_Shifts.EmployeeId,
			S_Shifts.ActualStartTime,
			S_Shifts.ActualEndTime
	FROM	S_Shifts WITH (NOLOCK)
	WHERE	S_Shifts.EmployeeId				=	@EmployeeId
	AND		Convert(Date,ActualStartTime)	>=	Convert(Date,@StartDate)
	AND		Convert(Date,ActualStartTime)	<=	Convert(Date,@EndDate)
END
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, ReconStatusId, OnCallShift IsOnCallShift
	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,
			DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftStartTime,
			DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) 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.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 WITH (NOLOCK))
	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_GetPendingApprovalLeaveTimeOffRequestDays')
	DROP PROC prS_GetPendingApprovalLeaveTimeOffRequestDays
GO

----------------------------------------------------------------------------
-- Retrieve List of Leaves, Request Days In Lie And Time Off Pending For Approval By Approver
----------------------------------------------------------------------------
CREATE PROC prS_GetPendingApprovalLeaveTimeOffRequestDays
(
	@ApproverId		BigInt = 0
)
AS
BEGIN
	-- Retreive Leaves Pending For Approval By Approver
	SELECT	Approver.EmployeeId ApproverEmployeeId,
			Approver.EmployeeNumber ApproverEmployeeNo, 
			Approver.DisplayName ApproverName, 
			Approver.EmailAddress ApproverEmailAddress,
			Applicant.EmployeeId ApplicantEmployeeId,
			Applicant.EmployeeNumber ApplicantEmployeeNo, 
			Applicant.DisplayName ApplicantName,
			ApplicantOU.OUName ApplicantDepartment,
			IsNull(D_ExceptionCodes.ExceptionCodeDesc, W_Modules.ModuleName) ApplicationType,
			L_Leaves.AppliedDate ApplicationDate,
			L_Leaves.LeaveStart, 
			L_Leaves.LeaveEnd, 
			L_Leaves.NoOfDays, 
			DATEDIFF(DAY,W_TRN_Approval_RouteDetails.AppliedDate,GETDATE()) DaysPendingForApproval,
			W_Modules.ModuleId 
	FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
			INNER JOIN C_Employee Applicant WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = Applicant.EmployeeId
			INNER JOIN C_Employee Approver WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApproverId = Approver.EmployeeId
			INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
			INNER JOIN C_OrganizationNode ApplicantOU WITH (NOLOCK) ON ApplicantOU.OUId = Applicant.OUId
			INNER JOIN L_Leaves WITH (NOLOCK) ON L_Leaves.LeaveId = W_TRN_ApprovalRoute.RequestTransId And L_Leaves.ApprovalStatusId IN (3,6)
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_Leaves.ExceptionCodeId
			INNER JOIN W_Modules WITH (NOLOCK) ON W_TRN_ApprovalRoute.ApprovalModuleID = W_Modules.ModuleId
	WHERE	W_TRN_Approval_RouteDetails.UserAction IS NULL
	AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	AND		(Approver.EmployeeId =	@ApproverId OR @ApproverId = 0)
	AND		(Convert(Date,Approver.TerminationDate) >= Convert(Date,GETDATE()) OR Approver.TerminationDate IS NULL) 
	UNION ALL
	-- Retreive Request Days In Lieu Pending For Approval By Approver
	SELECT	Approver.EmployeeId ApproverEmployeeId,
			Approver.EmployeeNumber ApproverEmployeeNo, 
			Approver.DisplayName ApproverName, 
			Approver.EmailAddress ApproverEmailAddress,
			Applicant.EmployeeId ApplicantEmployeeId,
			Applicant.EmployeeNumber ApplicantEmployeeNo, 
			Applicant.DisplayName ApplicantName,
			ApplicantOU.OUName ApplicantDepartment,
			W_Modules.ModuleName ApplicationType,
			L_RequestDaysInLieu.AppliedDate ApplicationDate,
			L_RequestDaysInLieu.RequestedDate LeaveStart,  
			L_RequestDaysInLieu.RequestedDate LeaveEnd,  
			Convert(decimal,1) NoOfDays,
			DATEDIFF(DAY,W_TRN_Approval_RouteDetails.AppliedDate,GETDATE()) DaysPendingForApproval,
			W_Modules.ModuleId 
	FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
			INNER JOIN C_Employee Applicant WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = Applicant.EmployeeId
			INNER JOIN C_Employee Approver WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApproverId = Approver.EmployeeId
			INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
			INNER JOIN C_OrganizationNode ApplicantOU WITH (NOLOCK) ON ApplicantOU.OUId = Applicant.OUId
			INNER JOIN L_RequestDaysInLieu WITH (NOLOCK) ON L_RequestDaysInLieu.DaysInLieuId = W_TRN_ApprovalRoute.RequestTransId And L_RequestDaysInLieu.ApprovalStatusId IN (3,6)
			INNER JOIN W_Modules WITH (NOLOCK) ON W_TRN_ApprovalRoute.ApprovalModuleID = W_Modules.ModuleId
	WHERE	W_TRN_Approval_RouteDetails.UserAction IS NULL
	AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	AND		(Approver.EmployeeId =	@ApproverId OR @ApproverId = 0)
	AND		(Convert(Date,Approver.TerminationDate) >= Convert(Date,GETDATE()) OR Approver.TerminationDate IS NULL) 
	UNION ALL
	-- Retreive Time Off Pending For Approval By Approver
	SELECT	Approver.EmployeeId ApproverEmployeeId,
			Approver.EmployeeNumber ApproverEmployeeNo, 
			Approver.DisplayName ApproverName, 
			Approver.EmailAddress ApproverEmailAddress,
			Applicant.EmployeeId ApplicantEmployeeId,
			Applicant.EmployeeNumber ApplicantEmployeeNo, 
			Applicant.DisplayName ApplicantName,
			ApplicantOU.OUName ApplicantDepartment,
			W_Modules.ModuleName ApplicationType,
			L_TimeOff.AppliedDate ApplicationDate,
			L_TimeOff.StartTime LeaveStart,  
			DATEADD(HOUR, L_TimeOff.Duration, L_TimeOff.StartTime) LeaveEnd,  
			Convert(decimal,L_TimeOff.Duration) NoOfDays,
			DATEDIFF(DAY,W_TRN_Approval_RouteDetails.AppliedDate,GETDATE()) DaysPendingForApproval,
			W_Modules.ModuleId 
	FROM	W_TRN_Approval_RouteDetails WITH (NOLOCK)
			INNER JOIN C_Employee Applicant WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApplicantId = Applicant.EmployeeId
			INNER JOIN C_Employee Approver WITH (NOLOCK) ON W_TRN_Approval_RouteDetails.ApproverId = Approver.EmployeeId
			INNER JOIN W_TRN_ApprovalRoute WITH (NOLOCK) ON W_TRN_ApprovalRoute.TransRouteID = W_TRN_Approval_RouteDetails.TransRouteID
			INNER JOIN C_OrganizationNode ApplicantOU WITH (NOLOCK) ON ApplicantOU.OUId = Applicant.OUId
			INNER JOIN L_TimeOff WITH (NOLOCK) ON L_TimeOff.TimeOffId = W_TRN_ApprovalRoute.RequestTransId And L_TimeOff.ApprovalStatusId IN (3,6)
			INNER JOIN W_Modules WITH (NOLOCK) ON W_TRN_ApprovalRoute.ApprovalModuleID = W_Modules.ModuleId
	WHERE	W_TRN_Approval_RouteDetails.UserAction IS NULL
	AND		W_TRN_Approval_RouteDetails.ActionDate IS NULL
	AND		(Approver.EmployeeId =	@ApproverId OR @ApproverId = 0)
	AND		(Convert(Date,Approver.TerminationDate) >= Convert(Date,GETDATE()) OR Approver.TerminationDate IS NULL) 
	-- Retrieve Time Off Request Pending For Approval By Approver
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,
	@TemplateId		BigInt = 0
AS
BEGIN
	-- Template Roster Details By Roster Group
	SELECT	S_TemplateRoster.TemplateId, 
			S_TemplateRoster.TemplateName, 
			S_TemplateRoster.TemplateDesc, 
			S_TemplateRoster.NoOfDays
	FROM	S_TemplateRoster WITH (NOLOCK)
			INNER JOIN S_TemplateRosterLine WITH (NOLOCK) ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId  And S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId	=	@RosterGroupId 
	AND		(S_TemplateRosterLine.TemplateId		=	@TemplateId OR @TemplateId = 0)
	--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 WITH (NOLOCK)
			INNER JOIN S_TemplateRoster WITH (NOLOCK) ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId And S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId = @RosterGroupId 
	AND		(S_TemplateRosterLine.TemplateId		=	@TemplateId OR @TemplateId = 0)
	--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 WITH (NOLOCK)
			INNER JOIN S_TemplateRosterLine WITH (NOLOCK) ON S_TemplateRosterLine.TemplateLineId = S_TemplateRoster_Shifts.TemplateLineId
			INNER JOIN S_TemplateRoster WITH (NOLOCK) ON S_TemplateRoster.TemplateId = S_TemplateRosterLine.TemplateId AND S_TemplateRoster.ActiveStatus = 1
	WHERE	S_TemplateRosterLine.RosterGroupId = @RosterGroupId 
	AND		(S_TemplateRosterLine.TemplateId		=	@TemplateId OR @TemplateId = 0)
	--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
-- Added OU ID In Reference To JiraItem cref="E10-320" [Recon Process] Change Shift Status To On Call 
----------------------------------------------------------------------------
create PROC prS_GetSchedulePeriodByPublicHolidayDate
	@ShiftDate	Date,
	@OUId		BigInt
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)
	AND		(S_SchedulePeriod.OUId = @OUId OR @OUId = 0)
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	OR @EmployeeId = 0)	
	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_GetShiftExceptionsByDateRange]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetShiftExceptionsByDateRange]
GO

CREATE PROCEDURE [dbo].[prS_GetShiftExceptionsByDateRange]    
(
	@StartDate			DateTime,
	@EndDate			DateTime,
	@SystemParamName	nVarchar(500)
)
AS
BEGIN

	-- Retrieve Training Exception Name From D_System Parameters
	DECLARE @TrainingExceptionCode nVarchar(100) = NULL
	SELECT @TrainingExceptionCode = IsNull(ParamValue,'')
	FROM	D_SystemParams 
	WHERE	ParamName = @SystemParamName

	SELECT	ShiftExceptionId,
			S_ShiftExceptions.ShiftId,
			S_ShiftExceptions.ExceptionCodeId,
			S_Shifts.EmployeeId,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
			D_ExceptionCodes.ColorCode ExceptionColor,
			StartTime,
			EndTime,
			S_ShiftExceptions.ApprovalStatus,
			S_ShiftExceptions.Remarks,
			S_ShiftExceptions.CreatedBy,
			S_ShiftExceptions.CreatedDate,
			S_ShiftExceptions.UpdatedBy,
			S_ShiftExceptions.UpdatedDate,
			D_ExceptionType.ExceptionTypeName ExceptionType,
			D_ExceptionType.ExceptionTypeId
	FROM	S_ShiftExceptions WITH (NOLOCK)
			INNER JOIN D_ExceptionCodes WITH (NOLOCK)  ON S_ShiftExceptions.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
			INNER JOIN D_ExceptionType WITH (NOLOCK)  ON D_ExceptionCodes.ExceptionTypeId = D_ExceptionType.ExceptionTypeId
	WHERE	Convert(Date,S_ShiftExceptions.StartTime) >= Convert(Date,@StartDate)
	AND		Convert(Date,S_ShiftExceptions.StartTime) <= Convert(Date,@EndDate)
	--AND		D_ExceptionCodes.ExcpetionCodeName IN (SELECT * FROM fnStringToTable(@TrainingExceptionCode))
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 WITH (NOLOCK)
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) 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.RosterGroupId = S_RosterGroup.RosterGroupId
			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_GetShiftReport')
	DROP PROCEDURE prS_GetShiftReport
GO


CREATE PROC prS_GetShiftReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeId			BigInt,
	@CraneConditionType Int,
	@OUId				BigInt,
	@SkillIds			nVarchar(500),
	@ShiftBand			nVarchar(max),
	@ReliefBreakId		BigInt,
	@DeployStatus		Int,
	@ExceptionTypeId	Int,
	@ShiftBandTypeId	Int
)
AS

		-- Retrieve Shift Details  
	 WITH ShiftDetails AS (  
	  SELECT  S_Shifts.ShiftId,   
		J_Activity.StartTime BookingDate,   
		S_Shifts.EmployeeId,   
		J_Activity.RBRRank DeployedRank,   
		S_Shifts.RBRRank LiveRank,   
		ISNULL(S_SHifts.Notes,'') Notes,  
		C_Employee.EmployeeNumber,   
		C_Employee.DisplayName EmployeeName,   
		M_CraneSchedule.CraneId,  
		D_MasterCodes.CodeValue Priority,  
		IsNull(M_Cranes.CraneNumber,M_Equipments.EquipmentName) CraneNumber,  
		J_Activity.AllocationNo,  
		J_Activity.GroupNo,  
		J_Activity.ActivityId,  
		J_Activity.WorkType,  
		D_Roles.RoleName,  
		D_Roles.RoleDesc RoleDescription,
		D_ShiftBand.ShiftBandCode,  
		S_Shifts.ActualStartTime ShiftActualStart,  
		S_Shifts.ActualEndTime ShiftActualEnd,  
		D_Roles.RoleId,  
		J_Activity.SkillId DeployedSkillId,  
		C_EmployeeSkills.SkillId PrimarySkillId,  
		J_Activity.StartTime ActivityStartTime,  
		J_Activity.EndTime,  
		ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId   
	  FROM S_Shifts   WITH (NOLOCK)   
		INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId   
		INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId  
		INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId    
		   --INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId   
		--INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId   
		   INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId  
		   INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId  
		INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId  
		LEFT OUTER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId  
		LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK)  ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId  
		LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = M_CraneSchedule.CranePriorityId   
		LEFT OUTER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId  
		LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON J_Workload.EquipmentScheduleId = M_EquipmentSchedule.EquipmentScheduleId
		LEFT OUTER JOIN M_Equipments WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentId = M_Equipments.EquipmentId
	  WHERE S_Shifts.ShiftStartTime >= @StartDate   
	  AND  S_Shifts.ShiftEndTime <= @EndDate   
	  AND  (S_Shifts.EmployeeId = @EmployeeId OR @EmployeeId=0)  
	  AND  (J_Activity.SkillId  IN (SELECT * FROM fnStringToTable(@SkillIds)) OR @SkillIds = '0')  
	  AND  S_Shifts.OUId = @OUId  
	
	 )  
	 SELECT  ShiftDetails.*,
			 (Select top 1 B.EndTime from ShiftDetails B WITH (NOLOCK) where ShiftDetails.ShiftId=B.ShiftId Order By RowId desc)ActivityEndTime
	 FROM ShiftDetails WITH (NOLOCK)  
	 Where RowId =1

	--Crane Condition Detail
	 SELECT M_CraneConditionDetails.CraneId,   
	 'YES' Jerk,  
	 StartDate,  
	 EndDate  
	 FROM M_CraneConditiondetails WITH (NOLOCK)    
	   INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneConditionDetails.CraneId  
	 WHERE M_Cranes.OUId =  @OUId  
	 AND  M_CraneConditionDetails.ConditionType = @CraneConditionType  
	 --AND  (StartDate BETWEEN @StartDate AND @EndDate)   
	 --OR  (EndDate BETWEEN @StartDate AND @EndDate)   
	 AND    Convert(datetime,EndDate) > @StartDate   
	 AND    Convert(datetime,StartDate) < @EndDate 

	--Over Time Details
	SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)

	-- Retrieve Skills For Fixed Ranking Grouping
	SELECT	D_Skill.SkillId, D_SKill.FixedRanking,
			D_Skill.Skill SkillName
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK) ON D_Skill.SkillId = D_SkillOU.SkillId
	WHERE	D_SkillOU.OUId	=	@OUId
	AND		D_Skill.FixedRanking IS NOT NULL

	-- Retrieve Standy Employee Details
	;WITH StandbyEmployeeActivity as 
	(
		SELECT	J_Activity.ActivityId, 
				J_Activity.StartTime, 
				S_Shifts.ShiftId, 
				J_Activity.SkillId DeployedSkill,
				J_Activity.RBRRank DeployedRank,
				J_Activity.AllocationNo,
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus,
				J_Activity.WorkType	,
				J_Activity.SkillId DeployedSkillId
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
				--LEFT OUTER JOIN S_EmployeeLeaves WITH (NOLOCK) ON  S_EmployeeLeaves.EmployeeId = S_Shifts.EmployeeId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')		
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		AND		J_Activity.SkillId !=  @ReliefBreakId
	
	)
	SELECT	C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStartTime,
			C_EmployeeSkills.SkillId,
			S_Shifts.ShiftId,
			S_Shifts.EmployeeId, 
			ISNULL(S_Shifts.Notes,'') Notes,
			ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) DeploymentStatus,
			S_Shifts.RBRRank LiveRank,
			StandbyEmployeeActivity.DeployedRank,
			D_Roles.RoleName,
			D_Roles.RoleDesc RoleDescription,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			StandbyEmployeeActivity.WorkType,
			StandbyEmployeeActivity.ActivityId,
			StandbyEmployeeActivity.AllocationNo,
			StandbyEmployeeActivity.DeployedSkillId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN StandbyEmployeeActivity WITH (NOLOCK) ON S_Shifts.ShiftId = StandbyEmployeeActivity.ShiftId And StandbyEmployeeActivity.RowNumber = 1
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			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 = S_Shifts.RoleId and D_Roles.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE	(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		ISNULL(StandbyEmployeeActivity.DeploymentStatus,2) = @DeployStatus
	AND		(C_EmployeeSkills.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		D_ShiftBand.ShiftTypeId != @ShiftBandTypeId

	--Retrieve Non Primary Skill Deployed Employee Detail

	;WITH NonPrimarySkillActivity as   
	 (  
	 SELECT	J_Activity.ActivityId, 
					J_Activity.StartTime, 
					S_Shifts.ShiftId, 
					J_Activity.SkillId DeployedSkillId,
					J_Activity.RBRRank DeployedRank,
					J_Activity.WorkType,
					J_Activity.AllocationNo,
					D_MasterCodes.CodeValue Priority,  
					iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) CraneNumber, 
					ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
					1 DeploymentStatus
			FROM	J_Activity WITH (NOLOCK) 
					INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
					INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
					LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
					INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
					LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
					LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
					LEFT OUTER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = M_CraneSchedule.CranePriorityId   
			WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @StartDate)
			AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
			AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
			AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
			AND		J_Activity.SkillId !=  @ReliefBreakId
	 )  
	 SELECT C_Employee.EmployeeNumber, 
			C_Employee.DisplayName EmployeeName,  
			C_Employee.EmployeeId,
			C_EmployeeSkills.SkillId PrimarySkillId,  
			NonPrimarySkillActivity.DeployedSkillId,  
			ISNULL(S_Shifts.Notes,'') Notes,
			S_Shifts.RBRRank LiveRank,
			NonPrimarySkillActivity.DeployedRank,
			S_Shifts.ShiftId ,
			D_Roles.RoleName,
			D_Roles.RoleDesc RoleDescription,
			D_ShiftBand.ShiftBandCode,
			S_Shifts.ActualStartTime ShiftActualStart,
			S_Shifts.ActualEndTime ShiftActualEnd,
			D_Roles.RoleId,
			NonPrimarySkillActivity.WorkType,
			NonPrimarySkillActivity.ActivityId,
			NonPrimarySkillActivity.AllocationNo,
			NonPrimarySkillActivity.CraneNumber,
			NonPrimarySkillActivity.Priority
	FROM    S_Shifts WITH (NOLOCK) INNER JOIN NonPrimarySkillActivity WITH (NOLOCK) ON S_Shifts.ShiftId = NonPrimarySkillActivity.ShiftId And NonPrimarySkillActivity.RowNumber = 1  
			INNER JOIN C_Employee WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId  
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId  
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId AND C_EmployeeSkills.IsPrimary = 1  
			INNER JOIN C_EmployeeRoles WITH (NOLOCK) ON C_EmployeeRoles.EmployeeId = C_Employee.EmployeeId AND C_EmployeeRoles.IsPrimaryRole = 1  
			INNER JOIN D_Roles EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId  
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId   
			INNER JOIN D_ShiftBand   WITH (NOLOCK) ON D_ShiftBand.ShiftBandId = S_Shifts.ShiftBandId
	WHERE   NonPrimarySkillActivity.DeployedSkillId != C_EmployeeSkills.SkillId  

	--Unallocated Work
	
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.WorkloadId,
			CraneWorkLoad.CraneScheduleId,
			EquipmentWorkLoad.EquipmentScheduleId,
	        iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) CraneNumber,
			Equipments.EquipmentId,
			Cranes.CraneId,
			J_Activity.RBRRank DeployedRank,
			J_Activity.WorkType,
			J_Activity.AllocationNo,
			J_Activity.SkillId DeployedSkillId,
			J_Activity.StartTime ActivityStartTime,  
			J_Activity.EndTime ActivityEndTime
	FROM    J_Activity  WITH (NOLOCK)
			LEFT OUTER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId  
			LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId  
			LEFT OUTER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId  
			LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId  
			LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId  
	WHERE	(J_Activity.ShiftId IS NULL OR J_Activity.ShiftId = 0)
	AND		J_Activity.StartTime > =@StartDate 
	AND		J_Activity.EndTime < = @EndDate
	AND		J_Activity.SkillId !=  @ReliefBreakId
	AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@SkillIds)))
	AND		(J_Activity.OUId = @OUId OR @OUId = 0)

	--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode
	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  Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@StartDate)
	AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) >= Convert(Date,@StartDate)
	AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) >= Convert(Date,@StartDate)
	AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@EndDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 
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),
	@EmployeeId					BigInt
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,
			S_Shifts.ReconStatusId,
			S_Shifts.Reconciled,
			S_Shifts.OnCallShift
	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 = @EmployeeId OR @EmployeeId = 0)
	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 D_Roles.RoleId = C_EmployeeRoles.RoleId
				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)
	AND		S_Shifts.EmployeeId NOT IN (SELECT	EmployeeId FROM L_UCL WITH (NOLOCK) 
										WHERE	Convert(Date,UCLDate) >= Convert(Date,@StartDate)
										AND		Convert(Date,UCLDate) <= Convert(Date,@EndDate))
	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',
			'' ClockInTime,
			'' ClockOutTime,
			D_ShiftBand.ShiftBandCode ShiftBand,
			Convert(nVarchar(5),Convert(Time,S_Shifts.ShiftStartTime)) ShiftStartTime,
			Convert(nVarchar(5),Convert(Time,S_Shifts.ShiftEndTime)) ShiftEndTime
	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',
			IsNull(Convert(nVarchar(5),Convert(Time,S_Shifts.InTime)),'') ClockInTime,
			IsNull(Convert(nVarchar(5),Convert(Time,S_Shifts.OutTime)),'') ClockOutTime,
			'' ShiftBand,
			'' ShiftStartTime,
			'' ShiftEndTime
	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',
			'' ClockInTime,
			'' ClockOutTime,
			'' ShiftBand,
			'' ShiftStartTime,
			'' ShiftEndTime
	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
	--Added UCL Leave to display in calender E10-619
	UNION ALL 
	SELECT	Convert(nVarchar,L_UCL.UCLID) + 'UCL' id,
			D_ExceptionCodes.ExcpetionCodeName as text,
			'Leave Details' details,
			Convert(nVarchar,Convert(Date,L_UCL.UCLDate)) as 'start_date',
			Convert(nVarchar,Convert(Date,L_UCL.UCLDate)) as 'end_date',
			D_ExceptionCodes.ColorCode color,
			'' textColor, 
			'UCL' as 'type',
			'' ClockInTime,
			'' ClockOutTime,
			'' ShiftBand,
			'' ShiftStartTime,
			'' ShiftEndTime
	FROM	L_UCL WITH (NOLOCK)
			INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = L_UCL.ExceptionCodeId
			LEFT  JOIN  S_EmployeeLeaves  WITH (NOLOCK) ON S_EmployeeLeaves.FromDate = L_UCL.UCLDate
				  AND   L_UCL.EmployeeId =  S_EmployeeLeaves.EmployeeId
	WHERE	C_Employee.EmployeeId = @EmployeeId
	AND		Convert(Date,L_UCL.UCLDate) >= Convert(Date,@StartDate)
	AND		Convert(Date,L_UCL.UCLDate) <= Convert(Date,@EndDate)
	AND		S_EmployeeLeaves.LeaveId IS 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	S_Shifts.ShiftId, ActualStartTime, ActualEndTime, IsNull(J_Activity.ActivityId,0) ActivityId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT OUTER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
	WHERE	EmployeeId	=	@EmployeeId	
	AND 	Convert(Date,ShiftStartTime) = CONVERT(Date, @ShiftDate)
END
GO

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

 
create PROCEDURE [dbo].[prS_GetShiftStartAndEndByEmployeeIdAndDateRange]   
(	
	@EmployeeId		BigInt,
	@StartDate		DateTime,
	@EndDate        DateTime
)
AS
BEGIN	 
	
	SELECT	S_Shifts.ShiftId, ActualStartTime, ActualEndTime, IsNull(J_Activity.ActivityId,0) ActivityId
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT OUTER JOIN J_Activity WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId
	WHERE	EmployeeId	=	@EmployeeId	
	AND 	Convert(Date,ShiftStartTime) >= CONVERT(Date, @StartDate)
	AND     COnvert(Date,ShiftStartTime) <= CONVERT(Date,@EndDate)
END
GO

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

 
CREATE PROCEDURE [dbo].[prS_GetShiftStartDateByDateAndEmployeeId]   
(	
	@EmployeeId		BigInt,
	@StartDate		DateTime	
)
AS
BEGIN	 
	
	SELECT	S_Shifts.ShiftId, ActualStartTime, ActualEndTime
	FROM	S_Shifts WITH (NOLOCK) 			
	WHERE	EmployeeId	=	@EmployeeId	
	AND 	Convert(Date,ShiftStartTime) >= CONVERT(Date, @StartDate)	
	Order By S_Shifts.ActualStartTime
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_GetSwapShiftEmployeeDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_GetSwapShiftEmployeeDetail]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prS_GetSwapShiftEmployeeDetail] 
(
	@EmployeeId				BigInt,
	@OUId					BigInt,
	@ShiftDate				DateTime,
	@ShiftBandId			BigInt,
	@ExceptionTypeId		BigInt,
	@SkillId				BigInt
)
AS

BEGIN	 
	-- List of Employees who are assinged to  work
	SELECT S_Shifts.ShiftId,
		   S_Shifts.EmployeeId,
		   S_Shifts.RoleId,
		   C_Employee.EmployeeNumber,
		   C_Employee.DisplayName EmployeeName,
		   D_Roles.RoleName,
		   S_Shifts.ShiftStartTime,
		   S_Shifts.ShiftEndTime,
		   C_EmployeeSkills.SkillId,
		   C_Employee.EmployeeId id,
		   C_Employee.EmployeeNumber + ' - ' + Replace(LTRIM(RTRIM(C_Employee.DisplayName)),'-','') + ' - ' + D_Roles.RoleName [text]
	FROM   S_Shifts WITH(NOLOCK)
		   INNER JOIN C_Employee WITH(NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
		   INNER JOIN D_Roles  WITH(NOLOCK) ON  D_Roles.RoleId = S_Shifts.RoleId 
		   INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId AND C_EmployeeSkills.IsPrimary = 1
	WHERE  (S_Shifts.ShiftBandId = @ShiftBandId OR @ShiftBandId= 0)
	AND	   Convert(Date,S_Shifts.ShiftStartTime) = Convert(Date,@ShiftDate)	
	AND	   S_Shifts.OUId = @OUId
	AND	   (S_Shifts.EmployeeId != @EmployeeId OR @EmployeeId = 0)
	--AND	   (S_Shifts.RoleId = @RoleId OR @RoleId = 0)

	UNION ALL
	-- List of Employees who are not assinged to any work
	SELECT	0 ShiftId,
			C_Employee.EmployeeId,
			C_EmployeeRoles.RoleId,
			C_Employee.EmployeeNumber,
			C_Employee.DisplayName EmployeeName,
			D_Roles.RoleName,
			NULL ShiftStartTime,
			NULL ShiftEndTime,
			C_EmployeeSkills.SkillId,
			C_Employee.EmployeeId id,
		    C_Employee.EmployeeNumber + ' - ' + Replace(LTRIM(RTRIM(C_Employee.DisplayName)),'-','') + ' - ' + D_Roles.RoleName [text]
	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,ShiftStartTime) = Convert(Date, @ShiftDate))
	AND	   (C_Employee.EmployeeId != @EmployeeId OR @EmployeeId = 0)
	AND	   (C_EmployeeSkills.SkillId = @SkillId)
	


		--Employee Leaves
	;WITH EmployeeLeave as (
	SELECT S_EmployeeLeaves.EmployeeId,
		   C_Employee.EmployeeNumber,
		   D_ExceptionCodes.ExceptionCodeDesc ExceptionCode,
		   S_EmployeeLeaves.FromDate LeaveDate
	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  Convert(Date,S_EmployeeLeaves.FromDate) >= Convert(Date,@ShiftDate)
	AND	   Convert(Date,S_EmployeeLeaves.FromDate) <= Convert(Date,@ShiftDate)
	AND	   S_EmployeeLeaves.EmployeeId != @EmployeeId

	UNION ALL

	SELECT L_UCL.EmployeeId,
		   C_Employee.EmployeeNumber,	
		   'UCL' ExceptionCode,
		   L_UCL.UCLDate LeaveDate
	FROM   L_UCL WITH (NOLOCK)
		   INNER JOIN C_Employee WITH (NOLOCK) ON L_UCL.EmployeeId = C_Employee.EmployeeId		  
	WHERE  Convert(Date,L_UCL.UCLDate) >= Convert(Date,@ShiftDate)
	AND	   Convert(Date,L_UCL.UCLDate) <= Convert(Date,@ShiftDate)
	AND    L_UCL.EmployeeId != @EmployeeId

	UNION ALL

	SELECT C_Employee.EmployeeId,
		   C_Employee.EmployeeNumber,
		   'Exclude Deployment' ExceptionCode,
		   S_ShiftExceptions.StartTime  LeaveDate
	FROM   S_ShiftExceptions  WITH (NOLOCK)
		   INNER JOIN  S_Shifts WITH (NOLOCK) ON S_Shifts.ShiftId = S_ShiftExceptions.ShiftId
		   INNER JOIN  C_Employee  WITH (NOLOCK) ON C_Employee.EmployeeId = S_Shifts.EmployeeId
		   INNER JOIN  D_ExceptionCodes  WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
		   INNER JOIN  D_ExceptionType  WITH (NOLOCK) ON D_ExceptionType.ExceptionTypeId = D_ExceptionCodes.ExceptionTypeId
	WHERE  Convert(Date,S_ShiftExceptions.StartTime) >= Convert(Date,@ShiftDate)
	AND	   Convert(Date,S_ShiftExceptions.EndTime) <= Convert(Date,@ShiftDate)
	AND	   D_ExceptionCodes.ExceptionTypeId = @ExceptionTypeId
	AND    C_Employee.EmployeeId != @EmployeeId

	)
	SELECT  * FROM EmployeeLeave WITH(NOLOCK) 

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 C_Employee WITH (NOLOCK) ON C_Employee.RosterGroupId = S_RosterGroup.RosterGroupId
			--inner join S_RosterGroupDetails WITH (NOLOCK) on S_RosterGroupDetails.RosterGroupId = S_RosterGroup.RosterGroupId
	WHERE	EmployeeId = @EmployeeId
END
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,
		ActiveStatus
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='14-03259'
	--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
BEGIN
	UPDATE	C_Employee 
	SET		RosterGroupId	=	@RosterGroupID 
	WHERE	EmployeeId		=	@EmployeeID
	
	--If (@ValidateDuplicate != 0) SET @RosterGroupDetailsID = @ValidateDuplicate
	SELECT 1 --@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	RosterGroup.RosterGroupId RosterGroupId,
			Emp.EmployeeId EmployeeId,			 
			RosterGroup.CreatedBy,
			RosterGroup.CreatedDate,
			RosterGroup.UpdatedBy,
			RosterGroup.UpdatedDate,
			Emp.EmployeeNumber, 
			Emp.DisplayName EmployeeName,
			RosterGroup.GroupName RosterGroupName,
			RosterGroup.GroupDesc RosterGroupDescription
	FROM	C_Employee Emp WITH (NOLOCK) 
			INNER JOIN S_RosterGroup RosterGroup WITH (NOLOCK) ON RosterGroup.RosterGroupId = Emp.RosterGroupId
			AND Emp.ActiveStatus = 1
	WHERE	(RosterGroup.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,
		   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_RosterGroup.RosterGroupId 
			--AND C_Employee.EmployeeId = S_RosterGroupDetails.EmployeeId
	WHERE	(S_RosterGroup.RosterGroupId = @RosterGroupID OR @RosterGroupID = 0)
	AND		C_Employee.OUId = @OUID
	AND		C_Employee.ActiveStatus = 1
	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,
			RosterGroup.TemplateId
	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,
	@IncludeLeave          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,
		IncludeLeave,
		CreatedBy,
		CreatedDate)
 VALUES(@Name, @Description, @ValidFrom, @ValidTo, @PeriodLength,@ShiftLengthMin,@ShiftLengthMax,@DaysPerPeriodMin,
 @DaysPerPeriodMax,@TimePerPeriodMin,@TimePerPeriodMax,@ContDaysScheduleOnMin,@ContDaysScheduleOnMax,@ContDaysScheduleOffMin,
 @ContDaysScheduleOffMax,@MinRestTime,@RestDelimiter,@OffDaysPerPeriodMin,@OffDaysPerPeriodMax,@IsOffDaysMaxForced,
 @ActiveStatus,@IncludeLeave,@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.IncludeLeave,
				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,
	@IncludeLeave          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, 
				 IncludeLeave           =@IncludeLeave,
				 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_THPEmployeeEquipmentDetails
	WHERE	ShiftId = @ShiftId 

	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,
				DeploymentNotes		=	REPLACE(DeploymentNotes,'Assemble Shift',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,
		S_Shifts.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,
		D_Roles.RoleName,
		D_RoleGroup.RoleGroupName
FROM	S_Shifts WITH (NOLOCK) 
		INNER JOIN D_Roles  WITH (NOLOCK) ON S_Shifts.RoleId = D_Roles.RoleId
		INNER JOIN D_RoleGroup WITH (NOLOCK) ON D_RoleGroup.RoleGroupId = D_Roles.RoleGroupId
		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 WITH (NOLOCK) INNER JOIN P_ShiftCosts WITH (NOLOCK) 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(S_Shifts.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
		SELECT @ShiftInTime = S_Shifts.ActualStartTime, @ShiftOutTime = S_Shifts.ActualEndTime
		FROM   S_Shifts WITH (NOLOCK) WHERE S_Shifts.ShiftId = @ShiftId
		--END
		--Fixed for actual start & end time affecting shift band over time E10-842
		update	S_Shifts 
		--SET		ShiftStartTime				=	@ShiftInTime,
		--		ShiftEndTime				=	@ShiftOutTime,
		--		ActualStartTime				=	@ShiftInTime,
		--		ActualEndTime				=	@ShiftOutTime,
		SET		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_THPEmployeeCraneConditionCounterIns')
	DROP PROC prS_THPEmployeeCraneConditionCounterIns
GO

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeCraneConditionCounter
----------------------------------------------------------------------------
CREATE PROCEDURE prS_THPEmployeeCraneConditionCounterIns
	@EmployeeId				BigInt,
	@CraneConditionTypeId	BigInt,
	@THPPeriodId			BigInt,
	@StartDate				DateTime,
	@EndDate				DateTime
AS
DECLARE @TransId BigInt = 0
BEGIN
	
	SELECT @TransId =  IsNUll(TransId,0)
	FROM	S_THPEmployeeCraneConditionCounter
	WHERE	EmployeeId		=	@EmployeeId
	AND		@THPPeriodId	=	@THPPeriodId

	IF (@TransId = 0)
	BEGIN
		INSERT S_THPEmployeeCraneConditionCounter(EmployeeId, CraneConditionTypeId, THPPeriodId, StartDate, EndDate, Occurrence)
		VALUES (@EmployeeId, @CraneConditionTypeId, @THPPeriodId, @StartDate, @EndDate, 1)

		SELECT CAST(@@Identity AS INTEGER) 
	END
	ELSE
	BEGIN 
		UPDATE	S_THPEmployeeCraneConditionCounter 
		SET		Occurrence = Occurrence + 1
		WHERE	EmployeeId	=	@EmployeeId
		AND		THPPeriodId	=	@THPPeriodId

		SELECT 1
	END
END

GO


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

----------------------------------------------------------------------------
-- Insert a single record into S_THPEmployeeDetails
----------------------------------------------------------------------------
CREATE PROCEDURE prS_THPEmployeeEquipmentCounterIns
	@THPPeriodId		BigInt = 0,
	@EmployeeId			BigInt = 0,
	@ShiftId			BigInt = 0,
	@ShiftDate			DateTime,
	@EquipmentId		BigInt = 0,
	@ActivityCounter	Decimal(18,2),
	@THPProcessDate		DateTime,
	@THPNotes			nVarchar(500),
	@CreatedBy			nVarchar(50)
AS
BEGIN
	DELETE FROM S_THPEmployeeEquipmentDetails 
	Where	ShiftId		=	@ShiftId
	AND		EquipmentId	=	@EquipmentId

	INSERT S_THPEmployeeEquipmentDetails
	(THPPeriodId, EmployeeId, ShiftDate, ShiftId, EquipmentId, ActivityCounter, THPProcessDate, THPNotes, CreatedBy, CreatedDate)
	VALUES (@THPPeriodId, @EmployeeId, @ShiftDate, @ShiftId, @EquipmentId, @ActivityCounter, @THPProcessDate, @THPNotes, @CreatedBy, GETDATE())

	SELECT CAST(@@Identity AS INTEGER) 

END

GO


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

CREATE PROC prS_UpdateEmployeeIdByShiftId
	@EmployeeId	BigInt,
	@ShiftId	BigInt,
	@UpdatedBy	nVarchar(50)
AS

	UPDATE	S_Shifts
	SET		EmployeeId	=	@EmployeeId,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GETDATE()
	WHERE	ShiftId		=	@ShiftId

	SELECT 1
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_UpdateEmployeeOverTimeRule')
	DROP PROC prS_UpdateEmployeeOverTimeRule
GO

CREATE PROC prS_UpdateEmployeeOverTimeRule
	@OverTimeId 		  BigInt,
	@EmployeeId			  BigInt,	
	@Action               Int, 
	@UpdatedBy			  nVarchar(50)
AS
BEGIN
	UPDATE	C_Employee
	SET		OvertimeId		    =	IIF(@Action = 2 , NULL, @OverTimeId),
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeId			=	@EmployeeId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateEmployeePayGroup')
	DROP PROC prS_UpdateEmployeePayGroup
GO

CREATE PROC prS_UpdateEmployeePayGroup
	@PayGroupId  		  BigInt,
	@EmployeeId			  BigInt,	
	@Action               Int, 
	@UpdatedBy			  nVarchar(50)
AS
BEGIN
	UPDATE	C_Employee 
	SET		PayGroupId	        =	IIF(@Action = 2 , NULL, @PayGroupId),
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeId			=	@EmployeeId

	SELECT 1
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateEmployeeScheduleRule')
	DROP PROC prS_UpdateEmployeeScheduleRule
GO

----------------------------------------------------------------------------
-- Delete a single record from M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC prS_UpdateEmployeeScheduleRule
	@ScheduleRuleId		  BigInt,
	@EmployeeId			  BigInt,	
	@Action               Int, 
	@UpdatedBy			  nVarchar(50)
AS

	UPDATE	C_Employee
	SET		ScheduleRuleId		=	IIF(@Action = 2 , NULL, @ScheduleRuleId),
			UpdatedBy			=	@UpdatedBy,
			UpdatedDate			=	GETDATE()
	WHERE	EmployeeId			=	@EmployeeId

	SELECT 1

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),
	@UpdatedBy		nVarchar(50)
AS
BEGIN
	UPDATE	S_PublicholidayEmployeeList
	SET		TypeId		=	@TypeId, 
			TypeDesc	=	@TypeDesc,
			UpdatedBy	=	@UpdatedBy,
			UpdatedDate	=	GETDATE()
	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
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prS_UpdateRosterGroupTemplateId')
	DROP PROC prS_UpdateRosterGroupTemplateId
GO

----------------------------------------------------------------------------
--Update Current Roster Groups Template Id which will be used in Roster Group & Employee Movement Chnages
----------------------------------------------------------------------------
CREATE PROC prS_UpdateRosterGroupTemplateId
(
	@RosterGroupId	BigInt = 0,
	@TemplateId		BigInt = 0,
	@UpdatedBy		nVarchar(50)
)
AS
BEGIN
	
	UPDATE	S_RosterGroup 
	SET		TemplateId		=	@TemplateId,
			UpdatedBy		=	@UpdatedBy,
			UpdatedDate		=	GETDATE()
	WHERE	RosterGroupId	=	@RosterGroupId
	
	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_UpdateShiftLiveRankByShiftId')
	DROP PROC prS_UpdateShiftLiveRankByShiftId
GO

----------------------------------------------------------------------------
-- Update Shift Live Rank By Shift Id
----------------------------------------------------------------------------
CREATE PROC prS_UpdateShiftLiveRankByShiftId
	@ShiftId	BigInt,
	@LiveRank	nVarchar(2),
	@UpdatedBy	nVarchar(50)
AS
	UPDATE	S_Shifts
	SET		RBRRank		=	@LiveRank,
			UpdatedBy	=	@UpdatedBy
	WHERE	ShiftId		=	@ShiftId

	SELECT 1;
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_UpdateShiftNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_UpdateShiftNotes]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prS_UpdateShiftNotes]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prS_UpdateShiftNotes]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[prS_UpdateShiftNotes]    
(
	@ShiftNotes UTS_ShiftNotes readonly	
)
AS

BEGIN
 
	--Update Notes
	Merge S_Shifts as Target Using @ShiftNotes as Source on(Target.ShiftId =Source.ShiftId And IsNull(Target.Notes,'') != IsNull(Source.Notes,''))	
	when Matched then
	Update Set Target.Notes=Source.Notes,Target.UpdatedBy=Source.UpdatedBy,
	Target.UpdatedDate=getdate();

	select 1
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),
	@ReconStatusId			int = null
AS
BEGIN
	
	UPDATE	S_Shifts 
	SET		ReconTime = Null,
			Reconciled = 0,
			ReconStatusId = @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_UpdateShifts')
	DROP PROC prS_UpdateShifts
GO

----------------------------------------------------------------------------
-- Update a single record in S_Shifts
----------------------------------------------------------------------------
CREATE PROC prS_UpdateShifts
	@ShiftId        bigInt,
	@ShiftBandId    bigInt,
	@ShiftStartTime DateTime,
	@ShiftEndTime   DateTime,
	@ActualStartTime DateTime,
	@ActualEndTime  DateTime,
	@OTStartTime    DateTime,
	@OTEndTime      DateTime,
	@UpdatedBy      nVarchar(50),
	@UpdatedDate    DateTime
AS
UPDATE	S_Shifts
	SET		ShiftBandId		=	@ShiftBandId,
			ShiftStartTime	=	@ShiftStartTime,
			ShiftEndTime	=	@ShiftEndTime,
			ActualStartTime =   @ActualStartTime,
			ActualEndTime   =   @ActualEndTime,
			OTStartTime     =   @OTStartTime,
			OTEndTime       =   @OTEndTime,
			UpdatedDate     =   @UpdatedDate,
			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,
	@ActiveStatus	Bit = 0
AS

UPDATE	S_THPSettings 
SET		OUId			=	@OUId, 
		StartDate		=	@StartDate, 
		PeriodUnit		=	@PeriodUnit, 
		PeriodLength	=	@PeriodLength, 
		UpdatedBy		=	@UpdatedBy, 
		UpdatedDate		=	GETDATE(),
		ActiveStatus	=	@ActiveStatus
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,
	@NormalHourPaycodeId    BigInt,
	@ShiftBandId		 nVarchar(max)
)
AS
DECLARE @__shiftBandIds BIGINT = 0
BEGIN	 
			;WITH 
			ShiftOverTime (ShiftId, ApprovedOverTimeHours, ApprovalStatus)
			AS
			(
				SELECT  S_Shifts.ShiftId, Sum(P_ShiftCosts.ApprovedHours) ApprovedOverTimeHours, Max(P_ShiftCosts.ApprovalStatus)
				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 D_PayCodes WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_Paycodes.IsEditable = 1
				WHERE 	C_OrganizationNode.OUId = @OUId 
				AND		CONVERT(DATE,S_Shifts.ActualStartTime)>=CONVERT(DATE,@StartDate)
				AND		CONVERT(DATE,S_Shifts.ActualStartTime)<=CONVERT(DATE,@EndDate)	
				AND		(S_Shifts.ShiftBandId IN (SELECT * from fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')
				GROUP BY S_Shifts.ShiftId
			),
			NormalHours As(
				SELECT  DISTINCT S_Shifts.ShiftId,P_ShiftCosts.PayCodeId, P_ShiftCosts.ApprovedHours ApprovedNormalHours
				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 D_PayCodes WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_Paycodes.IsEditable = 0
						INNER JOIN D_PaygroupCodes  WITH (NOLOCK) ON  D_PaygroupCodes.PayCodeId = D_PayCodes.PayCodeId
						INNER JOIN D_PayCodeType  WITH (NOLOCK) ON  D_PaygroupCodes.PaycodeType = D_PayCodeType.PaycodeTypeId AND D_PayCodeType.PayCodeTypeValue =1
				WHERE 	C_OrganizationNode.OUId = @OUId 
				AND		CONVERT(DATE,S_Shifts.ActualStartTime)>=CONVERT(DATE,@StartDate)
				AND		CONVERT(DATE,S_Shifts.ActualStartTime)<=CONVERT(DATE,@EndDate)
				AND		D_PaygroupCodes.PaycodeType = @NormalHourPaycodeId	
				AND		(S_Shifts.ShiftBandId IN (SELECT * from fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')
			)
			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,
					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(ShiftOverTime.ApprovedOverTimeHours,0) ApprovedOverTimeHours,
					S_Shifts.Remarks,
					IsNull(ShiftOverTime.ApprovalStatus,1) ShiftCostApprovalStatus,
					ISNULL(NormalHours.ApprovedNormalHours,DateDiff(MINUTE,0,(ShiftEndTime-ShiftStartTime)) )ApprovedNormalHours,
					ISNULL(PublicHolidayId,0) PublicHolidayId
		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
				LEFT OUTER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_EmployeeLeaves.ExceptionCodeId
				LEFT OUTER JOIN NormalHours WITH (NOLOCK) ON NormalHours.ShiftId = S_Shifts.ShiftId
				LEFT OUTER JOIN D_PublicHolidays WITH (NOLOCK) ON Convert(DATE,S_Shifts.ShiftEndTime) >= Convert(DATE,D_PublicHolidays.HolidayDate)
								AND Convert(DATE,S_Shifts.ShiftStartTime) <= Convert(DATE,D_PublicHolidays.HolidayDate)
		WHERE 	C_OrganizationNode.OUId = @OUId 		
		AND		CONVERT(DATE,S_Shifts.ActualStartTime)>=CONVERT(DATE,@StartDate)
		AND		CONVERT(DATE,S_Shifts.ActualStartTime)<=CONVERT(DATE,@EndDate)		
		AND		C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%')
		AND		(S_Shifts.ReconStatusId = @ReconStatusId OR @ReconStatusId = 0)
		AND		((S_Shifts.InStatus = @AttendanceStatusId AND  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)
		AND		(S_Shifts.ShiftBandId IN (SELECT * from fnStringToTable(@ShiftBandId)) OR @ShiftBandId ='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),
	@ReconStatusId			Int = NULL
)
AS
BEGIN	 
	
	UPDATE	S_Shifts 
	SET		Remarks						=	@TerminalName,
			ReconTime					=	Null,
			Reconciled					=	0,
			ReconStatusId				=	@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(), 0, @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
/****** Object:  StoredProcedure [dbo].[prTA_GetAttendanceMonitor]   ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'prTA_GetAttendanceMonitor') AND type in (N'P', N'PC'))
	DROP PROCEDURE prTA_GetAttendanceMonitor
GO
 
CREATE PROCEDURE prTA_GetAttendanceMonitor
(
	@EmployeeId		nVarchar(max),
	@RoleGroups		nVarchar(max),
	@ShiftDate		DateTime,
	@ShiftBand		nVarchar(max),
	@Skills			nVarchar(max),
	@AttStatus		int,
	@ReliefBreakId	BigInt,
	@OUId			BigInt,
	@DeployStatus   int
)
AS
BEGIN
	;WITH FirstActivity as 
	(
		SELECT	J_Activity.ActivityId, J_Activity.StartTime, S_Shifts.ShiftId, J_Activity.SkillId,
				iif(CraneWorkLoad.CraneScheduleId  != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName, 
				ROW_NUMBER() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
				1 DeploymentStatus
		FROM	J_Activity WITH (NOLOCK) 
				INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
				INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
				INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
				LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
				LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE	Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @ShiftDate)
		AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
		AND		(J_Activity.SkillId IN (SELECT * FROM fnStringToTable(@Skills))  OR @Skills = '0')
		AND		J_Activity.SkillId != @ReliefBreakId
		AND		(S_Shifts.OUId = @OUId OR @OUId = 0)
		
	)
	SELECT	C_Employee.EmployeeNumber, C_Employee.DisplayName EmployeeName,
			S_Shifts.ShiftStartTime ShiftStart, 
			S_Shifts.InTime ClockInTime,
			S_Shifts.ShiftEndTime ShiftEnd,
			S_Shifts.OutTime ClockOutTime,
			S_Shifts.ReconStatusId AttendanceStatusId,
			EmpPrimaryRole.RoleName PrimaryRole,
			FirstActivity.SkillId, S_Shifts.RoleId, S_Shifts.ShiftId,
			FirstActivity.EquipmentName FirstEquipmentName, FirstActivity.StartTime FirstActivityStartTime,
			isnull(FirstActivity.DeploymentStatus,2) DeploymentStatus
	FROM	S_Shifts WITH (NOLOCK) 
			LEFT JOIN FirstActivity WITH (NOLOCK) ON S_Shifts.ShiftId = FirstActivity.ShiftId And FirstActivity.RowNumber = 1
			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 EmpPrimaryRole WITH (NOLOCK) ON EmpPrimaryRole.RoleId = C_EmployeeRoles.RoleId
			INNER JOIN D_Roles WITH (NOLOCK) ON D_Roles.RoleId = S_Shifts.RoleId 
	WHERE	(S_Shifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeId)) OR @EmployeeId = '0')
	AND		(D_Roles.RoleGroupId IN (SELECT * FROM fnStringToTable(@RoleGroups)) OR @RoleGroups = '0')
	AND		Convert(Date,S_Shifts.ActualStartTime) = Convert(Date, @ShiftDate)
	AND		(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBand))  OR @ShiftBand = '0')
	AND		(isnull(FirstActivity.DeploymentStatus,2) = @DeployStatus OR @DeployStatus = 0)
	AND		S_Shifts.ShiftId NOT IN (	SELECT	ShiftId 
										FROM	S_EmployeeLeaves WITH (NOLOCK) 
										WHERE	Convert(Date, FromDate) = Convert(Date,@ShiftDate)
										AND		ShiftId IS NOT NULL
									)
	AND		S_Shifts.EmployeeId NOT IN (SELECT EmployeeId FROM L_UCL WITH (NOLOCK) WHERE Convert(Date,UCLDate) = Convert(Date,@ShiftDate))
	AND		S_Shifts.ShiftId NOT IN (SELECT ShiftId FROM S_ShiftExceptions WITH (NOLOCK) WHERE Convert(Date,StartTime) = Convert(Date, @ShiftDate))
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prTA_GetCraneConditionByShiftId')
	DROP PROCEDURE prTA_GetCraneConditionByShiftId
GO

CREATE PROC prTA_GetCraneConditionByShiftId
 (
	@ShiftId				BigInt,
	@IncentiveCraneHours	Int,
	@CraneConditionType		Int
)
AS
BEGIN
	;WITH CraneConditions AS (
	SELECT	J_Activity.ActivityId,
			J_Activity.StartTime,
			J_Activity.EndTime,
			J_Activity.ShiftId,
			M_Cranes.CraneNumber,
			DATEDIFF(HOUR,J_Activity.StartTime, J_Activity.EndTime) TotalHours,
			ROW_NUMBER() OVER(PARTITION BY M_Cranes.CraneNumber, J_Activity.ShiftId ORDER BY J_Activity.StartTime) RowId 
	FROM	J_Activity WITH (NOLOCK) 
			INNER JOIN J_Workload WITH (NOLOCK) ON J_Activity.WorkloadId = J_Workload.WorkloadId
			INNER JOIN M_CraneSchedule WITH (NOLOCK) ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId 
			INNER JOIN M_CraneConditionDetails WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_CraneConditionDetails.CraneId
			INNER JOIN S_Shifts WITH (NOLOCK) ON J_Activity.ShiftId = S_Shifts.ShiftId And S_Shifts.ShiftId = @ShiftId
			AND		Convert(DateTime,M_CraneConditionDetails.EndDate) >= Convert(DateTime,S_Shifts.ShiftStartTime) 
			AND		Convert(DateTime,M_CraneConditionDetails.StartDate) <= Convert(DateTime,S_Shifts.ShiftEndTime)
	WHERE	Convert(DateTime,J_Activity.StartTime) >= Convert(DateTime,S_Shifts.ShiftStartTime)
	AND		Convert(DateTime,J_Activity.EndTime) <=   Convert(DateTime,S_SHifts.ShiftEndTime)
	AND		J_Activity.ShiftBandId = S_SHifts.ShiftBandId
	AND		M_CraneConditionDetails.ConditionType = @CraneConditionType
	AND		DATEDIFF(HOUR,J_Activity.StartTime, J_Activity.EndTime) > @IncentiveCraneHours
	)
	SELECT * FROM CraneConditions Where RowId = 1
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, 0 HourlyRate,--Convert(Decimal,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,
			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
							AND D_RamadanPeriodEmployeeList.RamadanPeriodId IN 
							(SELECT RamadanPeriodId FROM D_RamadanPeriod WITH (NOLOCK)
							WHERE Convert(Date,S_Shifts.ActualEndTime) >= Convert(Date, D_RamadanPeriod.PeriodStart)
							And Convert(Date,S_Shifts.ActualEndTime) <= Convert(date, D_RamadanPeriod.PeriodEnd))
			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
							AND D_RamadanPeriodEmployeeList.RamadanPeriodId IN 
							(SELECT RamadanPeriodId FROM D_RamadanPeriod WITH (NOLOCK)
							WHERE Convert(Date,S_Shifts.ActualEndTime) >= Convert(Date, D_RamadanPeriod.PeriodStart)
							And Convert(Date,S_Shifts.ActualEndTime) <= Convert(date, D_RamadanPeriod.PeriodEnd))
	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_GetShiftsByShiftTrimming')
	DROP PROC prTA_GetShiftsByShiftTrimming
GO


CREATE PROC prTA_GetShiftsByShiftTrimming
(
	@EmployeeNumber			nVarchar(100),
	@OUId					BigInt,
	@ShiftBands			    nVarchar(100),
	@Skills           	    nVarchar(100),
    @ShiftDate			DateTime,
    @EmploymentBasis     	nVarchar(100),
	@Roles                  nVarchar(100),
	@Equipments             nVarchar(100),
	@EquipmentTypeId        BigInt
)
AS
BEGIN

	-- Retrieve First And Last Activity By Shift Id
	SELECT ActivityId, StartTime, EndTime, ShiftId, EquipmentName, Min(RowNumber) FirstRowNumber, Max(TotalRowsCount) LastRowNumber, EquipmentType, EquipmentId
	FROM (
		SELECT J_Activity.ActivityId, J_Activity.StartTime, J_Activity.EndTime, S_Shifts.ShiftId,
		IIF(CraneWorkLoad.CraneScheduleId != 0, 0, Equipments.EquipmentTypeId) EquipmentType,
		IIF(CraneWorkLoad.CraneScheduleId != 0, Cranes.CraneId, Equipments.EquipmentId) EquipmentId,
		IIF(CraneWorkLoad.CraneScheduleId != 0, Cranes.CraneNumber, Equipments.EquipmentName) EquipmentName,
		--CASE CraneWorkLoad.CraneScheduleId WHEN CraneWorkLoad.CraneScheduleId != 0 THEN M_Cranes.CraneNumber ELSE Equipments.EquipmentName END EquipmentName,
		ROW_NUMBEr() OVER(PARTITION BY J_Activity.ShiftId ORDER BY J_Activity.StartTime ASC) as RowNumber,
		COUNT(*) over (PARTITION BY J_Activity.ShiftId) as TotalRowsCount
		FROM J_Activity WITH (NOLOCK)
		INNER JOIN S_SHifts WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId
		INNER JOIN J_Workload CraneWorkLoad WITH (NOLOCK) ON CraneWorkLoad.WorkloadId = J_Activity.WorkloadId
		LEFT OUTER JOIN M_CraneSchedule WITH (NOLOCK) ON CraneWorkLoad.CraneScheduleId = M_CraneSchedule.CraneScheduleId
		LEFT OUTER JOIN M_Cranes Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = Cranes.CraneId
		INNER JOIN J_Workload EquipmentWorkLoad WITH (NOLOCK) ON EquipmentWorkLoad.WorkloadId = J_Activity.WorkloadId
		LEFT OUTER JOIN M_EquipmentSchedule WITH (NOLOCK) ON M_EquipmentSchedule.EquipmentScheduleId = EquipmentWorkLoad.EquipmentScheduleId
		LEFT OUTER JOIN M_Equipments Equipments WITH (NOLOCK) ON Equipments.EquipmentId = M_EquipmentSchedule.EquipmentId
		WHERE Convert(Date,S_Shifts.ActualStartTime) = Convert(Date,@ShiftDate)
		AND (S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '0')
		AND (S_Shifts.OUId = @OUId OR @OUId = 0)
	) Activities
	WHERE RowNumber = 1 or RowNumber = TotalRowsCount
	GROUP BY ActivityId, StartTime, EndTime, ShiftId, EquipmentName, EquipmentType, EquipmentId

	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.ActualStartTime,
			S_Shifts.ActualEndTime, 
			DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftStartTime,
			DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime)) ShiftEndTime,
			ShiftStartTime ActualShiftStartTime,
			ShiftEndTime ActualShiftEndTime,
			OTStartTime,
			OTEndTime
	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_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = C_Employee.EmployeeId
	Where  	(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands))  OR @ShiftBands = '0')
    AND		Convert(Date,ShiftStartTime)	=	Convert(Date,@ShiftDate)
	AND     (C_Employee.EmploymentBasisId IN (SELECT * FROM fnStringToTable(@EmploymentBasis))  OR @EmploymentBasis = '0')
	AND     (S_Shifts.RoleId IN (SELECT * FROM fnStringToTable(@Roles))  OR @Roles = '0')
    AND		(C_Employee.EmployeeNumber LIKE ('%' + @EmployeeNumber + '%') 
	OR		 C_Employee.DisplayName LIKE ('%' + @EmployeeNumber + '%') )
	AND     (C_EmployeeSkills.SkillID IN (SELECT * FROM fnStringToTable(@Skills))  OR @Skills = '0')
	AND     C_EmployeeSkills.IsPrimary = 1

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 WITH (NOLOCK)
		WHERE	Convert(Date, EndDate)		>= Convert(Date,@StartDate)
		AND		Convert(Date, StartDate)	<= Convert(Date,@EndDate)
		AND		OUID = @OUId 
	) 
	SELECT	--DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftActualStart, 
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ShiftActualEnd, 
			--DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ActualStartTime,
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ActualEndTime,
			S_Shifts.ActualStartTime ActualStartTime, 
			S_Shifts.ActualEndTime ActualEndTime, 
			S_Shifts.ActualStartTime ShiftActualStart, 
			S_Shifts.ActualEndTime ShiftActualEnd, 
			DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftStartTime,
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ShiftEndTime,
			DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime)) 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,DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate, DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftOutEarly, DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) ReconShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) ReconShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftInEarly,DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconGranularShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate, DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconGranularShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftOutEarly, DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) ReconGranularShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate, DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) ReconGranularShiftOutLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftInEarly,DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconToPlanShiftInEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime)) ReconToPlanShiftInLate,
			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftOutEarly,DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) ReconToPlanShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime)) 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
							AND D_RamadanPeriodEmployeeList.RamadanPeriodId IN 
							(SELECT RamadanPeriodId FROM D_RamadanPeriod WITH (NOLOCK)
							WHERE Convert(Date,S_Shifts.ActualEndTime) >= Convert(Date, D_RamadanPeriod.PeriodStart)
							And Convert(Date,S_Shifts.ActualEndTime) <= Convert(date, D_RamadanPeriod.PeriodEnd))
			LEFT OUTER JOIN P_OvertimeSettings WITH (NOLOCK) ON P_OvertimeSettings.OvertimeId = C_Employee.OvertimeId
	WHERE	Convert(Date,ActualStartTime) >= (SELECT StartDate From SchedulePeriodDates)
	AND		Convert(Date,ActualStartTime) <= (SELECT EndDate From SchedulePeriodDates)
	AND		(S_Shifts.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND		S_SHifts.EmployeeId IN (SELECT * FROM fnStringToTable(@EmployeeIds))	
	AND		S_Shifts.Reconciled = 1
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),
	@ReconStatusId			Int = NULL--,
	--@ClockingId				BigInt OUTPUT
)
AS
DECLARE @ValidateDuplicate int = 0
DECLARE @GranularityEarlyINMin int = 0,@GranularityLateOutMin int = 0
BEGIN

	SELECT	@ValidateDuplicate =  COUNT(*)
	FROM	TA_Rawclocking WITH (NOLOCK)
	WHERE	TypeId = @TypeId and EmployeeId=@EmployeeId and SwipeDateTime = @SwipeDateTime

	SELECT 	@GranularityEarlyINMin = TA_RPGConfig.ReconGranularShiftInEarly,
			@GranularityLateOutMin = TA_RPGConfig.ReconGranularShiftOutLate
	FROM	TA_RPGConfig  WITH (NOLOCK)
			INNER JOIN TA_RPGRoles WITH (NOLOCK) ON TA_RPGConfig.RPGId = TA_RPGRoles.RPGId 
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.RoleId = TA_RPGRoles.RoleId 
			INNER JOIN TA_RPGOU WITH (NOLOCK) ON TA_RPGOU.RPGId = TA_RPGConfig.RPGId AND S_Shifts.OUId = TA_RPGOU.OUId
	WHERE	S_Shifts.ShiftId = @ShiftId

	If (@ValidateDuplicate = 0)
	BEGIN
		SELECT	@EmployeeNo =  EmployeeNumber
		FROM	C_Employee WITH (NOLOCK)
		WHERE	EmployeeId  =@EmployeeId 

		If (@ShiftId != 0)
		BEGIN
			UPDATE	S_Shifts 
			SET		ReconTime = Null,
					Reconciled = 0,
					ReconStatusId = @ReconStatusId, --null,
					ReconFailureReasonId = NULL,
					ReconFailureReasonDetail= NULL,
					--RPGId = null,
					InStatus = null,
					OutStatus = null,
					--InTime = null,
					--OutTime = null,
					--ActualStartTime = ShiftStartTime,
					--ActualEndTime = IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime),
					ActualStartTime =  IIF(DATEDIFF(minute,0,ShiftStartTime) % @GranularityEarlyINMin > 0, 
										DATEADD(minute,(@GranularityEarlyINMin- DATEDIFF(minute,0,ShiftStartTime) % @GranularityEarlyINMin),ShiftStartTime),ShiftStartTime),
					ActualEndTime = IIF(OTEndTime > ShiftEndTime,  IIF(DATEDIFF(minute,0,OTEndTime) % @GranularityLateOutMin > 0, 
										DATEADD(minute,(@GranularityLateOutMin- DATEDIFF(minute,0,OTEndTime) % @GranularityLateOutMin),OTEndTime),OTEndTime),
										IIF(DATEDIFF(minute,0,ShiftEndTime) % @GranularityLateOutMin > 0, 
										DATEADD(minute,(@GranularityLateOutMin- DATEDIFF(minute,0,ShiftEndTime) % @GranularityLateOutMin),ShiftEndTime),ShiftEndTime)),
				
					--ActualStartTime = @ShiftBandStartDateTime,
					--ActualEndTime = @ShiftBandEndDateTime,
					UpdatedBy	=	@ReconBy
			WHERE ShiftId = @ShiftId 
		END
		--EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, @ReconBy, @ReconStatusId
		--UPDATE S_Shifts SET Reconciled = 0, ActualStartTime = ShiftStartTime, ActualEndTime = ShiftEndTime Where ShiftId = @ShiftId
		--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

		INSERT INTO TA_Rawclocking
		(TypeId, CardNo, TerminalName, SwipeDateTime, EmployeeNo, EmployeeId, CollectionDateTime, Allocated, ReconDate, ReconBy, CreatedBy, CreatedDate)
		VALUES( @TypeId, @CardNo, @TerminalName, @SwipeDateTime, @EmployeeNo, @EmployeeId, GETDATE(), 0, @ReconDate,@ReconBy ,@CreatedBy,GETDATE() )

		SELECT  CAST(@@Identity AS BigInt)  
	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,
	@ReconStatusId				Int = NULL
)
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		Allocated		=	0
	WHERE	SwipeDateTime	>=	@ShiftBandStartDateTime 
	AND		SwipeDateTime	<=	@ShiftBandEndDateTime
	AND		TypeId			=	@TypeId
	AND		EmployeeId		=	@EmployeeId

	UPDATE	TA_Rawclocking
	SET		TypeId				=	@TypeId,
			CardNo				=	@CardNo,
			TerminalName		=	@TerminalName,
			SwipeDateTime		=	SwipeDateTime,
			Allocated			=	@Allocated,
			ReconBy				=	NULL,
			ReconDate			=	NULL
	WHERE	ClockingId			=	@ClockingId

	--If (@ShiftId != 0) EXEC prS_UpdateShiftReconStatusByShiftId @ShiftId, 'Manual Raw Clocking Update', @ReconStatusId
	--UPDATE S_Shifts SET Reconciled = 0 Where ShiftId = @ShiftId
	UPDATE	S_Shifts 
	SET		ReconTime = Null,
			Reconciled = 0,
			ReconStatusId = @ReconStatusId, --null,
			ReconFailureReasonId = NULL,
			ReconFailureReasonDetail= NULL,
			RPGId = null,
			InStatus = null,
			OutStatus = null,
			InTime = null,
			OutTime = null,
			ActualStartTime = ShiftStartTime,
			ActualEndTime = ShiftEndTime,
			UpdatedBy	=	'Manual Raw Clocking Update'
	WHERE ShiftId = @ShiftId 

	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,
			D_ExceptionCodes.ExcpetionCodeName ExceptionCodeName,
			D_ExceptionCodes.ColorCode ExceptionColor
	FROM	S_ShiftExceptions WITH (NOLOCK) 
			INNER JOIN S_Shifts WITH (NOLOCK) ON S_ShiftExceptions.ShiftId = S_Shifts.ShiftId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK) ON D_ExceptionCodes.ExceptionCodeId = S_ShiftExceptions.ExceptionCodeId
	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 WITH (NOLOCK)
	WHERE	ParamName	= 'ReconProcessBufferMinutes'

	
	SELECT	--DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftActualStart, 
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ShiftActualEnd, 
			--DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ActualStartTime,
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ActualEndTime,
			S_Shifts.ActualStartTime ActualStartTime, 
			S_Shifts.ActualEndTime ActualEndTime, 
			S_Shifts.ActualStartTime ShiftActualStart, 
			S_Shifts.ActualEndTime ShiftActualEnd,
			DATEADD(MINUTE, -S_Shifts.PreparationMins, S_Shifts.ShiftStartTime) ShiftStartTime,
			--DATEADD(MINUTE, S_Shifts.DepreparationMins, S_Shifts.ShiftEndTime) ShiftEndTime,
			DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime)) 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,DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconShiftInEarly,

			DATEADD(MINUTE,TA_RPGConfig.ReconShiftInLate, DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconShiftInLate,

			DATEADD(MINUTE,-TA_RPGConfig.ReconShiftOutEarly, DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconShiftOutEarly,

			DATEADD(MINUTE,TA_RPGConfig.ReconShiftOutLate, DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconShiftOutLate,

			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftInEarly,DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconGranularShiftInEarly,

			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftInLate, DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconGranularShiftInLate,

			DATEADD(MINUTE,-TA_RPGConfig.ReconGranularShiftOutEarly, DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconGranularShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconGranularShiftOutLate, DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconGranularShiftOutLate,

			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftInEarly,DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconToPlanShiftInEarly,

			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftInLate,DATEADD(MINUTE, -S_Shifts.PreparationMins, IIF(DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly > 0, 
						DATEADD(minute,(TA_RPGConfig.ReconGranularShiftInEarly- DATEDIFF(minute,0,ShiftStartTime) % TA_RPGConfig.ReconGranularShiftInEarly),ShiftStartTime),ShiftStartTime))) ReconToPlanShiftInLate,

			DATEADD(MINUTE,-TA_RPGConfig.ReconToPlanShiftOutEarly,DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconToPlanShiftOutEarly,
			DATEADD(MINUTE,TA_RPGConfig.ReconToPlanShiftOutLate,DATEADD(MINUTE, S_Shifts.DepreparationMins, IIF(OTEndTime > ShiftEndTime,OTEndTime,ShiftEndTime))) ReconToPlanShiftOutLate,
			TA_RPGConfig.ReconGranularShiftInEarly GranularityInEarlyMin,
			TA_RPGConfig.ReconGranularShiftInLate GranularityInLateMin,
			TA_RPGConfig.ReconGranularShiftOutEarly GranularityOutEarlyMin,
			TA_RPGConfig.ReconGranularShiftOutLate GranularityOutLateMin,
			C_Employee.OvertimeId, IsNull(Convert(float,C_Employee.HourlyRate),0) 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
							AND D_RamadanPeriodEmployeeList.RamadanPeriodId IN 
							(SELECT RamadanPeriodId FROM D_RamadanPeriod WITH (NOLOCK)
							WHERE Convert(Date,S_Shifts.ActualEndTime) >= Convert(Date, D_RamadanPeriod.PeriodStart)
							And Convert(Date,S_Shifts.ActualEndTime) <= Convert(date, D_RamadanPeriod.PeriodEnd))
			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,
			--ActualEndTime				=	@OutTime,	
			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

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

CREATE PROC prTA_UpdateShiftStartEndTime
( 
	@ShiftStartTime				datetime,
	@ShiftEndTime				datetime,
	@ActualShiftStartTime		DateTime,
	@ActualShiftEndTime			DateTime,
	@ActualStartTime			datetime,
	@ActualEndTime				datetime,
	@OTStartTime				datetime,
	@OTEndTime					datetime,
	@ShiftId					bigint,
	@Remarks					nvarchar(50),
	@FirstActivityId			bigint,
	@LastActivityId				bigInt,
	@FirstActivityStartTime		datetime = NULL,
	@LastActivityEndTime		datetime = NULL,
	@ShiftTrimStartOrEndUpdated	int,
	@UpdateActivityTime			bit
)
AS
BEGIN
   UPDATE S_Shifts
   SET    ShiftStartTime	=	@ActualShiftStartTime,
          ShiftEndTime		=	@ActualShiftEndTime,
		  ActualStartTime	=	@ActualStartTime,
		  ActualEndTime		=	@ActualEndTime,
		  OTStartTime		=	@OTStartTime,
		  OTEndTime			=	@OTEndTime,
		  ReconTime			=	NULL,
		  Reconciled		=	0,
		  ReconStatusId		=	NULL,
		  Remarks			=	@Remarks
   WHERE  ShiftId			=	@ShiftId

   If ((@FirstActivityStartTime IS NOT NULL AND @LastActivityEndTime IS NOT NULL) AND @UpdateActivityTime = 1)
   BEGIN
	   IF(@ShiftTrimStartOrEndUpdated = 1)
	   BEGIN
		 UPDATE J_Activity
		 SET    StartTime	=	@FirstActivityStartTime
		 WHERE  ActivityId	=	@FirstActivityId
	   END
	   ELSE
	   BEGIN

		DELETE	FROM J_Activity 
		WHERE	ShiftId = @ShiftId
		AND		StartTime > @LastActivityEndTime

		 UPDATE J_Activity
		 SET    EndTime		=	@LastActivityEndTime
		 WHERE	ActivityId  = (SELECT Top 1 ActivityId  FROM	J_Activity WITH (NOLOCK) WHERE	ShiftId = @ShiftId ORDER BY StartTime DESC)
	   END
	END
   Select 1
END
GO

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

CREATE PROCEDURE prTT_UpdateLastShiftLiveRankFromInitialRankData
(
	@ShiftDate		DateTime
)
AS
BEGIN	
	DECLARE	@EmployeeId	BigInt = 0, @LiveRank nVarchar(2), @ShiftId BigInt = 0
	
	-- Create a cursor to retrieve data from TT_EmployeeInitialLiveRank
	DECLARE employeeLiveRankCursor CURSOR FOR
	SELECT	EmployeeId, RBRRank 
	FROM	TT_EmployeeInitialLiveRank
	--WHERE	EmployeeId =481

	-- Open Live Ranking Cursor
	OPEN employeeLiveRankCursor

	-- Fetch Data From Cursor
	FETCH NEXT FROM employeeLiveRankCursor INTO @EmployeeId, @LiveRank

	-- Loop through the data available in cursor
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @ShiftId = 0

		-- Retrieve Last Shift Of Employee By Employee Id And Shift Date 
		;WITH LastRbrRankByEmployee as 
		(
			SELECT	EmployeeId,  RBRRank, ShiftId,
					ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY ActualStartTime DESC) as RowNumber
			FROM	S_Shifts WITH (NOLOCK) 
			WHERE	Convert(Date,ActualStartTime) <= Convert(Date,@ShiftDate)
			--AND		EmployeeId =481
			AND		(S_Shifts.EmployeeId = @EmployeeId OR @EmployeeId = 0)
		)
		SELECT	@ShiftId = ShiftId
		FROM	LastRbrRankByEmployee
		WHERE	RowNumber = 1

		UPDATE	S_Shifts SET RBRRank = @LiveRank WHERE ShiftId = @ShiftId

		FETCH NEXT FROM employeeLiveRankCursor INTO @EmployeeId, @LiveRank
	END

	CLOSE employeeLiveRankCursor
	DEALLOCATE employeeLiveRankCursor
END
GO

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

CREATE PROCEDURE prTT_UpdateShiftsLiveRankFromInitialRankData
(
	@StartDate		DateTime
)
AS
BEGIN	
	DECLARE	@EmployeeId	BigInt = 0, @LiveRank nVarchar(2), @ShiftId BigInt = 0, @SkillRanking nVarchar(max), @CurrentRankInt int  = 64, @CurrentRankString nVarchar(2)
	
	-- Create a cursor to retrieve data from TT_EmployeeInitialLiveRank
	DECLARE employeeLiveRankCursor CURSOR FOR
	SELECT	TT_EmployeeInitialLiveRank.EmployeeId, ASCII(RBRRank) + 1, D_Skill.FixedRanking
	FROM	TT_EmployeeInitialLiveRank WITH (NOLOCK) 
			INNER JOIN C_EmployeeSkills WITH (NOLOCK) ON C_EmployeeSkills.EmployeeId = TT_EmployeeInitialLiveRank.EmployeeId
			INNER JOIN D_Skill WITH (NOLOCK) ON D_Skill.SkillId = C_EmployeeSkills.SkillId
	WHERE	D_Skill.FixedRanking IS NOT NULL
	--AND	TT_EmployeeInitialLiveRank.EmployeeId IN(481,693) 
	
	-- Open Live Ranking Cursor
	OPEN employeeLiveRankCursor

	-- Fetch Data From Cursor
	FETCH NEXT FROM employeeLiveRankCursor INTO @EmployeeId, @CurrentRankInt, @SkillRanking

	-- Loop through the data available in cursor
	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @ShiftId = 0;
		-- Retrieve All Shifts From > Given Date
		DECLARE empShiftsCur CURSOR FOR 
		SELECT	ShiftId 
		FROM	S_Shifts WITH (NOLOCK) 
		WHERE	Convert(Date,ActualStartTime) > Convert(Date,@StartDate)
		AND	 EmployeeId = @EmployeeId
		ORDER	BY Convert(Date,ActualStartTime)

		-- Open Shifts Cursor
		OPEN empShiftsCur

		-- Fetch Shifts
		FETCH NEXT FROM empShiftsCur INTO @ShiftId
		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF(CHARINDEX(CHAR(@CurrentRankInt),@SkillRanking) > 0) 
			BEGIN 
				SET @CurrentRankString = CHAR(@CurrentRankInt)
				Print @CurrentRankString + ' IN IF ' + Convert(nVarchar(2),@CurrentRankInt)
				SET @CurrentRankInt = @CurrentRankInt + 1
			END
			ELSE
			BEGIN
				SET @CurrentRankString = CHAR(65)
				SET @CurrentRankInt = 66
				Print @CurrentRankString + ' IN ELSE ' + Convert(nVarchar(2),@CurrentRankInt)
			END
			PRINT 'Shift ID ' + COnvert(NVarchar(50),@ShiftId)

			UPDATE S_Shifts SET RBRRank = @CurrentRankString WHERE ShiftId = @ShiftId

			FETCH NEXT FROM empShiftsCur INTO @ShiftId
		END
		CLOSE empShiftsCur
		DEALLOCATE empShiftsCur			
	
		FETCH NEXT FROM employeeLiveRankCursor INTO @EmployeeId, @CurrentRankInt, @SkillRanking
		SET @CurrentRankString = CHAR(@CurrentRankInt)
	END

	CLOSE employeeLiveRankCursor
	DEALLOCATE employeeLiveRankCursor
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_BackgroundProcessList]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_BackgroundProcessList]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[prT_BackgroundProcessList]   
(
	@BackgroundProcessId	 bigInt 
	
)
AS
BEGIN	 
	SELECT  	T_BackendProcessList.BackendProcessId,
			    T_BackendProcessList.Name	, 
				T_BackendProcessList.Type,
				T_BackendProcessList. ModuleName,
				T_BackendProcessList.Method, 
				T_BackendProcessList.Remarks ,				 
				T_BackendProcessList.FileFormat ,
				T_BackendProcessList.ActiveStatus 
	    FROM	T_BackendProcessList WITH (NOLOCK)		 
	WHERE	(BackendProcessId = @BackgroundProcessId OR @BackgroundProcessId = 0)
	 
	Order By T_BackendProcessList.Name
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,
				-- Added for schedule Perform Type E10-357
				T_SystemTaskSchedule.DayOfMonth,
				T_SystemTaskSchedule.Month,
				T_SystemTaskSchedule.WeekType,
				T_SystemTaskSchedule.DayOfWeek
	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,
			T_SystemTask.BackendProcessId --Added backend Process id E10-358
	FROM	T_SystemTask WITH (NOLOCK)
	WHERE	T_SystemTask.ActiveStatus = 1
	AND		(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.ActiveStatus = 1
	AND			(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,
				T_SystemTask.BackendProcessId -- Added for System Task Type E10-357
	    FROM	T_SystemTask WITH (NOLOCK)		 
	WHERE	(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_SystemTaskIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_SystemTaskIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_SystemTaskIns] 
(
	@SystemTaskName	nvarchar(1000),	
	@SystemTaskTypeId bigint,	
	@InterfaceId	 bigint,
	@Description	nvarchar(2000),
	@ActiveStatus   bit,
	@BackendProcessId bigint,
	@CreatedBy		nVarchar(50)
)
AS


BEGIN
			insert into T_SystemTask(SystemTaskName,SystemTaskTypeId,InterfaceId,Description,ActiveStatus,CreatedBy,CreatedDate,UpdatedBy,
			UpdatedDate,BackendProcessId)
			values(@SystemTaskName,@SystemTaskTypeId,@InterfaceId,@Description,@ActiveStatus,@CreatedBy,GETDATE(),@CreatedBy,
			GETDATE(),@BackendProcessId)
	SELECT @@IDENTITY
END
	
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_SystemTaskUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_SystemTaskUpd]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_SystemTaskUpd] 
(
	@SystemTaskId	BigInt,
	@SystemTaskName	nvarchar(1000),	
	@SystemTaskTypeId bigint,	
	@InterfaceId	 bigint,
	@Description	nvarchar(2000),
	@ActiveStatus   bit,
	@BackendProcessId bigint,
	@UpdatedBy		nVarchar(50)
)
AS

BEGIN
		update T_SystemTask set SystemTaskName =@SystemTaskName,
								SystemTaskTypeId=@SystemTaskTypeId,
								InterfaceId=@InterfaceId,
								Description=@Description,
								ActiveStatus=@ActiveStatus,
								BackendProcessId=@BackendProcessId, 
								UpdatedBy=@UpdatedBy,
								UpdatedDate=GETDATE()
								where SystemTaskId=@SystemTaskId
		SELECT @SystemTaskId
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 bigint) 

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.ActiveStatus ,
				W_Modules.CreatedBy ,
				W_Modules.CreatedDate,
				IsNull(W_Modules.LeaveCodes,'') LeaveCodes
	    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 OR @RouteId = 0) order by RouteLevel asc
END
go
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'prW_WorkflowRouteDetailsUpd')
	DROP PROC prW_WorkflowRouteDetailsUpd
GO

----------------------------------------------------------------------------
-- Update a single record in M_ResourceSet
----------------------------------------------------------------------------
CREATE PROC prW_WorkflowRouteDetailsUpd
	@RouteId			BigInt,
	@EmployeeId			BigInt,
	@RouteDetId         BigInt,
	@RouteLevel         int,
	@ApprovalRequirement int
AS

Update W_WorkflowRouteDetails
  SET    RouteId  =  @RouteId,
         EmployeeId = @EmployeeId,
		 RouteLevel = @RouteLevel,
		 ApprovalRequirement = @ApprovalRequirement
  WHERE  RouteDetId = @RouteDetId

 Select @RouteDetId

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

--Update Active status  Resource Set
UPDATE M_ResourceSet
	   SET ActiveStatus = 0
WHERE  ResourceSetId = @ResourceSetId


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

----------------------------------------------------------------------------
-- GET Records FROM M_CraneConditionDetails 
----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[pr_GetCraneConditionDetails] (
@CraneConditionId Bigint ) as

BEGIN
	SELECT  M_CraneConditionDetails.CraneConditionId,M_CraneConditionDetails.CraneId,M_Cranes.CraneNumber,M_CraneConditionDetails.ConditionType,M_CraneConditionDetails.StartDate,
		    M_CraneConditionDetails.EndDate,M_CraneConditionDetails.Remarks,M_CraneConditionDetails.CreatedBy,
		    M_CraneConditionDetails.CreatedDate,M_CraneConditionDetails.UpdatedBy,M_CraneConditionDetails.UpdatedDate
	FROM    M_CraneConditionDetails 
	INNER JOIN  M_Cranes  on M_CraneConditionDetails.CraneId=M_Cranes.CraneId
	WHERE  (M_CraneConditionDetails.CraneConditionId=@CraneConditionId OR @CraneConditionId = 0)
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetCraneConditionDetailsByCraneId]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetCraneConditionDetailsByCraneId]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pr_GetCraneConditionDetailsByCraneId] (
@CraneId Bigint ) as

BEGIN
 select M_CraneConditionDetails.CraneConditionId,M_CraneConditionDetails.CraneId,M_Cranes.CraneNumber,M_CraneConditionDetails.ConditionType,M_CraneConditionDetails.StartDate,
 M_CraneConditionDetails.EndDate,M_CraneConditionDetails.Remarks,M_CraneConditionDetails.CreatedBy,
 M_CraneConditionDetails.CreatedDate,M_CraneConditionDetails.UpdatedBy,M_CraneConditionDetails.UpdatedDate
  from M_CraneConditionDetails inner join M_Cranes  on M_CraneConditionDetails.CraneId=M_Cranes.CraneId where M_CraneConditionDetails.CraneId=@CraneId
END
GO
IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetCraneConditionForTHPCounter')
	DROP PROCEDURE pr_GetCraneConditionForTHPCounter
GO

CREATE PROCEDURE pr_GetCraneConditionForTHPCounter
 (
	@StartTime	DateTime,
	@EndTime	DateTime,
	@OUId		BigInt
)
AS
BEGIN
	--Crane Condition Detail
	SELECT	M_CraneConditionDetails.CraneId, 
			M_CraneConditionDetails.ConditionType, 
			M_CraneConditionDetails.StartDate, 
			M_CraneConditionDetails.EndDate
	FROM	M_CraneConditiondetails WITH (NOLOCK)  
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneConditionDetails.CraneId
	WHERE	M_Cranes.OUId	=	 @OUId
	AND		Convert(DateTime,EndDate) >= Convert(DateTime, @StartTime)
	AND		Convert(DateTime,StartDate) <= Convert(DateTime,@EndTime)
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetEmployeeIncentive')
	DROP PROCEDURE pr_GetEmployeeIncentive
GO

CREATE PROC pr_GetEmployeeIncentive
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeNumber		nVarchar(max),
	@ShiftBands			nVarchar(500),  
	@Paycode			nVarchar(255),  
	@SkillId			nVarchar(255),  
	@ReliefBreakId		BigInt
)
AS
	-- Retrieve Shift Details

		Select distinct  S_Shifts.ShiftId,
				S_Shifts.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_Skill.Skill,
				D_ShiftBand.ShiftBandCode ShiftBand,
				CONVERT(Date,ShiftStartTime)ShiftDate,
				(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ApprovedHours)/60),2) + ':' + 
				RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ApprovedHours)%60),2)) Hours,
				D_PayCodes.PayCode,
				isnull(P_ShiftCosts.UpdatedBy,P_ShiftCosts.CreatedBy) ApprovedBy,
				isnull(P_ShiftCosts.UpdatedDate,P_ShiftCosts.CreatedDate) ApprovedDate
		FROM  S_Shifts
		INNER JOIN J_Activity  WITH (NOLOCK)  on S_Shifts.ShiftId = J_Activity.ShiftId
		INNER JOIN D_Skill  WITH (NOLOCK)  on D_Skill.SkillId =J_Activity.SkillId
		INNER JOIN C_Employee  WITH (NOLOCK)  on C_Employee.EmployeeId =S_Shifts.EmployeeId
		INNER JOIN D_ShiftBand  WITH (NOLOCK)  on D_ShiftBand.ShiftBandId=S_Shifts.ShiftBandId 
		INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
	    INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId 
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 
		AND  (C_Employee.EmployeeNumber LIKE (@EmployeeNumber)  OR C_Employee.DisplayName LIKE (@EmployeeNumber))  
		AND     J_Activity.SkillId !=@ReliefBreakId
		AND    (J_Activity.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBands)) OR @ShiftBands = '')  
		AND    (J_Activity.SkillId  IN (SELECT * FROM fnStringToTable(@SkillId)) OR @SkillId = '')  
		AND    (P_ShiftCosts.PayCodeId  IN (SELECT * FROM fnStringToTable(@Paycode)) OR @Paycode = '')  
		

	
GO

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

----------------------------------------------------------------------------
-- Get Records from L_EmployeeLieuDates Based on DateRange
----------------------------------------------------------------------------
CREATE PROC pr_GetEmployeeLieuDaysList

(
@EmployeeId	BigInt,
@StartDate		DateTime = NULL,
@EndDate		DateTime = NULL
)
 
AS

       SELECT	C_Employee.EmployeeId,  C_Employee.EmployeeNumber,C_Employee.DisplayName,C_OrganizationNode.OUName,L_EmployeeLieuDates.LieuDate,
				L_EmployeeLieuDates.Utilized,
				L_EmployeeLieuDates.CreatedBy,L_EmployeeLieuDates.CreatedDate,L_EmployeeLieuDates.UpdatedBy,L_EmployeeLieuDates.UpdatedDate 
	   FROM		L_EmployeeLieuDates WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON L_EmployeeLieuDates.EmployeeId = C_Employee.EmployeeId
				INNER JOIN C_OrganizationNode WITH (NOLOCK)  on C_Employee.OUId = C_OrganizationNode.OUId
       WHERE   (C_Employee.EmployeeId	=	 @EmployeeId OR @EmployeeId = 0)
	   AND		Convert(Date,L_EmployeeLieuDates.LieuDate) >= Convert(Date,@StartDate) 
	   AND		Convert(Date,L_EmployeeLieuDates.LieuDate) <= Convert(Date,@EndDate)
	   
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetEmployeePanelClinicsList')
	DROP PROC pr_GetEmployeePanelClinicsList
GO
----------------------------------------------------------------------------
-- Get Records from C_EmployeePanelClinics Based on DateRange
----------------------------------------------------------------------------
CREATE PROC pr_GetEmployeePanelClinicsList
(
@EmployeeId	BigInt,
@EffectiveFrom		DateTime = NULL,
@EffectiveTo		DateTime = NULL
)
 
AS
BEGIN
       SELECT	C_EmployeePanelClinics.EmployeePanelClinicId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				D_PanelClinics.PanelClinicCode,
				D_PanelClinics.PanelClinicName,
				D_PanelClinics.Address,
				C_EmployeePanelClinics.EffectiveFrom,
				C_EmployeePanelClinics.EffectiveTo 
	   FROM		C_EmployeePanelClinics WITH (NOLOCK)
				INNER JOIN C_Employee WITH (NOLOCK) ON C_EmployeePanelClinics.EmployeeId = C_Employee.EmployeeId
				INNER JOIN D_PanelClinics WITH (NOLOCK)  on D_PanelClinics.PanelClinicId = C_EmployeePanelClinics.PanelClinicId
       WHERE   (C_Employee.EmployeeId	=	 @EmployeeId OR @EmployeeId = @EmployeeId)
	   AND		(Convert(Date,C_EmployeePanelClinics.EffectiveFrom) >= Convert(Date,@EffectiveFrom) OR @EffectiveFrom = @EffectiveFrom)
	   AND		(Convert(Date,C_EmployeePanelClinics.EffectiveTo) <= Convert(Date,@EffectiveTo) OR @EffectiveTo =  @EffectiveTo)
END
GO	  

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetExportedDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetExportedDetails]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pr_GetExportedDetails] (
@StartDate Datetime,
@EndDate Datetime)as    	  

BEGIN
  select Distinct 'AnnualLeaveBalance' InterfaceType,ExportedDate,Exportedby from IE_LeaveBalance where IE_LeaveBalance.AsAtDate>=@StartDate and
  IE_LeaveBalance.AsAtDate<=@EndDate and InterfaceFlag=1
  union all
  select Distinct 'SickLeave' InterfaceType,ExportedDate,Exportedby from IE_LeaveTransactions where IE_LeaveTransactions.AsAtDate>=@StartDate and
  IE_LeaveTransactions.AsAtDate<=@EndDate and InterfaceFlag=1 and LeaveCode='SL'
  union all
  select Distinct 'UnpaidLeave' InterfaceType,ExportedDate,Exportedby from IE_LeaveTransactions where IE_LeaveTransactions.AsAtDate>=@StartDate and
  IE_LeaveTransactions.AsAtDate<=@EndDate and InterfaceFlag=1  and LeaveCode='UL'
  union all
  select Distinct 'Absent' InterfaceType,ExportedDate,Exportedby from IE_EmployeeAbsents where IE_EmployeeAbsents.AsAtDate>=@StartDate and
  IE_EmployeeAbsents.AsAtDate<=@EndDate and InterfaceFlag=1
  union all
  select Distinct 'OvertimeHours' InterfaceType,ExportedDate,Exportedby from IE_EmployeeOvertime where IE_EmployeeOvertime.AsAtDate>=@StartDate and
  IE_EmployeeOvertime.AsAtDate<=@EndDate and InterfaceFlag=1
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetFinalBookingReport')
	DROP PROCEDURE pr_GetFinalBookingReport
GO

CREATE PROC pr_GetFinalBookingReport
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeId			BigInt,
	@CraneConditionType Int,
	@OUId				BigInt,
	@SkillIds			nVarchar(500)
)
AS
	-- Retrieve Shift Details
	WITH ShiftDetails AS (
		SELECT	 S_Shifts.ShiftId, 
				J_Activity.StartTime BookingDate, 
				S_Shifts.EmployeeId, 
				J_Activity.RBRRank Ranks, 
				J_Activity.SkillId,
				ISNULL(S_SHifts.Notes,'') Notes,
				C_Employee.EmployeeNumber,	
				C_Employee.DisplayName EmployeeName, 
				M_CraneSchedule.CraneId,
				D_MasterCodes.CodeValue Priority,
				M_Cranes.CraneNumber,
				J_Activity.AllocationNo,
				J_Activity.GroupNo,
				ROW_NUMBER() OVER(PARTITION BY S_Shifts.ShiftId, J_Activity.AllocationNo ORDER BY J_Activity.StartTime) RowId 
		FROM	S_Shifts   WITH (NOLOCK) 
				INNER JOIN J_Activity WITH (NOLOCK) ON S_Shifts.Shiftid = J_Activity.ShiftId	
				INNER JOIN C_Employee  WITH (NOLOCK) ON S_Shifts.EmployeeId =C_Employee.EmployeeId
				INNER JOIN J_Workload  WITH (NOLOCK) ON J_Workload.WorkloadId = J_Activity.WorkloadId
				INNER JOIN M_CraneSchedule WITH (NOLOCK)  ON J_Workload.CraneScheduleId = M_CraneSchedule.CraneScheduleId
				INNER JOIN D_MasterCodes WITH (NOLOCK) ON D_MasterCodes.CodeId = M_CraneSchedule.CranePriorityId 
				INNER JOIN M_Cranes WITH (NOLOCK) ON M_CraneSchedule.CraneId = M_Cranes.CraneId
		WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
		AND		S_Shifts.ShiftEndTime	<=	@EndDate 
		AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId=0)
		AND		(J_Activity.SkillId		IN (SELECT * FROM fnStringToTable(@SkillIds)) OR @SkillIds = '0')
		AND		S_Shifts.OUId =	@OUId
	)
	SELECT * FROM ShiftDetails WITH (NOLOCK)  
	WHERE	RowId = 1
	--ORDER BY SkillId, GroupNo, Ranks

	--Crane Condition Detail
	SELECT	M_CraneConditionDetails.CraneId,	
			'YES' Jerk 
	FROM	M_CraneConditiondetails WITH (NOLOCK)  
			INNER JOIN M_Cranes WITH (NOLOCK) ON M_Cranes.CraneId = M_CraneConditionDetails.CraneId
	WHERE	M_Cranes.OUId	=	 @OUId
	AND		M_CraneConditionDetails.ConditionType = @CraneConditionType
	AND		COnvert(DateTime,EndDate) >= Convert(DateTime,@StartDate)
	AND		Convert(DateTIme,StartDate) <= Convert(DateTIme,@EndDate)
	--AND		(StartDate BETWEEN @StartDate AND @EndDate) 
	--OR		(EndDate BETWEEN @StartDate AND @EndDate) 

	--Over Time Details
	SELECT	S_Shifts.ShiftId,
			(RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)/60),2) + ':' + 
			 RIGHT('0' + CONVERT(VARCHAR,CONVERT(INT,P_ShiftCosts.ActualHour)%60),2)) OT 
	FROM	S_Shifts WITH (NOLOCK) 
			INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
			INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
	WHERE	S_Shifts.ShiftStartTime >=	@StartDate 
	AND		S_Shifts.ShiftEndTime	<=	@EndDate 
	AND		(S_Shifts.EmployeeId	=	@EmployeeId OR @EmployeeId = 0)

	-- Retrieve Skills For Fixed Ranking Grouping
	SELECT	D_Skill.SkillId, D_SKill.FixedRanking
	FROM	D_Skill WITH (NOLOCK) 
			INNER JOIN D_SkillOU WITH (NOLOCK) ON D_Skill.SkillId = D_SkillOU.SkillId
	WHERE	D_SkillOU.OUId	=	@OUId
	AND		D_Skill.FixedRanking IS NOT NULL
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetIE_ ExportFileConfig]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetIE_ ExportFileConfig]
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetIE_ExportFileConfig]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetIE_ExportFileConfig]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[pr_GetIE_ExportFileConfig]   
(
	@ConfigId	 BigInt,
	@FileId		 BigInt
)
AS
	BEGIN		
	SELECT		IE_ExportFileConfig.FileId,
				IE_ExportFileConfig.FileName,
				IE_ExportFileConfig.SortSequence,
				IE_ExportFileConfig.ColumnName,
				IE_ExportFileConfig.DefaultValue,
				IE_ExportFileConfig.DataType,
				IE_ExportFileConfig.JiViColumn,
				IE_ExportFileConfig.MappingData
	FROM		IE_ExportFileConfig WITH (NOLOCK)
	WHERE		IE_ExportFileConfig.FileId = @FileId
	AND			(IE_ExportFileConfig.ConfigId = @ConfigId OR @ConfigId = 0)
				
	
	END
go



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

----------------------------------------------------------------------------
-- Get All Records from L_LeaveBalanceDiscrepancy
----------------------------------------------------------------------------
CREATE PROC pr_GetLeaveBalanceDiscrepancyList
 (
	@EmployeeId	BigInt,
	@StartDate		DateTime = NULL,
	@EndDate		DateTime = NULL
)
AS
BEGIN
			SELECT     L_LeaveBalanceDiscrepancy.EmployeeLeaveProfileId,C_Employee.EmployeeId,  C_Employee.EmployeeNumber,C_Employee.DisplayName,
			           C_OrganizationNode.OUName,L_EmployeeLeaveProfiles.LeaveYear,
			           D_ExceptionCodes.ExceptionCodeDesc,L_LeaveBalanceDiscrepancy.UsedDaysFromMYERP,L_LeaveBalanceDiscrepancy.LMSBalanceDays,
			           L_LeaveBalanceDiscrepancy.MYERPBalanceDays,
			           L_LeaveBalanceDiscrepancy.CreatedBy,L_LeaveBalanceDiscrepancy.CreatedDate
			FROM       L_LeaveBalanceDiscrepancy      
			INNER JOIN L_EmployeeLeaveProfiles   WITH (NOLOCK)  on L_LeaveBalanceDiscrepancy.EmployeeLeaveProfileId = L_EmployeeLeaveProfiles.Empprofileid 
			INNER JOIN C_Employee WITH (NOLOCK)  on L_EmployeeLeaveProfiles.EmployeeId = C_Employee.EmployeeId
			INNER JOIN C_OrganizationNode WITH (NOLOCK)  on C_Employee.OUId = C_OrganizationNode.OUId
			INNER JOIN D_ExceptionCodes WITH (NOLOCK)  on L_EmployeeLeaveProfiles.ExceptionId = D_ExceptionCodes.ExceptionCodeId
			WHERE      (C_Employee.EmployeeId = @EmployeeId OR @EmployeeId =0)	
			AND		(Convert(Date,L_LeaveBalanceDiscrepancy.CreatedDate) >= Convert(Date,@StartDate)  OR @StartDate = @StartDate)
		    AND		(Convert(Date,L_LeaveBalanceDiscrepancy.CreatedDate) <= Convert(Date,@EndDate)	 OR @EndDate = @EndDate)
END			
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetLeaveTransactionDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetLeaveTransactionDetails]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pr_GetLeaveTransactionDetails] (
@StartDate			Date,
@EndDate			Date,
@TranType		int) as    	  

BEGIN
 
	Select * from V_LeaveTransactions With (NoLock) where LeaveDate>=@StartDate and LeaveDate<=@EndDate and ExceptionCodeId=@TranType
	union
	Select * from V_LeaveTransactions With (NoLock) where UpdatedDate>=@StartDate and UpdatedDate<=@EndDate and
	(LeaveDate between convert(datetime,@StartDate)-90 and convert(datetime,@StartDate)-1) and ExceptionCodeId=@TranType
	 
END
GO

IF EXISTS(SELECT * FROM sysobjects WHERE name = 'pr_GetPayoutReportDetails')
	DROP PROCEDURE pr_GetPayoutReportDetails
GO

CREATE PROC pr_GetPayoutReportDetails
 (
	@StartDate			DateTime,
	@EndDate			DateTime,
	@ReliefBreakId		BigInt,
	@SkillId			BigInt
)
AS
	SELECT 	S_Shifts.ShiftId,
			S_Shifts.EmployeeId,
			C_Employee.EmployeeNumber,
			J_Activity.StartTime,
			J_Activity.EndTime,
			M_CraneSchedule.CraneId,
			M_Cranes.CraneNumber
	FROM    J_Activity WITH (NOLOCK)
	INNER JOIN S_Shifts WITH (NOLOCK) on S_Shifts.ShiftId=J_Activity.ShiftId 
	INNER JOIN J_WorkLoad WITH (NOLOCK) on J_WorkLoad.WorkLoadId=J_Activity.WorkLoadId
	INNER JOIN M_CraneSchedule WITH (NOLOCK) on M_CraneSchedule.CraneScheduleId=J_WorkLoad.CraneScheduleId
	INNER JOIN M_Cranes WITH (NOLOCK) on M_Cranes.CraneId=M_CraneSchedule.CraneId
	INNER JOIN C_Employee WITH (NOLOCK) on C_Employee.EmployeeId = S_Shifts.EmployeeId
	WHERE S_Shifts.ShiftStartTime >=	@StartDate 
	AND	  S_Shifts.ShiftEndTime	<=	@EndDate  
	AND   J_Activity.SkillId !=@ReliefBreakId
	AND	  J_Activity.SkillId =@SkillId

	--Crane Payout Granularity
	SELECT  ParamValue GranularityValue from D_SystemParams 
	Where ParamName='CranePayoutGranularity'
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetPosInterfaceDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetPosInterfaceDetails]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pr_GetPosInterfaceDetails] as    	  

BEGIN
 select IE_PoS_Interfaces.InterfaceRunId, IE_PoS_Interfaces.ActionDate,IE_PoS_Interfaces.ActionBy, IE_PoS_Interfaces.StartDate,
 IE_PoS_Interfaces.EndDate,IE_PoS_Interfaces.InterfaceList,IE_PoS_Interfaces.HistoryStartDate,
 IE_PoS_Interfaces.HistoryEndDate,IE_PoS_Interfaces.InterfaceStatus from IE_PoS_Interfaces
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetPreviousSignOffDetails]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetPreviousSignOffDetails]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[pr_GetPreviousSignOffDetails] as    	  

BEGIN
 select Top 1 (Convert(varchar(10),IE_PoS_Interfaces.StartDate,103) +' to '+Convert(varchar,IE_PoS_Interfaces.EndDate,103))PreviousSignOffPeriod,
 (Convert(varchar(10),ActionDate,103)+' '+Convert(varchar(8),IE_PoS_Interfaces.ActionDate,14)) PreviousSignOffDate, ActionBy PreviousSignOffBy,(IE_PoS_Interfaces.EndDate+1)StartDate,(Eomonth(IE_PoS_Interfaces.EndDate+1))EndDate 
 from IE_PoS_Interfaces order by ActionDate Desc
END
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 sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetScheduleJobDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetScheduleJobDetail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[pr_GetScheduleJobDetail]   

AS
	BEGIN	 
	with HF_Hash as(
		SELECT   ROW_NUMBER() OVER(ORDER BY (SELECT 1)) id,[Key] TaskName,[Cron],   [LastExecution], [NextExecution],   [LastJobId]
		FROM   [HangFire].[Hash] 
		PIVOT
		(
			  Max( [HangFire].[Hash].[Value])
			   FOR [Field] IN ([Cron],   [LastExecution], [NextExecution],   [LastJobId])
		) AS P)
		select Id,HangFire.[Set].Value TaskName,Cron,
		CONVERT(datetime,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, DATEADD(S, CONVERT(int,LEFT(LastExecution, 10)), '1970-01-01')),DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) 
		LastExecution,
		CONVERT(datetime,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, DATEADD(S, CONVERT(int,LEFT(NextExecution, 10)), '1970-01-01')),DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) 
		NextExecution,LastJobId from HF_Hash WITH (NOLOCK)  inner join HangFire.[Set]  WITH (NOLOCK)
		on 'recurring-job:'+HangFire.[Set].Value =TaskName 
		union all
		select  id,JSON_VALUE (InvocationData,'$.Method')
		TaskName,'' Cron,null LastExecution,null NextExecution,id LastJobId from HangFire.[Job]
		where JSON_VALUE (InvocationData,'$.Type') is not null and StateName !='Succeeded'

	
	END
go

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

----------------------------------------------------------------------------
-- Display record pr_GetSlashedCranesList Based on Id And Date
----------------------------------------------------------------------------
CREATE PROC pr_GetSlashedCranesList
(
	@ShiftBandId	BigInt,
	@Date		    DateTime 
)
AS
BEGIN
       SELECT	J_SlashedCranes.ShiftDate, D_ShiftBand.ShiftBandName,D_Skill.Skill,J_SlashedCranes.Activitystart,J_SlashedCranes.ActivityEnd,
	            J_SlashedCranes.GroupNumber,M_Cranes.CraneNumber,J_SlashedCranes.IsSlashed,J_SlashedCranes.CreatedBy,J_slashedcranes.CreatedDate,
				J_SlashedCranes.UpdatedBy,J_SlashedCranes.UpdatedDate
	   FROM		J_SlashedCranes WITH (NOLOCK)
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON J_SlashedCranes.ShiftBandId = D_ShiftBand.ShiftBandId
				INNER JOIN D_Skill WITH (NOLOCK)  ON J_SlashedCranes.SkillId = D_Skill.SkillId
				INNER JOIN M_Cranes WITH (NOLOCK)  ON J_SlashedCranes.CraneId = M_Cranes.CraneId
       WHERE    J_SlashedCranes.ShiftBandId	=	 @ShiftBandId
	   AND		Convert(Date,J_SlashedCranes.ShiftDate) = Convert(Date,@Date) 
END
GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetSystemTaskLogByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetSystemTaskLogByID]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[pr_GetSystemTaskLogByID]   
(
	@SystemTaskId	 nvarchar(10) 
)
AS
	BEGIN	 
	SELECT		HangFire.[Job].Id JobId,
				HangFire.[Job].StateId,
				HangFire.[Job].StateName,
				HangFire.[Job].InvocationData,
				HangFire.[Job].Arguments,
				--CONVERT(datetime,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, HangFire.[Job].CreatedAt),DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) 
				--CreatedAt,
				--CONVERT(datetime,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, HangFire.[Job].ExpireAt),DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) 
				--ExpireAt  ,
				MAX(CASE When HangFire.[State].Name ='Enqueued' THEN HangFire.[State].CreatedAt ELSE NULL END) StartDate,
				MAX(CASE When HangFire.[State].Name ='Succeeded' THEN HangFire.[State].CreatedAt ELSE NULL END) EndDate
	FROM		HangFire.[Job] WITH (NOLOCK)
				INNER JOIN HangFire.[State] WITH (NOLOCK) ON  HangFire.[Job].Id = HangFire.[State].JobId
				AND HangFire.[State].Name IN ('Enqueued','Succeeded')
				WHERE JSON_VALUE (InvocationData,'$.Type') is  null and  SUBSTRING(LTRIM(Arguments),3, CHARINDEX ( ',' , Arguments )-4)=@SystemTaskId
	GROUP BY	HangFire.[Job].Id,
				HangFire.[Job].StateId,
				HangFire.[Job].StateName,
				HangFire.[Job].InvocationData,
				HangFire.[Job].Arguments
		

	END
go



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetSystemTaskLogDetailByID]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetSystemTaskLogDetailByID]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[pr_GetSystemTaskLogDetailByID]   
(
	@JobId	 BigInt 
)
AS
	BEGIN	 
			SELECT  HangFire.[State].Id,
				HangFire.[State].JobId,
				HangFire.[State].Name,
				HangFire.[State].Reason,
				--CONVERT(datetime,SWITCHOFFSET(CONVERT(DATETIMEOFFSET, HangFire.[State].CreatedAt),DATENAME(TZOFFSET, SYSDATETIMEOFFSET()))) 
				HangFire.[State].CreatedAt,
				HangFire.[State].Data
				From HangFire.[State]  WITH (NOLOCK)
				inner join HangFire.[Job] WITH (NOLOCK) on HangFire.[State].JobId =HangFire.[Job].Id 
				--where SUBSTRING(LTRIM( HangFire.[Job].Arguments),3, CHARINDEX ( ',' ,  HangFire.[Job].Arguments )-4)=@SystemTaskId
				where HangFire.[State].JobId =@JobId

	END
go



IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[pr_GetTimeAttendanceDetail]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[pr_GetTimeAttendanceDetail]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
Create PROCEDURE [dbo].[pr_GetTimeAttendanceDetail]   
(
	@StartDate			DateTime,
	@EndDate			DateTime,
	@EmployeeNumber		nVarchar(100),
	@AttendanceStatusId	int,
	@ReconStatusId		int,
	@EmploymentBasisId  Bigint,
	@ShiftBandId		nVarchar(100)
)
AS
	BEGIN	
	--Shift Details
	SELECT		S_Shifts.ShiftId,
				S_Shifts.EmployeeId,
				C_Employee.EmployeeNumber,
				C_Employee.DisplayName EmployeeName,
				C_OrganizationNode.OUName,
				S_Shifts.ShiftStartTime,
				S_Shifts.ShiftEndTime,
				D_ShiftBand.ShiftBandCode ShiftBand,
				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 C_OrganizationNode WITH (NOLOCK) ON C_OrganizationNode.OUId = S_Shifts.OUId
				INNER JOIN D_ShiftBand WITH (NOLOCK) ON S_Shifts.ShiftBandId = D_ShiftBand.ShiftBandId
	WHERE		CONVERT(DateTime,ShiftStartTime) >= @StartDate
	AND			CONVERT(DateTime,ShiftEndTime) <= @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.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND			(C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
	AND			(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')

	--Attendance Exception

	SELECT		S_Shifts.ShiftId,
				S_Shifts.EmployeeId,
				S_Shifts.ReconStatusId,
				TA_ExceptionCodes.TAException ExceptionCode,
				S_Shifts.ShiftStartTime
	FROM		S_Shifts WITH (NOLOCK)
				INNER JOIN TA_ExceptionCodes WITH (NOLOCK) ON S_Shifts.ReconStatusId = TA_ExceptionCodes.TAExceptionId
				INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
	WHERE		CONVERT(DateTime,ShiftStartTime) >= @StartDate
	AND			CONVERT(DateTime,ShiftEndTime) <= @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.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND			(C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
	AND			(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')

	--OT Detail

	SELECT		S_Shifts.ShiftId,
			    D_PayCodes.PayCodeId,
				D_PayCodes.PayCode,
				(CONVERT(decimal(18,2),P_ShiftCosts.ActualHour)/60) OTHrs,
				S_Shifts.EmployeeId,
				S_Shifts.ShiftStartTime
	FROM		S_Shifts WITH (NOLOCK) 
				INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
				INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 1 
				INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
	WHERE		CONVERT(DateTime,ShiftStartTime) >= @StartDate
	AND			CONVERT(DateTime,ShiftEndTime) <= @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.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND		    (C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
	AND			(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')

	--Leave Detail
	SELECT		D_ExceptionCodes.ExceptionCodeDesc LeaveType,
				L_Leaves.EmployeeId,
				L_Leaves.LeaveStart,
				L_Leaves.LeaveEnd,
				L_Leaves.NoOfDays,
				L_Leaves.ApprovedBy,
				L_Leaves.UpdatedDate LastUpdatedDate,
				S_Shifts.ShiftStartTime,
				S_Shifts.ShiftEndTime
	FROM		L_Leaves WITH (NOLOCK) 				
				INNER JOIN D_ExceptionCodes WITH (NOLOCK)  ON L_Leaves.ExceptionCodeId = D_ExceptionCodes.ExceptionCodeId
				INNER JOIN C_Employee WITH (NOLOCK) ON L_Leaves.EmployeeId = C_Employee.EmployeeId
				INNER JOIN S_Shifts WITH (NOLOCK) ON S_Shifts.EmployeeId =  C_Employee.EmployeeId AND CONVERT(date,S_Shifts.ShiftStartTime) = CONVERT(date,L_Leaves.LeaveStart)
	WHERE		Convert(Date,L_Leaves.LeaveEnd) >= Convert(Date,@StartDate)
	AND			Convert(Date,L_Leaves.LeaveStart) <= Convert(Date,@EndDate)
	AND			(C_Employee.EmployeeNumber LIKE('%' + @EmployeeNumber + '%') OR @EmployeeNumber =0)

	--Allowance Detail

	SELECT		S_Shifts.ShiftId,
			    D_PayCodes.PayCodeId,
				D_PayCodes.PayCode,
				(CONVERT(decimal(18,2),P_ShiftCosts.ActualHour)/60) AllowanceHrs,
				S_Shifts.EmployeeId,
				S_Shifts.ShiftStartTime,
				D_PayCodeType.PaycodeTypeId
	FROM		S_Shifts WITH (NOLOCK) 
				INNER JOIN	P_ShiftCosts WITH (NOLOCK) ON P_ShiftCosts.ShiftId = S_Shifts.ShiftId 
				INNER JOIN	D_PayCodes   WITH (NOLOCK) ON D_PayCodes.PayCodeId = P_ShiftCosts.PayCodeId AND D_PayCodes.IsEditable = 0 
				INNER JOIN C_Employee WITH (NOLOCK) ON S_Shifts.EmployeeId = C_Employee.EmployeeId
				INNER JOIN	D_PayGroup   WITH (NOLOCK) ON D_PayGroup.PayGroupId = C_Employee.PayGroupId
				INNER JOIN	D_PaygroupCodes   WITH (NOLOCK) ON D_PaygroupCodes.PayCodeId = D_PayCodes.PayCodeId  AND D_PayGroup.PayGroupId = D_PaygroupCodes.PayGroupId
				INNER JOIN	D_PayCodeType WITH (NOLOCK) ON D_PayCodeType.PaycodeTypeId = D_PaygroupCodes.PaycodeType AND D_PayCodeType.PayCodeTypevalue = 2
	WHERE		CONVERT(DateTime,ShiftStartTime) >= @StartDate
	AND			CONVERT(DateTime,ShiftEndTime) <= @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.ShiftBandId != CombinationShiftId OR CombinationShiftId IS NULL)
	AND		    (C_Employee.EmploymentBasisId = @EmploymentBasisId OR @EmploymentBasisId = 0)
	AND			(S_Shifts.ShiftBandId IN (SELECT * FROM fnStringToTable(@ShiftBandId)) OR @ShiftBandId = '0')


	END
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,
	@TypeId bigInt = NULL,
	@EquipmentTypeId bigInt = NULL
	
AS

UPDATE	M_ResourceSetDetails
SET	ResourceSetId = @ResourceSetId,
	SkillId = @SkillId,
	Requirement = @Requirement,
	LocationId = @LocationId,
	UpdatedBy = @UpdatedBy,
	UpdatedDate = GETDATE(),
	TypeId = @TypeId,
	EquipmentTypeId = @EquipmentTypeId
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 WITH (NOLOCK)
			INNER JOIN E_EqipmentMatrix_Schedule MatrixSchedule WITH (NOLOCK) ON E_EquipmentMatrix.MatrixId = MatrixSchedule.MatrixId
			INNER JOIN E_EquipmentMatrix_EquipmentType EquipmentType WITH (NOLOCK) ON E_EquipmentMatrix.MatrixId = EquipmentType.MatrixId 
			AND EquipmentType.MatrixScheduleId = MatrixSchedule.MatrixScheduleId
			INNER JOIN M_EquipmentType WITH (NOLOCK) ON M_EquipmentType.EquipmentTypeId = EquipmentType.EquipmentTypeId
	WHERE	E_EquipmentMatrix.MatrixId = @EquipmentMatrixTemplateId 
	AND		(MatrixSchedule.ScheduledValue = @CraneCount OR @CraneCount = 0)

END

GO

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_SystemTaskScheduleIns]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_SystemTaskScheduleIns]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_SystemTaskScheduleIns] 
(
	@SystemTaskId	BigInt,
	@TaskType bigint,	
	@TaskInterval	 bigint,
	@ScheduledTime	nvarchar(20),	
	@CronExpression   nvarchar(510),
	@StartDate datetime,
	@EndDate datetime,
	@DayOfMonth bigint,
	@Month bigint,
	@WeekType bigint,
	@DayOfWeek nvarchar(20),
	@CreatedBy		nVarchar(50)
)
AS


BEGIN
			insert into T_SystemTaskSchedule(SystemTaskId,TaskType,TaskInterval,ScheduledTime,CronExpression,StartDate,EndDate,CreatedBy,CreatedDate,UpdatedBy,
			UpdatedDate,DayOfMonth,Month,WeekType,DayOfWeek)
			values(@SystemTaskId,@TaskType,@TaskInterval,@ScheduledTime,@CronExpression,@StartDate,@EndDate,@CreatedBy,GETDATE(),@CreatedBy,
			GETDATE(),@DayOfMonth,@Month,@WeekType,@DayOfWeek)
	SELECT @@IDENTITY
END
	
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[prT_SystemTaskScheduleUpd]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[prT_SystemTaskScheduleUpd]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[prT_SystemTaskScheduleUpd] 
(
	@SystemTaskScheduleId Bigint,
	@SystemTaskId	BigInt,
	@TaskType bigint,	
	@TaskInterval	 bigint,
	@ScheduledTime	nvarchar(20),	
	@CronExpression   nvarchar(510),
	@StartDate datetime,
	@EndDate datetime,
	@DayOfMonth bigint,
	@Month bigint,
	@WeekType bigint,
	@DayOfWeek nvarchar(20),
	@UpdatedBy	nVarchar(50)
)
AS


BEGIN
		update T_SystemTaskSchedule set TaskType=@TaskType,
										TaskInterval=@TaskInterval,
										ScheduledTime=@ScheduledTime,
										CronExpression=@CronExpression,
										StartDate=@StartDate,
										EndDate=@EndDate,
										DayOfMonth=@DayOfMonth,
										Month=@Month,
										WeekType=@WeekType,
										DayOfWeek=@DayOfWeek,
										UpdatedBy=@UpdatedBy,
										UpdatedDate=GETDATE()
										where SystemTaskScheduleId=@SystemTaskScheduleId and SystemTaskId=@SystemTaskId
	SELECT @SystemTaskScheduleId
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
SET IDENTITY_INSERT [dbo].[C_Menu] ON 
GO
-- Insert Horizontal Menu Items

-- 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, 9, N'sidenav-icon fas fa-tachometer-alt', 1, N'System',GETDATE(), 0, 0, 1)
ELSE UPDATE C_Menu SET DisplayOrder = 9 Where MenuID = 108

-- Mobile Application Services
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 999)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(999, NULL, N'Mobile Services',NULL, 10, N'sidenav-icon fas fa-tachometer-alt', 1, N'System',GETDATE(), 0, 0, 1)
ELSE UPDATE C_Menu SET DisplayOrder = 10 Where MenuID = 999

-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 1 Where MenuID = 200
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 2 Where MenuID = 300
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 3 Where MenuID = 301


-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 4 Where MenuID = 201
	--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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 5 Where MenuID = 302

	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 6 Where MenuID = 303

	-- General Master
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuID = 423)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(423, 201, N'General Master',N'Setup/GeneralMaster', 6, N'', 1, N'System',GETDATE(), 14, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 6 Where MenuID = 423

	-- Acting Incentive Rates
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuID = 424)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(424, 201, N'Acting Incentive Rates',N'Definitions/ActingIncentiveRates', 6, N'', 1, N'System',GETDATE(), 14, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 6 Where MenuID = 424

	-- Screen Configuration
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuID = 452)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(452, 201, N'Screen Configuration',N'Planning/ScreenConfiguration', 7, N'', 1, N'System',GETDATE(), 15, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 7 Where MenuID = 452

	-- Password Policy
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuID = 464)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(464, 201, N'Password Policy',N'Definitions/PasswordPolicy', 8, N'', 1, N'System',GETDATE(), 15, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 8 Where MenuID = 464

	    -- Miscellaneous Columns
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuID = 472)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(472, 201, N'Miscellaneous Columns',N'Definitions/MiscellaneousColumns', 9, N'', 1, N'System',GETDATE(), 16, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 9 Where MenuID = 472

-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 7 Where MenuID = 202
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 8 Where MenuID = 304

	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 9 Where MenuID = 305
	    -- Added for Application Info screen E10-318
		-- Application Info
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 428)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(428, 202, N'Application Info',N'Process/ApplicationInfo', 10, N'', 1, N'System',GETDATE(), 18, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 10 Where MenuID = 428


-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 10 Where MenuID = 203
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 11 Where MenuID = 306
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 12 Where MenuID = 307
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 13 Where MenuID = 308
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 14 Where MenuID = 309
	-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 15 Where MenuID = 204
	-- 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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 16 Where MenuID = 310
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 17 Where MenuID = 311
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 18 Where MenuID = 312
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 19 Where MenuID = 313
	-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 20 Where MenuID = 205

	-- 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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 21 Where MenuID = 314
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 22 Where MenuID = 315
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 23 Where MenuID = 316
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 24 Where MenuID = 317
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 25 Where MenuID = 401

	-- 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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 26 Where MenuID = 414

	-- Messages Template [Notifications] (449)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 449)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(449, 205, N'Messages Setup', N'LeaveManagement/MessageSetup', 16, N'', 1, N'System',GETDATE(), 33, 0, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 27 Where MenuID = 449

	--Panel Clinic (465)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 465)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(465, 205, N'Panel Clinic Setup', N'LeaveManagement/PanelClinic',28, N'', 1, N'System',GETDATE(), 33, 0, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 28 Where MenuID = 465

		--Employee Panel Clinics (476)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 476)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(476, 205, N'Employee Panel Clinics', N'LeaveManagement/EmployeePanelClinics',28, N'', 1, N'System',GETDATE(), 33, 0, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 28 Where MenuID = 476
-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 27 Where MenuID = 206
	-- 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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 28 Where MenuID = 318
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 29 Where MenuID = 319
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 30 Where MenuID = 320
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 31 Where MenuID = 321
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 32 Where MenuID = 322
	-- /End Pay Group
	-- PayCode Types (471)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 471)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(471, 206, N'Paycode Types', N'Definitions/PayCodeType', 22, N'', 1, N'System',GETDATE(), 39, 0, 0)	
	
	-- /End Paycode Types

-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 33 Where MenuID = 207

	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 34 Where MenuID = 323
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 35 Where MenuID = 334
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 36 Where MenuID = 335
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 37 Where MenuID = 336
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 38 Where MenuID = 337
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 39 Where MenuID = 338
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 40 Where MenuID = 339
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 41 Where MenuID = 340
	--/ End Skill Requirement Matrix Template (340)

		-- Equipment Matrix Template Group (477)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 477)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(477, 207, N'Equipment Matrix Template Group', N'MariTime/EquipmentMatrixTemplateGroup', 30, N'', 1, N'System',GETDATE(), 47, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 41 Where MenuID = 477
	--/ Equipment Matrix Template Group (477)

		--Equipment Rotation Group (478)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 478)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(478, 207, N'Equipment Rotation Group', N'MariTime/EquipmentBrands', 30, N'', 1, N'System',GETDATE(), 47, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 41 Where MenuID = 478
	--/ End Equipment Brands (478)

-- /End Equipment Rotation Group

-- 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)			
ELSE UPDATE C_Menu SET DisplayOrder = 42 Where MenuID = 208
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 43 Where MenuID = 341
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 44 Where MenuID = 342
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 45 Where MenuID = 343
	-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 46 Where MenuID = 209
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 47 Where MenuID = 344
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 48 Where MenuID = 345
	-- /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-digital-tachograph', 1, N'System',GETDATE(), 54, 0, 0)			
ELSE UPDATE C_Menu SET MenuImage ='sidenav-icon fas fa-digital-tachograph', DisplayOrder = 49 WHere MenuID = 227

	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 50 Where MenuID = 407
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 51 Where MenuID = 408
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 52 Where MenuID = 409
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 53 Where MenuID = 418
	-- /End User Login Audit

	-- Employee Audit (421)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 421)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(421, 227, N'Employee Audit', N'Definitions/Audit/EmployeeAuditIndex', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 54 Where MenuID = 421
	-- /End Employee Period

	-- T&A Raw Clocking Audit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 425)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(425, 227, N'Raw Clocking Audit', N'Definitions/Audit/TARawClockingAuditIndex', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 54 Where MenuID = 425

	-- T&A Costing Audit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 426)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(426, 227, N'Costing Audit', N'Definitions/Audit/TACostingAuditIndex', 37, N'', 1, N'System',GETDATE(), 54, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 54 Where MenuID = 426

	-- Operation Audit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 466)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(466, 227, N'Operations Audit', N'Definitions/Audit/OperationAuditIndex', 56, N'', 1, N'System',GETDATE(), 54, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 54 Where MenuID = 466

	-- N4 Interface Audit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 451)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(451, 227, N'N4 Interface Audit', N'Definitions/Audit/N4InterfaceAuditIndex', 57, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 57 Where MenuID = 451

    --Log File Content
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 458)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(458, 227, N'LogFile Content', N'Definitions/LogFileContent', 58, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 458

	--Leave Balance Discrepancy
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 460)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(460, 227, N'Leave Balance Discrepancy',N'Definitions/Audit/LeaveBalanceDiscrepancyIndex', 58, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 460

	--Employee Lieu Days
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 461)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(461, 227, N'Employee Lieu Days',N'Definitions/Audit/EmployeeLieuDaysIndex', 58, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 461

	--Employee THP Details
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 475)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(475, 227, N'Employee THP Details',N'Definitions/Audit/EmployeeTHPDetailsIndex', 58, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 475

		--Employee Notifications
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 479)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(479, 227, N'Employee Notifications',N'Definitions/Audit/EmployeeNotificationsIndex', 58, N'', 1, N'System',GETDATE(), 57, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 479
--/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)			
ELSE UPDATE C_Menu SET DisplayOrder = 55 Where MenuID = 210
	-- 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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 56 Where MenuID = 346
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 57 Where MenuID = 347
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 58 Where MenuID = 348
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 59 Where MenuID = 349
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 60 Where MenuID = 397
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 61 Where MenuID = 399

	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 62 Where MenuID = 400
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 63 Where MenuID = 402
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 64 Where MenuID = 404
	-- /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)	
	ELSE UPDATE C_Menu SET DisplayOrder = 65 Where MenuID = 407
	-- /End Ramadan Period

	-- Employee Performance Rating (480)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 480)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(480, 210, N'Employee Performance Rating', N'Employee/PerformanceRating', 8, N'', 1, N'System',GETDATE(), 60, 0, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 60 Where MenuID = 480
	-- /End Employee Performance Rating

-- /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)	
ELSE UPDATE C_Menu SET DisplayOrder = 66 Where MenuID = 211
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 67 Where MenuID = 390

	-- 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)		
	ELSE UPDATE C_Menu SET DisplayOrder = 68 Where MenuID = 391
	
	--  Employee RBR Rank Audit
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 422)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(422, 211, N'Shift Live Rank', N'Scheduler/EmployeeRoster/EmployeeLiveRankListIndex', 3, N'', 1, N'System',GETDATE(), 63, 0, 0)
	ELSE UPDATE C_Menu SET MenuName ='Shift Live Rank', MenuLink = 'Scheduler/EmployeeRoster/EmployeeLiveRankListIndex', ParentMenuID = 211, DisplayOrder = 69 Where MenuID = 422

	--  Leave Entitlement Alert
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 450)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(450, 211, N'Leave Entitlement Alert', N'Scheduler/EmployeeLeave/LeaveEntitlementAlert', 4, N'', 1, N'System',GETDATE(), 64, 0, 0)
	ELSE UPDATE C_Menu SET MenuName ='Leave Entitlement Alert', MenuLink = 'Scheduler/EmployeeLeave/LeaveEntitlementAlert', DisplayOrder = 70 Where MenuID = 450

	--  Roster Export
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 459)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(459, 211, N'Roster Export', N'Scheduler/RosterExport', 71, N'', 1, N'System',GETDATE(), 71, 0, 0)
	ELSE UPDATE C_Menu SET MenuName ='Roster Export', MenuLink = 'Scheduler/RosterExport', DisplayOrder = 71 Where MenuID = 459

	--Employee Unavailability Report (463)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 463)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(463, 211, N'Employee Unavailability Report',N'Scheduler/EmployeeLeave/EmployeeUnavailabilityIndex', 2, N'', 1, N'System',GETDATE(), 62, 0, 0)		
	ELSE UPDATE C_Menu SET DisplayOrder = 68 Where MenuID = 463

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, 70, N'sidenav-icon fas fa-chalkboard-teacher', 1, N'System',GETDATE(), 63, 1, 0)			
ELSE UPDATE C_Menu SET DisplayOrder = 70 Where MenuID = 213
	-- 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', 71, N'', 1, N'System',GETDATE(), 64, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 71 Where MenuID = 350
	-- /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', 72, N'', 1, N'System',GETDATE(), 65, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 72 Where MenuID = 351
	-- /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', 73, N'', 1, N'System',GETDATE(), 66, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 73 Where MenuID = 352
	-- /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', 74, N'', 1, N'System',GETDATE(), 67, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 74 Where MenuID = 353
	-- /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', 75, N'', 1, N'System',GETDATE(), 68, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 75 Where MenuID = 354
	-- /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', 76, N'', 1, N'System',GETDATE(), 69, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 76 Where MenuID = 355
	-- /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', 77, N'', 1, N'System',GETDATE(), 70, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 77 Where MenuID = 356
	-- /End Apply on Behalf 

	-- Apply for Uncontrolled Leave (446)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 446)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(446, 213, N'Apply for Uncontrolled Leave',  N'SelfService/UncontrolledLeave/UncontrolledLeaveIndex', 102, N'', 1, N'System',GETDATE(), 102, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 102,MenuLink= N'SelfService/UncontrolledLeave/UncontrolledLeaveIndex' Where MenuID = 446
	-- /End Apply for Uncontrolled Leave

	---- Upload UCL Document (447)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 447)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(447, 213, N'Upload UCL Document',  N'SelfService/UncontrolledLeave/UploadUCLDocumentIndex', 103, N'', 1, N'System',GETDATE(), 103, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 103,MenuName= N'Upload UCL Document', MenuLink=N'SelfService/UncontrolledLeave/UploadUCLDocumentIndex' Where MenuID = 447
	-- /End Upload UCL Document (447)

		---- Manage UCL Upload Document (448)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 448)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(448, 213, N'Manage UCL Upload Document',  N'SelfService/UncontrolledLeave/ManageUCLDocumentIndex', 104, N'', 1, N'System',GETDATE(), 104, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 104 Where MenuID = 448
	-- /End  Manage UCL Upload Document (448)


-- /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, 78, N'sidenav-icon fas fa-calendar-check', 1, N'System',GETDATE(), 71, 1, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 78 Where MenuID = 214
	-- 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', 79, N'', 1, N'System',GETDATE(), 73, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 79 Where MenuID = 357
	-- /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', 80, N'', 1, N'System',GETDATE(), 73, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 80 Where MenuID = 358
	-- /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', 81, N'', 1, N'System',GETDATE(), 74, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 81 Where MenuID = 359
	-- /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', 82, N'', 1, N'System',GETDATE(), 70, 1, 0)		
	Else
		UPDATE	C_Menu SET MenuLink = N'Transactions/CancelApprovedLeaves', DisplayOrder = 82 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, 83, N'sidenav-icon fas fa-clinic-medical', 1, N'System',GETDATE(), 75, 1, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 83 Where MenuID = 215
	-- 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', 84, N'', 1, N'System',GETDATE(), 76, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 84 Where MenuID = 360
	-- /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', 85, N'', 1, N'System',GETDATE(), 77, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 85 Where MenuID = 405
	-- /End Sick/Injury Leave

-- /End Clinic Portal (215)

-- Mobile Application Menus [999]
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 900)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(900, 999, N'Mobile Application',NULL, 900, N'sidenav-icon fas fa-chalkboard-teacher', 1, N'System',GETDATE(), 900, 1, 0)			
ELSE UPDATE C_Menu SET DisplayOrder = 900 WHERE MenuID = 900 
	-- Add Menu Items For Mobile Application

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

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

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

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

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

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

	-- Apply on Behalf (356)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 907)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(907, 900, N'Apply on Behalf',  N'Approvers/ApplyOnBehalf', 907, N'', 1, N'System',GETDATE(), 907, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 907 Where MenuID = 907
	-- /End Apply on Behalf 
	-- Approve Time Off (357)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 908)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(908, 900, N'Approve Time Off',  N'SelfService/Transactions/PendingTimeOffIndex', 908, N'', 1, N'System',GETDATE(), 908, 1, 0)	
	ELSE UPDATE C_Menu SET DisplayOrder = 908 Where MenuID = 908
	-- /End Approve Time Off 

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

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

	-- Cancel Approved Leaves (356)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 911)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(911, 900, N'Cancel Approved Leaves',  N'Transactions/CancelApprovedLeaves', 911, N'', 1, N'System',GETDATE(), 911, 1, 0)		
	Else
		UPDATE	C_Menu SET MenuLink = N'Transactions/CancelApprovedLeaves', DisplayOrder = 911 Where MenuID = 911
	-- /End Cancel APproved Leaves

	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 10425)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(10425, 900, N'UnControlled Leave',  N'SelfService/ApplyLeave/UncontrolledLeaveIndex', 912, N'', 1, N'System',GETDATE(), 912, 1, 0)		
	Else
		UPDATE	C_Menu SET MenuLink = N'SelfService/ApplyLeave/UncontrolledLeaveIndex', DisplayOrder = 912 Where MenuID = 10425

		IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 10426)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(10426, 900, N'Upload Uncontrolled Leave',  N'SelfService/ApplyLeave/UploadUncontrolledLeaveDocumentIndex', 913, N'', 1, N'System',GETDATE(), 913, 1, 0)		
	Else
		UPDATE	C_Menu SET MenuLink = N'SelfService/ApplyLeave/UploadUncontrolledLeaveDocumentIndex', DisplayOrder = 913 Where MenuID = 10426
		
		IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 10427)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(10427, 900, N'Manage Uncontrolled Leave',  N'SelfService/ApplyLeave/ManageUncontrolledLeaveIndex', 914, N'', 1, N'System',GETDATE(), 914, 1, 0)		
	Else
		UPDATE	C_Menu SET MenuLink = N'SelfService/ApplyLeave/ManageUncontrolledLeaveIndex', DisplayOrder = 914 Where MenuID = 10427

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)			
ELSE UPDATE C_Menu SET DisplayOrder = 86 Where MenuID = 216
-- 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)	
ELSE UPDATE C_Menu SET DisplayOrder = 87 Where MenuID = 361
-- /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)
ELSE UPDATE C_Menu SET DisplayOrder = 88 Where MenuID = 362
-- /End Resource Set Definition (362)

-- Prime Mover Planning (435)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 435)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(435, 216, N'Prime Mover Planning', N'Planning/DailyPlanning/PrimeMoverPlanning', 89, N'', 1, N'System',GETDATE(), 80, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 89,MenuLink = N'Planning/DailyPlanning/PrimeMoverPlanning' Where MenuID = 435
-- /End  Prime Mover Planning  (435)

-- RTG Planning (437)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 437)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(437, 216, N'RTG Planning', N'Planning/DailyPlanning/RTGPlanning', 90, N'', 1, N'System',GETDATE(), 90, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 90,MenuLink = N'Planning/DailyPlanning/RTGPlanning' Where MenuID = 437
-- /End  RTG Planning  (437)

-- Stackers Planning (439)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 439)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(439, 216, N'Stackers Planning', N'Planning/DailyPlanning/StackersPlanning', 91, N'', 1, N'System',GETDATE(), 91, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 91,MenuLink = N'Planning/DailyPlanning/StackersPlanning' Where MenuID = 439
-- /End  Stackers Planning  (439)

-- HSSE Planning (441)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 441)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(441, 216, N'HSSE Planning', N'Planning/DailyPlanning/HSSEPlanning', 92, N'', 1, N'System',GETDATE(), 92, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 92,MenuLink = N'Planning/DailyPlanning/HSSEPlanning' Where MenuID = 441
-- /End  HSSE Planning  (441)

-- Lashing Deployment (443)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 443)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(443, 216, N'Lashing Deployment', N'Planning/DailyPlanning/LashingDeployment', 93, N'', 1, N'System',GETDATE(), 93, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 93,MenuLink = N'Planning/DailyPlanning/LashingDeployment' Where MenuID = 443
-- /End  HSSE Planning  (443)

-- Employee Projection (473)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 473)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(473, 216, N'Employee Projection', N'Planning/DailyPlanning/EmployeeProjection', 94, N'', 1, N'System',GETDATE(), 94, 0, 0)
ELSE UPDATE C_Menu SET DisplayOrder = 94,MenuLink = N'Planning/DailyPlanning/EmployeeProjection' Where MenuID = 473
-- /End Employee Projection  (473)

-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 89 Where MenuID = 217
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 90 Where MenuID = 363
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 91 Where MenuID = 413
	-- /End Operations Duty Manager (363)

	-- Execution/Acting Skills List (420)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 420)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(420, 217, N'Acting Skill List', N'Operations/Execution/ActingSkillListIndex', 15, N'', 0, N'System',GETDATE(), 92, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 92 Where MenuID = 420
	-- /End Execution/Acting Skills List (420)

	-- Attendance Monitor (423)
	IF NOT EXISTS (SELECT * FROM C_Menu WHERE MenuID = 427)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(427, 217, N'Attendance Monitor', N'Operations/DailyOperation/AttendanceMonitorIndex', 15, N'', 0, N'System',GETDATE(), 92, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 92 Where MenuID = 427

	IF NOT EXISTS (SELECT * FROM C_Menu WHERE MenuID = 467)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(467, 217, N'Shift Trimming', N'TimeAttendance/ShiftTrimming', 93, N'',1, N'System',GETDATE(), 92, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 93 Where MenuID = 467
	
	--Vessel Schedule E10-355
	IF NOT EXISTS (SELECT * FROM C_Menu WHERE MenuID = 920)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(920, 217, N'Execution - Vessel Schedule', N'Operations/Execution', 94, N'',1, N'System',GETDATE(), 94, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 94, MenuName='Execution - Vessel Schedule' Where MenuID = 920

	-- Final Booking Report (432)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 432)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(432, 217, N'QC Final Booking Report', N'Operations/FinalBookingReport', 4, N'', 1, N'System',GETDATE(), 93, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 93,MenuLink=N'Operations/FinalBookingReport',ParentMenuID=217, MenuName='QC Final Booking Report' Where MenuID = 432
	-- /End Final Booking Report (432)

	-- Payout Report (434)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 434)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(434, 217, N'QC Booking Report', N'Operations/PayoutReport', 95, N'', 1, N'System',GETDATE(), 95, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 95, MenuName='QC Booking Report' Where MenuID = 434
	-- /End Payout Report (434)

	-- PM Final Booking Report (436)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 436)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(436, 217, N'PM Final Booking Report', N'Operations/FinalBookingReport/PMFinalBookingReport', 96, N'', 1, N'System',GETDATE(), 96, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 96,MenuLink=N'Operations/FinalBookingReport/PMFinalBookingReport' Where MenuID = 436
	-- /End PM Final Booking Report (436)

	-- RTG Final Booking Report (438)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 438)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(438, 217, N'RTG Final Booking Report', N'Operations/FinalBookingReport/RTGFinalBookingReport', 97, N'', 1, N'System',GETDATE(), 97, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 97,MenuLink=N'Operations/FinalBookingReport/RTGFinalBookingReport' Where MenuID = 438
	-- /End RTG Final Booking Report (438)

	-- Stackers Final Booking Report (440)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 440)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(440, 217, N'Stackers Final Booking Report', N'Operations/FinalBookingReport/StackersFinalBookingReport', 98, N'', 1, N'System',GETDATE(), 98, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 98,MenuLink=N'Operations/FinalBookingReport/StackersFinalBookingReport' Where MenuID = 440
	-- /End Stackers Final Booking Report (440)

	-- HSSE Final Booking Report (442)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 442)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(442, 217, N'HSSE Final Booking Report', N'Operations/FinalBookingReport/HSSEFinalBookingReport', 99, N'', 1, N'System',GETDATE(), 99, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 99 Where MenuID = 442
	-- /End HSSE Final Booking Report (442)

    -- Lashing Final Booking Report (444)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 444)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(444, 217, N'Lashing Final Booking Report', N'Operations/FinalBookingReport/LashingFinalBookingReport', 100, N'', 1, N'System',GETDATE(), 100, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 100 Where MenuID = 444
	-- /End Lashing Final Booking Report (444)

	-- Revoke SignOff (445)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 445)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(445, 217, N'Revoke SignOff', N'Operations/DailyOperation/RevokeSignOff', 101, N'', 1, N'System',GETDATE(), 101, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 101 Where MenuID = 445
	-- /End Revoke SignOff (445)

	-- Shift Report (453)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 453)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(453, 217, N'Shift Report', N'Operations/FinalBookingReport', 102, N'', 1, N'System',GETDATE(), 102, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 102,MenuLink=N'Operations/FinalBookingReport' Where MenuID = 453
	-- /End Shift Report (453)

		-- Slashed Cranes List (462)
	IF NOT EXISTS (SELECT * FROM C_Menu WHERE MenuID = 462)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(462, 217, N'Slashed Cranes List', N'Operations/DailyOperation/SlashedCranesListIndex', 15, N'', 1, N'System',GETDATE(), 92, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 92 Where MenuID = 462
	-- /End Slashed Cranes List (462)

-- /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)			
--ELSE UPDATE C_Menu SET DisplayOrder = 93 Where MenuID = 218

--	-- 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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 94 Where MenuID = 364
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 95 Where MenuID = 365
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 96 Where MenuID = 366
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 97 Where MenuID = 367
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 95 Where MenuID = 368
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 96 Where MenuID = 369
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 97 Where MenuID = 370
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 98 Where MenuID = 371
--	-- /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)
--	ELSE UPDATE C_Menu SET DisplayOrder = 99 Where MenuID = 372
--	-- /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)	
ELSE UPDATE C_Menu SET DisplayOrder = 100 Where MenuID = 219
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 101 Where MenuID = 392
-- /End Equipment Maintenance Update (219)

	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 474)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(474, 219, N'Crane Condition',N'MariTime/EquipmentMaintenance/CraneConditionindex', 1, N'sidenav-icon fas fa-user-tie', 1, N'System',GETDATE(), 93, 0, 0)			
	ELSE UPDATE C_Menu SET DisplayOrder = 101 Where MenuID = 474
-- /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)			
ELSE UPDATE C_Menu SET DisplayOrder = 102 Where MenuID = 220
-- /End E-Attendance Monitoring (220)

-- TOS Interface Logs (454)
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 454)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(454, 105, N'TOS Interface Logs',NULL, 1, N'sidenav-icon fas fa-book-reader', 8, N'System',GETDATE(), 95, 0, 0)	

	--Equipment Log In - Out (455)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 455)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(455, 454, N'Equipment Log In - Out','Interfaces/TOSInterfaceLogIndex', 1, N'', 9, N'System',GETDATE(), 103, 0, 0)	

	--Box Movement (456)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 456)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(456, 454, N'Box Movement','Interfaces/TOSInterfaceLogIndex', 1, N'', 10, N'System',GETDATE(), 104, 0, 0)	

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)	
ELSE UPDATE C_Menu SET DisplayOrder = 103 Where MenuID = 221
	-- 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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 104 Where MenuID = 393
	-- /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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 105 Where MenuID = 398
	-- /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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 106 Where MenuID = 394
	-- /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)			
	ELSE UPDATE C_Menu SET DisplayOrder = 107 Where MenuID = 410
	-- /End Raw Clocking (410)

	-- Employee Incentive (433)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 433)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(433, 221, N'Employee Incentive', N'Operations/EmployeeIncentive', 108, N'', 1, N'System',GETDATE(), 94, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 108, ParentMenuID = 221 Where MenuID = 433
	-- /End Employee Incentive (433)

	-- PTP T&A Export (457)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 457)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(457, 221, N'PTP T&A Export', N'TimeAttendance/TimeAttendanceExport', 108, N'', 1, N'System',GETDATE(), 109, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 109, ParentMenuID = 221 Where MenuID = 457
	-- /End PTP T&A Export (457)


-- HRMS Interface [429]
IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 429)
	INSERT INTO 
	C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
	VALUES(429, 106, N'HRMS Interface',NULL, 1, N'sidenav-icon fas fa-tasks', 1, N'System',GETDATE(), 98, 0, 0)	
 
    -- Pay period Sign-Off (430)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 430)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(430, 429, N'Pay period Sign-Off',N'TimeAttendance/HRMSInterface/PayperiodSignOffIndex', 1, N'', 1, N'System',GETDATE(), 99, 0, 0)	
	--HRMS Data (431)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 431)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(431, 429, N'HRMS Data',N'TimeAttendance/HRMSInterface/HRMSDataIndex', 2, N'', 1, N'System',GETDATE(), 100, 0, 0)
SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
SET 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-clock', 1, N'System',GETDATE(), 98, 0, 0)
ELSE UPDATE C_Menu SET MenuImage ='sidenav-icon fas fa-clock', DisplayOrder = 108 WHere MenuID = 223

	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 109 Where MenuID = 373
	-- /End Employee Details (373)Reports/TimeSheetSummary

	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 110 Where MenuID = 374
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 111 Where MenuID = 375
	-- /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)
ELSE UPDATE C_Menu SET DisplayOrder = 112 Where MenuID = 224
-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 113 Where MenuID = 376
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 114 Where MenuID = 377
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 115 Where MenuID = 378
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 116 Where MenuID = 379
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 116 Where MenuID = 380
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 117 Where MenuID = 381
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 118 Where MenuID = 382
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 119 Where MenuID = 395
	-- /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)	
ELSE UPDATE C_Menu SET DisplayOrder = 120 Where MenuID = 225
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 121 Where MenuID = 383
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 122 Where MenuID = 396
	-- /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)	
ELSE UPDATE C_Menu SET DisplayOrder = 123 Where MenuID = 226
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 124 Where MenuID = 384
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 125 Where MenuID = 385
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 126 Where MenuID = 386
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 127 Where MenuID = 387
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 128 Where MenuID = 388
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 129 Where MenuID = 389
	-- /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)
	ELSE UPDATE C_Menu SET DisplayOrder = 130 Where MenuID = 404
	-- /End Weekly Leave Report (404)

-- /End ESS Reports (226)

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

	-- User Login Activity (419)
	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 419)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(419, 229, N'User Login Activity', N'Reports/UserLoginActivity', 1, N'', 1, N'System',GETDATE(), 115, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 131 Where MenuID = 419
	-- /End Monthly Leave Report (419)
-- /End ESS Reports (229)

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
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)		
ELSE UPDATE C_Menu SET DisplayOrder = 132 Where MenuID = 228
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 132 Where MenuID = 411
	-- 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)
	ELSE UPDATE C_Menu SET DisplayOrder = 133 Where MenuID = 415

	IF NOT EXISTS(SELECT * FROM C_Menu WHERE MenuId = 481)
		INSERT INTO 
		C_Menu (MenuID, ParentMenuID, MenuName, MenuLink, DisplayOrder, MenuImage, IsActive, CreatedBy, CreatedDate, Sequence, IsSelfService, IsHorizontalMenuItem)
		VALUES(481, 228, N'RTG Dashboard', N'Dashboard/RTGDashboard/Index', 4, N'', 1, N'System',GETDATE(), 12, 0, 0)
	ELSE UPDATE C_Menu SET DisplayOrder = 134 Where MenuID = 481
-- /End Dashboard Child Menu Items

SET IDENTITY_INSERT [dbo].[C_Menu] OFF
GO
--Insert Into Organization Unit
IF NOT EXISTS(SELECT * FROM C_OrganizationNode WITH (NOLOCK) WHERE OUId = 1)
BEGIN
	SET IDENTITY_INSERT [dbo].[C_OrganizationNode] ON 

	INSERT INTO C_OrganizationNode 
	(OUId, OUName, OUDesc, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(1, 'HOME','HOME',1,'System',GETDATE())

	SET IDENTITY_INSERT [dbo].[C_OrganizationNode] OFF
END
GO



BEGIN
	-- Insert Admin Security Role
	DECLARE @@SecurityRoleId BigInt = 0, @@SecurityRolePermissionId BigInt = 0, @@UserId BigInt = 0, @@UserSecurityRoleId BigInt = 0

	--DELETE FROM C_SecurityRole WHERE C_SecurityRole.SecurityRoleCode = 'Administrator'

	IF NOT EXISTS(SELECT * FROM C_SecurityRole WITH (NOLOCK) WHERE C_SecurityRole.SecurityRoleCode = 'Administrator')
	BEGIN
		INSERT INTO C_SecurityRole (SecurityRoleCode, Description, IsActive, CreatedBy, CreatedDate)
		VALUES('Administrator','System Administrator', 1, 'System', GETDATE())

		SET @@SecurityRoleId = CAST(@@Identity AS INTEGER) 
	END
	ELSE
	BEGIN
		SELECT	@@SecurityRoleId = C_SecurityRole.SecurityRoleId 
		FROM	C_SecurityRole WITH (NOLOCK) WHERE C_SecurityRole.SecurityRoleCode = 'Administrator'
	END


	print 'C_SecurityRole' + Convert(nVarchar(50),@@SecurityRoleId)

	-- Insert Admin Security Role Permissions
	IF NOT EXISTS(SELECT * FROM C_SecurityRolePermissions WITH (NOLOCK) WHERE C_SecurityRolePermissions.SecurityRoleId = @@SecurityRoleId)
	BEGIN
		INSERT INTO C_SecurityRolePermissions (SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
		SELECT	@@SecurityRoleId, C_Menu.MenuID, 2, 'System', GETDATE()
		FROM	C_Menu	WHERE C_Menu.IsHorizontalMenuItem <> 1 AND IsActive = 1
	END


	print 'C_SecurityRole' + Convert(nVarchar(50),@@SecurityRoleId)

	-- Insert Admin User.
	IF NOT EXISTS (SELECT * FROM C_User WITH (NOLOCK) WHERE UserName ='Admin')
	BEGIN
		INSERT INTO C_User
		(UserName, PasswordHash, PasswordSalt, UserRoleID, EmployeeID, LastLoginDate, ChangePasswordOnLogin, ResetPassword, IsActive, CreatedBy, CreatedDate)
		VALUES('Admin',
			   'YNwBx/OgPoMb3yMHTmJ88rk8TFfHb8ASkD7S8NT5dUqXXbFm99DtYVDIlyAoBVEWNHuusuY1evaX3226G59FCRThrOPQQK3AisL1RbJgy1d+iGKRuLTD0Glv/+jlMQ+ZukfHdfmIM2q92t/zjVYboq7V7qECLWr9lT9CIkEqUPi5GKQYn5L0A0GeGJsiZVq1KhwwbwPEoahlhF1s/+kUvVjX9JwOsYWzjrZbR6+J8l1Bpf3GXFnsW99sXxEN2y8PkkVcpdf6B05//Xu0w7OVs92zZw3MzxTjLE7Dg+hNv/xpASk3ltUjBvoMdMwqa9xRsM+w4rgaDVrP2Ok6eL87lw==',
			   'OPHhgymPLv5n/tGs+FY70fe/+GFSoW6L0+jo04GXDkY=', NULL, NULL, NULL, 0, 0, 1, 'System', GETDATE())
		
		SET @@UserId = CAST(@@Identity AS INTEGER) 
	END
	ELSE
	BEGIN
		SELECT	@@UserId = UserID 
		FROM	C_User WITH (NOLOCK)
		WHERE	UserName ='Admin'
	END


	print 'C_User' + Convert(nVarchar(50),@@UserId)

	-- Insert User Security Role
	IF NOT EXISTS(SELECT * FROM C_UserSecurityRole WITH (NOLOCK) WHERE UserId = @@UserId)
	BEGIN
		INSERT INTO C_UserSecurityRole
		(UserId, SecurityRoleId, StartDate, EndDate, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(@@UserId, @@SecurityRoleId, NULL, NULL, 1, 'System',GETDATE())

		SET @@UserSecurityRoleId = CAST(@@Identity AS INTEGER) 
	END


	print 'C_UserSecurityRole' + Convert(nVarchar(50), @@UserSecurityRoleId)

	-- Insert Into User Security Role OU
	IF NOT EXISTS(SELECT * FROM C_UserSecurityRoleOU WHERE UserSecurityRoleId = @@UserSecurityRoleId)
	BEGIN
		INSERT INTO C_UserSecurityRoleOU
		(UserSecurityRoleId, OUId, ActiveStatus, CreatedBy, CreatedDate)
		SELECT	@@UserSecurityRoleId, OUId, 1, 'System',GETDATE()
		FROM	C_OrganizationNode 
	END

	-- Create Default Security Role As 'Employee'
	IF NOT EXISTS(SELECT * FROM C_SecurityRole WITH (NOLOCK) WHERE C_SecurityRole.SecurityRoleCode = 'Employee')
	BEGIN
		INSERT INTO C_SecurityRole (SecurityRoleCode, Description, IsActive, CreatedBy, CreatedDate)
		VALUES('Employee','Employee', 1, 'System', GETDATE())

		SET @@SecurityRoleId = CAST(@@Identity AS INTEGER) 
	END
	ELSE
	BEGIN
		SELECT	@@SecurityRoleId = C_SecurityRole.SecurityRoleId 
		FROM	C_SecurityRole WITH (NOLOCK) WHERE C_SecurityRole.SecurityRoleCode = 'Employee'
	END


	print @@SecurityRoleId

	-- Insert Employee Security Role Permissions
	IF NOT EXISTS(SELECT * FROM C_SecurityRolePermissions WITH (NOLOCK) WHERE C_SecurityRolePermissions.SecurityRoleId = @@SecurityRoleId)
	BEGIN
		INSERT INTO C_SecurityRolePermissions (SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
		SELECT	@@SecurityRoleId, C_Menu.MenuID, 2, 'System', GETDATE()
		FROM	C_Menu	WHERE C_Menu.IsHorizontalMenuItem <> 1 AND IsActive = 1 And ParentMenuID  IN (213)

		INSERT INTO C_SecurityRolePermissions (SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
		SELECT	2, C_Menu.MenuID, 0, 'System', GETDATE()
		FROM	C_Menu	WHERE C_Menu.IsHorizontalMenuItem <> 1 AND IsActive = 1 And ParentMenuID NOT  IN (213)
	END
END
GO


-- Menu Functions For Employee Profile - Basic Profile
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 1346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(1346, 346, 'Basic Profile','Employee/Views/EmployeeProfile/PartialViews/_BasicInfo.cshtml', 1 ,'System',GETDATE())

	Print 'Basic Profile Menu Function Created Successfully...'
END

-- Menu Functions For Employee Profile - Contacts
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 2346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder,  CreatedBy, CreatedDate)
	VALUES(2346, 346, 'Contacts','Employee/Views/EmployeeProfile/PartialViews/_Contacts.cshtml',6 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Contacts] Created Successfully...'
END

-- Menu Functions For Employee Profile - Disciplinary Action
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 3346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(3346, 346, 'Disciplinary','Employee/Views/EmployeeProfile/PartialViews/_DisciplinaryList.cshtml',2 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Disciplinary] Created Successfully...'
END

-- Menu Functions For Employee Profile - Excluded Skills
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 4346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(4346, 346, 'Excluded Skills','Employee/Views/EmployeeProfile/PartialViews/_ExcludedSkillsList.cshtml',3 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Excluded Skills] Created Successfully...'
END

-- Menu Functions For Employee Profile - Roles
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 5346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(5346, 346, 'Roles','Employee/Views/EmployeeProfile/PartialViews/_Roles.cshtml',4 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Roles] Created Successfully...'
END

-- Menu Functions For Employee Profile - Security
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 6346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder,  CreatedBy, CreatedDate)
	VALUES(6346, 346, 'Security','Employee/Views/EmployeeProfile/PartialViews/_SecurityAndSharedResources.cshtml',5 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Security] Created Successfully...'
END

-- Menu Functions For Employee Profile - ESS
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 7346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder,  CreatedBy, CreatedDate)
	VALUES(7346, 346, 'ESS','Employee/Views/EmployeeProfile/PartialViews/_Others.cshtml',6 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [ESS] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Reconsile
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 1393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder,  CreatedBy, CreatedDate)
	VALUES(1393, 393, 'Reconcile','',7 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Reconcile] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Mark As Present
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 2393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(2393, 393, 'Mark As Present','',8 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Mark As Present] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Mark As Absent
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 3393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(3393, 393, 'Mark As Absent','',9 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Mark As Absent] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Generate Attendance Repot
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 4393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(4393, 393, 'Generate Attendance Repot','',10 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Generate Attendance Repot] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Generate Overtime Repot
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 5393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(5393, 393, 'Generate Overtime Repot','',11 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Generate Overtime Repot] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Reprocess Reconciliation
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 6393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(6393, 393, 'Reprocess Reconciliation','',12 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Reprocess Reconciliation] Created Successfully...'
END

-- Menu Functions For Attendance Reconciliation - Reprocess Shift Costing
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 7393 And MenuId = 393) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(7393, 393, 'Reprocess Shift Costing','',13 ,'System',GETDATE())

	Print 'Attendance Reconciliation Menu Function [Reprocess Shift Costing] Created Successfully...'
END

-- Menu Functions For Workload Planning - Import Vessel Schedule
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 1361 And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(1361, 361, 'Import Vessel Schedule','',14 ,'System',GETDATE())

	Print 'Workload Planning Menu Function [Import Vessel Schedule] Created Successfully...'
END

-- Menu Functions For Workload Planning - Generate Equipments
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 2361 And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(2361, 361, 'Generate Equipments','',15 ,'System',GETDATE())

	Print 'Workload Planning Menu Function [Generate Equipments] Created Successfully...'
END

-- Menu Functions For Workload Planning - Planning Singoff
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 3361 And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(3361, 361, 'Planning Singoff','',16 ,'System',GETDATE())

	Print 'Workload Planning Menu Function [Planning Signoff] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Deployment
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 1363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(1363, 363, 'Deployment','',17 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Deployment] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Date Range Deployment
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 2363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(2363, 363, 'Date Range Deployment','',18 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Date Range Deployment] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Deallocation
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 3363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(3363, 363, 'Deallocation','',19 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Deallocation] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Date Range Deallocation
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 4363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(4363, 363, 'Date Range Deallocation','',20 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Date Range Deallocation] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Revoke Sign Off
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 5363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(5363, 363, 'Revoke Sign Off','',21 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Revoke Sign Off] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Broadcast Deployment
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 6363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(6363, 363, 'Broadcast Deployment','',22 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Broadcast Deployment] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Add Shift
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 7363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(7363, 363, 'Add Shift','',23 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Add Shift] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Swap Employee
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 8363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(8363, 363, 'Swap Employee','',24 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Swap Employee] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Add Cranes
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 9363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(9363, 363, 'Add Cranes','',25 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Add Cranes] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Add Equipments
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 10363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(10363, 363, 'Add Equipments','',26 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Add Equipments] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Create Or Assign Task
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 11363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(11363, 363, 'Create Or Assign Task','',27 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Create Or Assign Task] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Add Workload
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 12363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(12363, 363, 'Add Workload','',28 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Add Workload] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Filter
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 13363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(13363, 363, 'Filter','',29 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Filter] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Daily Booking Report
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 14363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(14363, 363, 'Daily Booking Report','',30 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Daily Booking Report] Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Equipment Booking Report
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 15363 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(15363, 363, 'Equipment Booking Report','',31, 'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Equipment Booking Report] Created Successfully...'
END

-- Menu Functions For Workload Planning - Import Equipment Schedule
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 4361 And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(4361, 361, 'Import Equipment Schedule','',32 ,'System',GETDATE())

	Print 'Workload Planning Menu Function [Import Equipment Schedule] Created Successfully...'
END

-- Menu Functions For Employee Roster - Assemble Shift
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 1390 And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(1390, 390, 'Assemble Shift','',33 ,'System',GETDATE())

	Print 'Employee Roster Menu Function [Assemble Shift] Created Successfully...'
END

-- Menu Functions For Employee Roster - Shift Validation
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 2390 And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(2390, 390, 'Shift Validation','',34 ,'System',GETDATE())

	Print 'Employee Roster Menu Function [Shift Validation] Created Successfully...'
END

-- Menu Functions For Employee Roster - Un-Allocated Work Report
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 3390 And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(3390, 390, 'Un-Allocated Work Report','',35 ,'System',GETDATE())

	Print 'Employee Roster Menu Function [Un-Allocated Work Report] Created Successfully...'
END

-- Menu Functions For Employee Roster - Un-Allocated Work Report
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 4390 And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(4390, 390, 'Advanced Assemble Shift','',36 ,'System',GETDATE())

	Print 'Employee Roster Menu Function [Advanced Assemble Shift] Created Successfully...'
END

-- Menu Functions For Employee Profile - Miscellaneous Columns
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 8346 And MenuId = 346) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder,  CreatedBy, CreatedDate)
	VALUES(8346, 346, 'Miscellaneous','Employee/Views/EmployeeProfile/PartialViews/_MiscColumns.cshtml',37 ,'System',GETDATE())

	Print 'Employee Profile Menu Function [Miscellaneous] Created Successfully...'
END

-- Menu Functions For Workload Planning - [N4] Import Vessel And Crane SChedule
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 5361 And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(5361, 361, 'N4 - Import Vessel And Crane Schedule','',38 ,'System',GETDATE())

	Print 'Workload Planning Menu Function [[N4] Import Vessel And Crane Schedule] Created Successfully...'
END

-- Menu Functions For Workload Planning - [N4] Employee Equipment Login
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 18363  And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(18363 , 363, 'N4 - Employee Equipment Login','',39 ,'System',GETDATE())

	Print 'Menu Functions For Workload Planning - [N4] Employee Equipment Login Created Successfully...'
END

-- Menu Functions For Workload Planning - Box Movement
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 19363  And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(19363 , 363, 'Box Movement','',40 ,'System',GETDATE())

	Print 'Menu Functions For Workload Planning - Box Movement Created Successfully...'
END

-- Menu Functions For Employee Roster -Roster Template Export
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 19364  And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(19364 , 390, 'Roster Template Export','',41 ,'System',GETDATE())

	Print 'Menu Functions For Employee Roster - Roster Template Export Created Successfully...'
END

-- Menu Functions For Employee Roster -Roster Template Export
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20363  And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20363 , 363, 'Update Prime Mover Equipments','',42 ,'System',GETDATE())

	Print 'Menu Functions For Update Prime Mover Equipments Created Successfully...'
END

-- Menu Functions For Workload Planning - [PTP] Import Berth Tool
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 19365  And MenuId = 361) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(19365 , 361, 'PTP - Import Berth Tool','',42 ,'System',GETDATE())

	Print 'Menu Functions For Workload Planning - [PTP] Import Berth Tool Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Apply Leave
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20364  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20364 , 907, 'Apply Leave','',44 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf - Apply Leave Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Apply TimeOff
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20365  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20365 , 907, 'Apply TimeOff','',45 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf - Apply TimeOff Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Request Days In Lieu
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20366  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20366 , 907, 'Request DaysInLieu','',46 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf - Request Days In Lieu Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Request Training
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20367  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20367 , 907, 'Request Training','',47 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf - Request Training Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Apply for UnControlled Leave
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20368  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20368 , 907, 'Apply for UnControlled Leave','',48 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf -Apply for UnControlled Leave Created Successfully...'
END

-- Menu Functions For Apply On Behalf - Apply for Exclude Deployment
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20369  And MenuId = 907) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20369 , 907, 'Apply for Exclude Deployment','',49 ,'System',GETDATE())

	Print 'Menu Functions For Apply On Behalf -Apply for Exclude Deployment Created Successfully...'
END

-- Menu Functions For Operations Duty Manager - Swap Employee Shift
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20370 And MenuId = 363) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20370, 363, 'Swap Employee Shift','',50 ,'System',GETDATE())

	Print 'Operations Duty Manager Menu Function [Swap Employee Shift] Created Successfully...'
END

-- Menu Functions For Employee Roster - BroadCast Message
IF NOT EXISTS (SELECT * FROM C_MenuFunctions Where MenuFunctionId = 20371 And MenuId = 390) 
BEGIN
	INSERT INTO C_MenuFunctions (MenuFunctionId, MenuId, FunctionName, FunctionView, DisplayOrder, CreatedBy, CreatedDate)
	VALUES(20371, 390, 'BroadCast Message','',51 ,'System',GETDATE())

	Print 'Employee Roster Menu Function [BroadCast Message] Created Successfully...'
END

DECLARE @MenuFunctionId BigInt  = 0, @MenuId BigInt = 0, @SecurityRoleId BigInt = 0, @MenuPermissionTypeId Int = 0

DECLARE SecurityRoles_Cursor CURSOR FOR
SELECT	SecurityRoleID
FROM	C_SecurityRole WITH (NOLOCK)

OPEN SecurityRoles_Cursor
FETCH NEXT FROM SecurityRoles_Cursor INTO @SecurityRoleId

WHILE @@FETCH_STATUS = 0
BEGIN
	DECLARE MenuFunctions_Cursor CURSOR FOR
	SELECT	MenuFunctionId, MenuId
	FROM	C_MenuFunctions WITH (NOLOCK)	

	OPEN MenuFunctions_Cursor
	FETCH NEXT FROM MenuFunctions_Cursor INTO @MenuFunctionId, @MenuId

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SELECT	@MenuPermissionTypeId = PermissionTypeId
		FROM	C_SecurityRolePermissions
		WHERE	SecurityRoleId = @SecurityRoleId
		AND		MenuId = @MenuId

		IF NOT EXISTS (SELECT * FROM C_SecurityRoleMenuFunctionPermissions WHERE MenuFunctionId = @MenuFunctionId And SecurityRoleId = @SecurityRoleId)
		BEGIN
			INSERT INTO C_SecurityRoleMenuFunctionPermissions
			(SecurityRoleId, MenuFunctionId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleId, @MenuFunctionId, iif(@MenuPermissionTypeId = 0, 4, 3), 'System',GETDATE())
			--Print 'Create Permission ' + Convert(nVarchar(2),iif(@MenuPermissionTypeId = 2, 3, 4)) + ' For Security Role Id ' + Convert(nVarchar(10),@SecurityRoleId) + ' MenuFunctionId ' + Convert(nVarchar(10),@MEnuFunctionId)
		END
		ELSE	UPDATE C_SecurityRoleMenuFunctionPermissions SET PermissionTypeId = iif(@MenuPermissionTypeId = 0, 4, 3) 
				Where SecurityRoleId = @SecurityRoleId And MenuFunctionId = @MenuFunctionId --Print 'Permission Available For Security Role Id ' + Convert(nVarchar(10),@SecurityRoleId) + ' MenuFunctionId ' + Convert(nVarchar(10),@MEnuFunctionId)

		FETCH NEXT FROM MenuFunctions_Cursor INTO @MenuFunctionId, @MenuId
	END

	CLOSE MenuFunctions_Cursor
	DEALLOCATE MenuFunctions_Cursor

	FETCH NEXT FROM SecurityRoles_Cursor INTO @SecurityRoleId
END
CLOSE SecurityRoles_Cursor
DEALLOCATE SecurityRoles_Cursor

--select * from C_SecurityRoleMenuFunctionPermissions wHERE SecurityRoleId = 4



SET IDENTITY_INSERT [dbo].[D_MasterCodes] ON 
GO

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 1)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (1, N'Country', N'Malaysia', 99, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Country [Malaysia] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 2)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (2, N'Gender', N'Male', 1, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Gender [Male] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 3)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (3, N'Gender', N'Female', 2, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Gender [Female] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 4)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (4, N'Country', N'United States', 3, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Country [United States] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 5)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (5, N'RelationShip', N'Spouse', 1, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'RelationShip [Spouse] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 6)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (6, N'DisciplinaryStatus', N'Suspended', 1, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'DisciplinaryStatus [Suspended] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 7)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate])
	VALUES (7, N'DisciplinaryStatus', N'Terminated', 2, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'DisciplinaryStatus [Terminated] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 11)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (11, N'Priority', N'High', 1, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Priority [High] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 12)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (12, N'Priority', N'Medium', 2, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Priority [Medium] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 13)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (13, N'Priority', N'Low', 3, 1, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Priority [Low] Exists...'

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 14)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (14, N'Country', N'Oman', 4, 0, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Country [Oman] Exists...'

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeId = 15)
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (15, N'Position', N'Stevedore', 1, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Workflow Positions [Stevedore] Added'
END

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeId = 16)
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (16, N'Position', N'YHE Operator', 1, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Workflow Positions [YHE Operator] Added'
END

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeId = 17)
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (17, N'Position', N'TT Driver', 1, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Workflow Positions [TT Driver] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'CranePriority' And CodeValue ='P1')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (551, N'CranePriority', N'P1', 1, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Crane Priority [P1] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'CranePriority' And CodeValue ='P2')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (552, N'CranePriority', N'P2', 2, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Crane Priority [P2] Exists'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'CranePriority' And CodeValue ='P3')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (553, N'CranePriority', N'P3', 3, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Crane Priority [P3] Added'
END

IF NOT EXISTS (SELECT * FROM D_MasterCodes WHERE CodeId = 554)
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (554, N'Country', N'Vietnam', 18, 0, N'System', GETDATE(), NULL, NULL)
ELSE Print 'Country [Vietnam] Exists...'

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'PerformanceRating' And CodeValue ='A')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES ((SELECT MAX(CodeId) + 1 FROM D_MasterCodes), N'PerformanceRating', N'A', 1, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Performance Rating [A] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'PerformanceRating' And CodeValue ='A1')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES ((SELECT MAX(CodeId) + 1 FROM D_MasterCodes), N'PerformanceRating', N'A1', 2, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Performance Rating [A1] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'PerformanceRating' And CodeValue ='A2')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES ((SELECT MAX(CodeId) + 1 FROM D_MasterCodes), N'PerformanceRating', N'A2', 3, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Performance Rating [A2] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'PerformanceRating' And CodeValue ='B')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES ((SELECT MAX(CodeId) + 1 FROM D_MasterCodes), N'PerformanceRating', N'B', 4, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Performance Rating [B] Added'
END

IF NOT EXISTS (SELECT * FROM d_mastercodes WHERE CodeType = 'PerformanceRating' And CodeValue ='C')
BEGIN
	INSERT [dbo].[D_MasterCodes] ([CodeId], [CodeType], [CodeValue], [Seq], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES ((SELECT MAX(CodeId) + 1 FROM D_MasterCodes), N'PerformanceRating', N'C', 5, 1, N'admin', GETDATE(), N'admin', GETDATE())
	
	Print 'Performance Rating [C] Added'
END

SET IDENTITY_INSERT [dbo].[D_MasterCodes] OFF
GO

SET IDENTITY_INSERT [dbo].[D_ShiftBandType] ON 
GO

IF NOT EXISTS (SELECT * FROM D_ShiftBandType WHERE ShiftTypeId = 1)
	INSERT [dbo].[D_ShiftBandType] ([ShiftTypeId], [ShiftBandTypeDescription], [Seq], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate], [IsActive]) 
	VALUES (1, N'Normal Shift', 1, 'System', GETDATE(), NULL, NULL, 1)
Else Print 'Shift Band Type [Normal Shift] Exists...'

IF NOT EXISTS (SELECT * FROM D_ShiftBandType WHERE ShiftTypeId = 2)
	INSERT [dbo].[D_ShiftBandType] ([ShiftTypeId], [ShiftBandTypeDescription], [Seq], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate], [IsActive]) 
	VALUES (2, N'Overtime Shift', 2, 'System', GETDATE(), NULL, NULL, 1)
ELSE Print 'Shift Band Type [Overtime Shift] Exists...'

IF NOT EXISTS (SELECT * FROM D_ShiftBandType WHERE ShiftTypeId = 3)
	INSERT [dbo].[D_ShiftBandType] ([ShiftTypeId], [ShiftBandTypeDescription], [Seq], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate], [IsActive]) 
	VALUES (3, N'Combination Shift', 3, 'System', GETDATE(), NULL, NULL, 1)
Else Print 'Shift Band Type [Combination Shift] Exists...'

SET IDENTITY_INSERT [dbo].[D_ShiftBandType] OFF
GO




SET IDENTITY_INSERT [dbo].[D_SystemParams] ON 
GO

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 1) 
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (1, N'THPBuffer', N'-6', N'THP Process Buffertime', 1, N'SYSTEM ADMIN', CAST(N'2018-10-10 00:00:00.000' AS DateTime), NULL, NULL)
ELSE Print 'System Parameter [THPBuffer] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 2) 
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (2, N'ReconProcessBufferMinutes', N'300', N'Reconcilation Process Buffer Minutes. Shifts Which ends - Minutes From Current Process Time', 1, N'SYSTEM ADMIN', CAST(N'2018-10-10 00:00:00.000' AS DateTime), NULL, NULL)
ELSE Print 'System Parameter [ReconProcessBufferMinutes] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 3)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (3, N'ReliefBreakId', N'19', N'Relief Break Id From D_Skill', 1, N'SYSTEM ADMIN', CAST(N'2018-10-10 00:00:00.000' AS DateTime), NULL, NULL)
ELSE Print 'System Parameter [ReliefBreakId] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 4)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (4, N'DaysInLieuId', N'9', N'Days In Lieu Exception Code ID From D_ExceptionCodes', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [DaysInLieuId] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 5)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (5, N'ApplicationUserDefaultSecurityRoleId', N'5', N'User Security Role ID From C_SecurityRole', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [ApplicationUserDefaultSecurityRoleId] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 6)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (6, N'ClinicalPortalLeaveIds', N'2,13,14,15', N'Exception Code Ids From D_ExceptionCodes.ExceptionCodeId For Sick Leave, Domestic Injury, Work Related Injury, Maternity Leave', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [ClinicalPortalLeaveIds] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 7)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (7, N'MinActivityHoursInShift', N'24:2,63:10', N'Min Activity Hours Filtered By OU to Slash and Merge Activities And Shifts With Multi Skills', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MinActivityHoursInShift] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 8)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (8, N'AnnualLeaveId', N'1', N'Annual Leave Id For Public Holiday And Ramadan Process', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [AnnualLeaveId] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 9)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (9, N'MaxTimeOffHoursInCalendarYear', N'60', N'Number of Time Off Application Hours Allowed In Calendar Year', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MaxTimeOffHoursInCalendarYear] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 10)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (10, N'AllowApprovedLeaveCancellationBefore', N'30', N'System Allows users to cancel approved leaves with in X Number of defined days', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [AllowApprovedLeaveCancellationBefore] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 11)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (11, N'RamadanDaysInLieuCode', N'DaysinLieu_Ramadan', N'Ramadan Days In Lieu Exception Code D_ExceptionCodes', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [RamadanDaysInLieuCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 12)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (12, N'OvertimeMinutesForRamadanDaysInLieu', N'360', N'6 Hours OverTime  = 1 Ramadan DIL [6 * 60 = 360 Min]', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [OvertimeMinutesForRamadanDaysInLieu] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 13)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (13, N'ConvertToOnCallShiftFromXDays', N'6', N'Change Shift From Normal to On Call Shift After Being Deployed For 6 days in a period', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [ConvertToOnCallShiftFromXDays] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 14)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (14, N'TimeOffExceptionCode', N'Time Off', N'Time Off Code To Determine Id For Pending Transaction Approval', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [TimeOffExceptionCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 15)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (15, N'TrainingExceptionCode', N'Training', N'Training Code To Determine Id For On Behalf Training Application', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [TrainingExceptionCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 16)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (16, N'OnCallShiftColor', N'#263238', N'Back Ground Color For On Call Shift', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [OnCallShiftColor] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 17)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (17, N'LeaveCodesHiddenToEmployee', N'RR,Haj', N'Leave Codes Which are not allowed to apply by employee, allow only by on behalf', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [LeaveCodesHiddenToEmployee] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 18)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (18, N'NonBusinessDayNames', N'Friday,Saturday', N'Names of week day to be considered as weekend', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [NonBusinessDayNames] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 19)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (19, N'MinLeaveDaysToExcludeNonBusinessDays', N'5', N'If Leave Days are >5 Consider WeekEnd Days as off days for Flex', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MinLeaveDaysToExcludeNonBusinessDays] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 20)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (20, N'EmploymentBasisToExcludeNonBusinessDays', N'Flex,GCT-Flex', N'Employment Basis Which Required to exclude non business days if leave take >X days', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EmploymentBasisToExcludeNonBusinessDays] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 21)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (21, N'PublicHolidayProcessTypeBEmploymentBasis', N'Flex,GCT-Flex', N'Exclude The Selected Employment Basis From Public Holiday DIL Process', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [PublicHolidayProcessTypeBEmploymentBasis] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 22)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate])
	VALUES (22, N'ExcludeDILForfeitProcessYear', N'2020', N'Year of which DIL forfeit process should not process', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [ExcludeDILForfeitProcessYear] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 23)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (23, N'FirstDayOfWeekNumber', N'0', N'Determines Week Day Number From Sunday-Saturday, index starts from 0 - 6', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [FirstDayOfWeekNumber] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 24)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (24, N'MHPMTarget', N'1.25', N'This will be used in Productivity Dashboard MHPM Weekly & Monthly Chart', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MHPMTarget] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 25)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (25, N'FifthDayTargetPercentage', N'90', N'Weekly & Monthly Fifth Day Target Percentage', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [FifthDayTargetPercentage] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 26)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (26, N'SixthDayTargetPercentage', N'50', N'Weekly & Monthly Sixth Day Target Percentage', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [SixthDayTargetPercentage] Already Exists'

--IF NOT EXISTS (SELECT * FROM D_SystemParams WHERE ParamId = 27)
--	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
--	VALUES (27, N'SixthDayTargetPercentage', N'50', N'Weekly & Monthly Sixth Day Target Percentage', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
--ELSE Print 'System Parameter [SixthDayTargetPercentage] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 28)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (28, N'EnableEmployeeSkillCounters', N'1', N'Enable Skill Based THP Calculation By Employee For Allocation. 0 = Disabled, 1 = Enabled', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EnableEmployeeSkillCounters] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 29)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (29, N'EnableRollingTHP', N'1', N'Enable Rolling THP Calculation For Allocation. 0 = Disabled, 1 = Enabled', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EnableRollingTHP] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 30)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (30, N'PublishRosterBacklogDays', N'30', N'Number of days does the system allows to select publish roster start date', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [PublishRosterBacklogDays] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 31)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (31, N'EnableReliefBreakRotation', N'1', N'Enable Relie Break Rotation Rule For Activity Generation Process', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EnableReliefBreakRotation] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 32)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (32, N'LiveRankingRoles', N'QCO', N'Roles which are required to enable RBR Ranking', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [LiveRankingRoles] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 33)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (33, N'LiveRankingSequence', N'A,B,C,D', N'Order of Live Ranking sequence', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE UPDATE D_SystemParams SET ParamValue = N'A,B,C,D,E,F' WHERE ParamId = 33 

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 34)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (34, N'LiveRankStandbySequence', N'D', N'The Character which shall be treated as Standby from Rank Sequence', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [LiveRankStandbySequence] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 35)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (35, N'EnableDeleteExceptionsFromEmployeeRoster', N'Attendance,Exclude Deployment', N'Define those exceptions which are allowed to cancel/delete from Employee Roster screen Ex: [Training,External Training]', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE UPDATE D_SystemParams SET ParamValue = N'Attendance,Exclude Deployment' WHERE ParamId = 35

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 36)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (36, N'DisplayEmployeeLeaveCodes', N'AL,DaysinLieu,DaysinLieu_Ramadan', N'System Will only displays those leave codes in employee leave profile', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [DisplayEmployeeLeaveCodes] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 37)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (37, N'AnnualLeaveCode', N'AL', N'Use Leave Codes to Find Id For Leave Application Summary Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [AnnualLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 38)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (38, N'HajLeaveCode', N'Haj', N'Use Leave Codes to Find Id For Leave Application Summary Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [HajLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 39)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (39, N'MarriageLeaveCode', N'MAL', N'Use Leave Codes to Find Id For Leave Application Summary Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MarriageLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 40)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (40, N'MaternityLeaveCode', N'ML', N'Use Leave Codes to Find Id For Leave Application Summary Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MaternityLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 41)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (41, N'UnpaidLeaveCode', N'UL', N'Use Leave Codes to Find Id For Leave Application Summary Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [UnpaidLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 42)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (42, N'EnableEquipmentTypeFilterInPlanning', N'0', N'If set to 1 is show, 0 to hide Equipment Type Dropdown in Operation Planning', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EnableEquipmentTypeFilterInPlanning] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 43)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (43, N'ExcludeAccrualForLeaveCodesXDays', N'UL:30,ML:60', N'Exclude from Accrual when Unpaid Leave is more than 30 days Ex: [UL:30,ML:60 - Unpaid Leave : Morethan 30days, Maternity Leave : More than 60days', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [ExcludeAccrualForLeaveCodesXDays] Already Exists'

--Added for History Period E10-384
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 44)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (44, N'HistoryStartFrom', N'-90', N'History Data start From Days for HRMS Interface', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [HistoryStartFrom] Already Exists'

--Added for Crane Payout Granularity E10-384
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 45)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (45, N'CranePayoutGranularity', N'30', N'Crane Payout Granularity in minutes', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [CranePayoutGranularity] Already Exists'

-- Default Equipment Name For Prime Mover Planning
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 46)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (46, N'DefaultPrimeMoverName', N'DefaultPM', N'Name of the Equipment Which will be used in PM Planning', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [DefaultPrimeMoverName] Already Exists'

-- Default Equipment Name For Prime Mover Planning
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 47)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (47, N'NotifyUncontrolledLeave', N'000175,000185', N'Send Uncontrolled Leave Notification to given list [Ex: 000175,000185]', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [NotifyUncontrolledLeave] Already Exists'

-- Default Interval time for Raw Clocking In Time
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 48)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (48, N'RawClockingBufferInterval', N'30', N'An interval between transactions of In & Out [Ex: 30sec]', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [RawClockingBufferInterval] Already Exists'

-- Off day Code for Off days
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 49)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (49, N'OFFDay', N'OD', N'Uses the code to fill for off days in the report', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [OFFDay] Already Exists'


-- Default Berth Name for Berth Tool Interface
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 50)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (50, N'DefaultBerth', N'B02', N'Berth name to be used in Import of Berth Tool', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [DefaultBerth] Already Exists'

-- Customer Reference Number For UI Manipulation
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 51)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (51, N'CustomerReference', N'PTP', N'Customer Reference For Caption Control', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [CustomerReference] Already Exists'

-- Default Berth Name for Berth Tool Interface
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 52)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (52, N'WorkloadSlashMinutes', N'60', N'X number of minutes for Slash Parameters', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [WorkloadSlashMinutes] Already Exists'

-- Employee Skill Rating
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 53)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (53, N'EmployeeSkillRating', N'QCO', N'EmployeeSkillRating', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EmployeeSkillRating] Already Exists'

-- Mandatory Remarks
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 54)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (54, N'RemarksMandatory', N'1', N'Remarks is mandatory for Apply Leave', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [RemarksMandatory] Already Exists'

-- Medical Leave
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 55)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (55, N'MedicalLeave', N'MC:HP', N'Hospitalization leave is with MC for Leave Balance deduction', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE 
Begin
    Update D_SystemParams
	Set    ParamName = N'MedicalLeave',
	       ParamValue = N'MC:HP'
	Where  ParamId = 55
End

-- Leave in Lieu COde
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 56)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (56, N'LeaveInLieu', N'17', N'Leave Code for Leave in Lieu', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [LeaveInLieu] Already Exists'

-- Medical Leave COde
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 57)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (57, N'MedicalLeaveCode', N'MC', N'Leave Code for MedicalLeave', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [MedicalLeaveCode] Already Exists'

-- Retrive Working RTG Rage Mins
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 58)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (58, N'RetriveWorkingRTGRageMins', N'60', N'Retrieve List of working RTGs in Last X Mins', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [RetriveWorkingRTGRageMins] Already Exists'

-- Display Shift Band Only In Employee Roster Event
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 59)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (59, N'DisplayShiftBandOnlyInEmployeeRosterEvent', N'1', N'Display ShiftBand Only In Employee Roster Event', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [DisplayShiftBandOnlyInEmployeeRosterEvent] Already Exists'

-- Number of hours to define the validity of Location From Employee Equipment Login
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 60)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (60, N'EquipmentLocationValidityHours', N'24', N'X Number of hours does the Last Location is valid', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [EquipmentLocationValidityHours] Already Exists'

-- Number of hours to define the validity of Location From Employee Equipment Login
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 61)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (61, N'PMActivityGranularityUpdateMins', N'15', N'X Number of mins Granularity For Used PM Equipment', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [PMActivityGranularityUpdateMins] Already Exists'

-- Number of hours to define the validity of Location From Employee Equipment Login
IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 62)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (62, N'RTGActivityGranularityUpdateMins', N'60', N'X Number of mins Granularity For Used RTG Equipment', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [RTGActivityGranularityUpdateMins] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 63)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (63, N'PublicHolidayId', N'11', N'Public Holiday Id for Apply Leave', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [PublicHolidayId] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 64)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (64, N'UnrecordedLeaveCode', N'UNREC', N'Unrecorded Leave Code for Validating Application On PBH', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [UnrecordedLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 65)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (65, N'UnpaidMedicalLeaveCode', N'UML', N'Unpaid Medical Leave Code for Validation', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [UnpaidMedicalLeaveCode] Already Exists'


IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 66)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (66, N'CompensationLeaveCodes', N'MCOMD,MCOMH,MCOMN', N'Compensation Leave Codes To Deduct Balance', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [UnpaidMedicalLeaveCode] Already Exists'

IF NOT EXISTS (SELECT * FROM D_SystemParams WITH (NOLOCK) WHERE ParamId = 67)
	INSERT [dbo].[D_SystemParams] ([ParamId], [ParamName], [ParamValue], [ParamDesc], [ActiveStatus], [CreatedBy], [CreatedDate], [UpdatedBy], [UpdatedDate]) 
	VALUES (67, N'CraneAndSkillPriorityMapping', N'P1:1,P2:2,P3:3,P4:4,P5:5,P6:6,P7:7', N'Map Crane Priority With Skill Rating Numbers.', 1, N'SYSTEM ADMIN', GETDATE(), NULL, NULL)
ELSE Print 'System Parameter [CraneAndSkillPriorityMapping] Already Exists'

SET IDENTITY_INSERT [dbo].[D_SystemParams] OFF
GO


--Validate Whether Allocation Factor 'Shift Hours' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 1) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (1, N'Shift Hours', N'Shift Hours', 100, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Shift Hours] Already Exists'

--Validate Whether Allocation Factor 'Primary Skill' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 2) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (2, N'Primary Skill', N'Primary Skill', 100, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Primary Skill] Already Exists'

--Validate Whether Allocation Factor 'Non Primary Skill' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 3) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (3, N'Non Primary Skill', N'Non Primary Skill', 50, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Non Primary Skill] Already Exists'

--Validate Whether Allocation Factor 'Activity Hours' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 4) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (4, N'Activity Hours', N'Activity Hours', 100, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Activity Hours] Already Exists'

--Validate Whether Allocation Factor 'Schedule Creation Rule' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 5) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (5, N'ScheduleCreationRuleSchedule','CreationRuleActivity Hours', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [ScheduleCreationRuleSchedule] Already Exists'

--Validate Whether Allocation Factor 'Activity Hours Sort By DESC' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 6) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (6, N'Workload Activity Hours (Descending)','Sort Activity Hours In Descending Order', 0, 1, 'System', GETDATE(), 1)
END
ELSE Print 'Allocation Factor [Workload Activity Hours (Descending)] Already Exists'

--Validate Whether Allocation Factor 'Overrid' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 7) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (7, N'Override Allocation Process','Override And Optimize Allocation With In A Role Group', 0, 1, 'System', GETDATE(), 2)
END
ELSE Print 'Override Allocation Process [Override And Optimize Allocation With In A Role Group] Already Exists'

--Validate Whether Allocation Factor 'Relief Rule Rotation' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 8) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (8, N'Relief Rule Rotation','Relief Rule Rotation For Employees and Activities', 0, 1, 'System', GETDATE(), 3)
END
ELSE Print 'Relief Rule Rotation Process [Relief Rule Rotation For Employees and Activities] Already Exists'
GO

--Validate Whether Allocation Factor 'Primary OU' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 9) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (9, N'Primary OU','Employee Primary Organization Unit', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Primary Organization Unit Allocation Factor Already Exists'
GO


--Validate Whether Allocation Factor 'Secondary OU' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 10) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (10, N'Secondary OU','Employee Secondary Organization Unit', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Secondary Organization Unit Allocation Factor Already Exists'
GO

--Validate Whether Allocation Factor 'Employee Skill Priority' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 11) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (11, N'Employee Skill Priority','Employee Skill Priority For Factor Calculation', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Employee Skill Priority Allocation Factor Already Exists'
GO

--Validate Whether Allocation Factor 'Sort Activities By Crane Priority' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 12) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (12, N'Sort Activities By Crane Priority','Sort Activities By Available Crane Priority', 0, 1, 'System', GETDATE(), 1)
END
ELSE Print 'Allocation Factor [Sort Activities By Crane Priority] Already Exists'
GO

--Validate Whether Allocation Factor 'Sort Activities By Crane Priority' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 13) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (13, N'Crane Condition','Crane Condition Value For THP Calculation', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Crane Condition] Already Exists'
GO

--Validate Whether Allocation Factor 'Relief Rule Rotation' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 14) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (14, N'Equipment Rotation','Equipment Assignment Rotation For Employees', 0, 1, 'System', GETDATE(), 3)
END
ELSE Print 'Relief Rule Rotation Process [Equipment Assignment Rotation For Employees] Already Exists'
GO

--Validate Whether Allocation Factor 'Relief Rule Rotation' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 15) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (15, N'Skill And Crane Rating Priority','Priority To Assign Cranes By Skills Priority', 0, 1, 'System', GETDATE(), 3)
END
ELSE Print 'Relief Rule Rotation Process [Skill And Crane Rating Priority] Already Exists'
GO

--Validate Whether Allocation Factor 'Relief Rule Rotation' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 16) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (16, N'Nationality','Allocation Factor For Nationality', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Nationality] Already Exists'
GO

--Validate Whether Allocation Factor 'Relief Rule Rotation' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 17) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (17, N'Religion','Allocation Factor For Religion', 0, 1, 'System', GETDATE(), 0)
END
ELSE Print 'Allocation Factor [Religion] Already Exists'
GO

--Validate Whether Allocation Factor 'Overrid' Exists Or Not
IF NOT EXISTS (SELECT * FROM J_AllocationFactor WHERE FactorId = 18) 
BEGIN
	INSERT [dbo].[J_AllocationFactor] ([FactorId], [FactorName], [FactoryDesc], [FactorValue], [ActiveStatus], [CreatedBy], [CreatedDate], [FactorType]) 
	VALUES (18, N'Override PMO Locations By Gender','Set to 1 To make PMO Female operators to assign at single location.', 0, 1, 'System', GETDATE(), 2)
END
ELSE Print 'Override PMO Locations By Gender [Override And Optimize Allocation With PMO Female Operators Location] Already Exists'
GO

SET IDENTITY_INSERT [dbo].[W_Modules] ON 
GO

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 201)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate)
	VALUES (201, N'Leave', N'Leave Module', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE())
	Print 'Workflow Module [Leave] Added'
END
Else
BEGIN
	UPDATE	W_Modules
	SET		ModuleName		=	N'Leave',
			ModuleDesc		=	N'Leave Module',
			TableName		=	N'L_Leaves',
			TransIdName		=	N'LeaveId',
			ViewURL			=	N'',
			ActiveStatus	=	1
	WHERE	(ModuleId		=	201)
	Print 'Workflow Module [Leave] Updated'
END
GO

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 202)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate)
	VALUES (202, N'Request Leave', N'Request Day In Lieu', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE())
	Print 'Workflow Module [Request Days In Lieu] Added'
END
Else
BEGIN
	UPDATE	W_Modules
	SET		ModuleName		=	N'Request Leave',
			ModuleDesc		=	N'Request Day In Lieu',
			TableName		=	N'L_Leaves',
			TransIdName		=	N'LeaveId',
			ViewURL			=	N'',
			ActiveStatus	=	1
	WHERE	ModuleId		=	202
	Print 'Workflow Module [Request Days In Lieu] Updated'
END
GO

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 203)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate)
	VALUES (203, N'Time Off', N'Request Time Off', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE())
	Print 'Workflow Module [Request Time Off] Added'
END
Else
BEGIN
	UPDATE	W_Modules
	SET		ModuleName		=	N'Time Off',
			ModuleDesc		=	N'Request Time off',
			TableName		=	N'L_Leaves',
			TransIdName		=	N'LeaveId',
			ViewURL			=	N'',
			ActiveStatus	=	1
	WHERE	ModuleId		=	203
	Print 'Workflow Module [Leave] Updated'
END
GO

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 204)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate)
	VALUES (204, N'Time Attendance', N'Time Attendance Module', N'S_Shifts', N'ShitId', N'', 1, 'System', GETDATE())
	Print 'Workflow Module [Time Attendance] Added'
END
Else
BEGIN
	UPDATE	W_Modules
	SET		ModuleName		=	N'Time Attendance',
			ModuleDesc		=	N'Time Attendance Module',
			TableName		=	N'S_Shifts',
			TransIdName		=	N'ShiftId',
			ViewURL			=	N'',
			ActiveStatus	=	1
	WHERE	(ModuleId		=	204)
	Print 'Workflow Module [Time Attendance] Updated'
END
GO

--Validate Whether special Leave exists or not
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 205)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate)
	VALUES (205, N'UnControlledLeave', N'Leave Mdoule', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE())
	Print 'Workflow Module [UnControlledLeave] Added'
END
GO

--Validate Whether special Leave exists or not
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 206)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate, LeaveCodes)
	VALUES (206, N'SpecialLeave', N'Leave Mdoule', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE(),'SL')
	Print 'Workflow Module [SpecialLeave] Added'
END
GO

--Validate Whether special Leave exists or not
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 207)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate,LeaveCodes)
	VALUES (207, N'UnpaidLeave', N'Leave Mdoule', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE(),'UML,UPL')
	Print 'Workflow Module [UnpaidLeave] Added'
END
GO

--Validate Whether special Leave exists or not
IF NOT EXISTS (SELECT * FROM W_Modules WHERE ModuleId = 208)
BEGIN
	INSERT INTO W_Modules
	(ModuleId, ModuleName, ModuleDesc, TableName, TransIdName, ViewURL, ActiveStatus, CreatedBy, CreatedDate,LeaveCodes)
	VALUES (208, N'HajLeave', N'Leave Mdoule', N'L_Leaves', N'LeaveId', N'', 1, 'System', GETDATE(),'HAJ')
	Print 'Workflow Module [UnpaidLeave] Added'
END
GO

SET IDENTITY_INSERT [dbo].[W_Modules] OFF
GO

--Insert D_Exception Type
SET IDENTITY_INSERT [dbo].[D_ExceptionType] ON 
GO

IF NOT EXISTS(SELECT * FROM D_ExceptionType WITH (NOLOCK) WHERE ExceptionTypeId = 1)
BEGIN
	
	INSERT INTO D_ExceptionType
	(ExceptionTypeId, ExceptionTypeName, ExceptionTypeDesc, CreatedBy, CreatedDate)
	VALUES(1, N'Attendance','Attendance Exception','System',GETDATE())
END
GO

IF NOT EXISTS(SELECT * FROM D_ExceptionType WITH (NOLOCK) WHERE ExceptionTypeId = 2)
BEGIN
	
	INSERT INTO D_ExceptionType
	(ExceptionTypeId, ExceptionTypeName, ExceptionTypeDesc, CreatedBy, CreatedDate)
	VALUES(2, N'Leave','Leave Exception','System',GETDATE())
END
GO

IF NOT EXISTS(SELECT * FROM D_ExceptionType WITH (NOLOCK) WHERE ExceptionTypeId = 3)
BEGIN
	
	INSERT INTO D_ExceptionType
	(ExceptionTypeId, ExceptionTypeName, ExceptionTypeDesc, CreatedBy, CreatedDate)
	VALUES(3, N'Uncontrolled Leave','Uncontrolled Leave Exception','System',GETDATE())
END
GO

IF NOT EXISTS(SELECT * FROM D_ExceptionType WITH (NOLOCK) WHERE ExceptionTypeId = 4)
BEGIN
	
	INSERT INTO D_ExceptionType
	(ExceptionTypeId, ExceptionTypeName, ExceptionTypeDesc, CreatedBy, CreatedDate)
	VALUES(4, N'Exclude Deployment','Exclude Deployment Exception','System',GETDATE())
END
GO

SET IDENTITY_INSERT [dbo].[D_ExceptionType] OFF
GO

SET IDENTITY_INSERT [dbo].[D_EmailTemplate] ON 

-- Template ID = 1 Leave Pending For Approval
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 1 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	1, 1, 1, 'Leave Pending For Approval', '<p>Dear <strong>[ApproverName]</strong></p><p>Leave has been submitted by <strong>[EmployeeNumber]</strong> <strong>-</strong> <strong>[EmployeeName]</strong> for your approval, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to approve/reject</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Pending Leave Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]' 
	Where TemplateId = 1
END

-- Template ID = 2 Leave Approved
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 2 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	2, 1, 2, 'Leave Approved', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your leave application submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(0, 138, 0);">Approved</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending and approved leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Approved Leave Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]' 
	Where TemplateId = 2
END

-- Template ID = 3 Leave Rejected
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 3 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	3, 1, 3, 'Leave Rejected', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your leave application submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(230, 0, 0);">Rejected</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending, approved and rejected leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Rejected Leave Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 3
END

-- Template ID = 4 Leave Cancellation Pending For Approval
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 4 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	4, 1, 4, 'Leave Cancellation Request Pending For Approval', '<p>Dear <strong>[ApproverName]</strong></p><p>Leave cancellation request has been submitted by <strong>[EmployeeNumber]</strong> <strong>-</strong> <strong>[EmployeeName]</strong> for your approval, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to approve/reject</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Pending Leave Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 4
END

-- Template ID = 5 Leave Cancellation Request Approved
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 5 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	5, 1, 5, 'Leave Cancellation Request Approved', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your leave cancellation request submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(0, 138, 0);">Approved</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending and approved leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Approved Leave Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 5
END

-- Template ID = 6 Leave Rejected
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 6 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	6, 1, 6, 'Leave Cancellation Request Rejected', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your leave cancellation request submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(230, 0, 0);">Rejected</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending, approved and rejected leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(), '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Rejected Leave Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [ToDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 6
END

-- Template ID = 7 Time Off Pending For Approval
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 7 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	7, 1, 7, 'Time Off Pending For Approval', '<p>Dear <strong>[ApproverName]</strong></p><p>Time Off request has been submitted by <strong>[EmployeeNumber]</strong> <strong>-</strong> <strong>[EmployeeName]</strong> for your approval, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to approve/reject</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Pending Time Off Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 7
END

-- Template ID = 8 Time Off Approved
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 8 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	8, 1, 8, 'Time Off Approved', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your Time Off application submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(0, 138, 0);">Approved</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending and approved leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(), '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Approved Time Off Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 8
END

-- Template ID = 9 Time Off Rejected
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 9 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES( 9, 1, 9, 'Time Off Rejected', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your Time Off application submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(230, 0, 0);">Rejected</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending, approved and rejected leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(), '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Rejected Time Off Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 9
END

-- Template ID = 10 Time Off Cancellation Pending For Approval
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 10 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	10, 1, 10, 'Time Off Cancellation Request Pending For Approval', '<p>Dear <strong>[ApproverName]</strong></p><p>Time Off cancellation request has been submitted by <strong>[EmployeeNumber]</strong> <strong>-</strong> <strong>[EmployeeName]</strong> for your approval, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to approve/reject</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Pending Time Off Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApproverName] [EmployeeNumber] [EmployeeName] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 10
END

-- Template ID = 11 Time Off Cancellation Request Approved
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 11 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	11, 1, 11, 'Time Off Cancellation Request Approved', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your Time Off cancellation request submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(0, 138, 0);">Approved</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending and approved leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(), '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Approved Time Off Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 11
END

-- Template ID = 12 Time Off Rejected
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 12 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	12, 1, 12, 'Time Off Cancellation Request Rejected', '<p>Dear <strong>[ApplicantName]</strong></p><p>Your Time Off cancellation request submitted on <strong>[AppliedDate] </strong>has been <strong style="color: rgb(230, 0, 0);">Rejected</strong>, below are the leave details</p><p>Leave Type			:		<strong>[LeaveCodeAndDescription]</strong></p><p>From Date				:		<strong>[FromDate]</strong></p><p>To Date					:		<strong>[ToDate]</strong></p><p>No. Of Days			:		<strong>[NoOfDays]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to check pending, approved and rejected leave(s)</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),  '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]')

	Print 'Rejected Time Off Cancellation Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions =  '[ApplicantName] [AppliedDate] [LeaveCodeAndDescription] [FromDate] [NoOfDays] [ApplicationUrlString]'
	Where TemplateId = 12
END

-- Template ID = 19 Send Temporary Password Email
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 19 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	19, 1, 19, 'Eltizam - Temporary Password', '<p>Dear <strong>[ApplicantName]</strong></p><p>A temporary password has been requested for your Eltizam account, and the password is</p><p><strong>[TemporaryPassword]</strong></p><p>You will be prompted to change password on next login<p>This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(), '[ApplicantName] [TemporaryPassword]')

	Print 'Reset Password Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions =  '[ApplicantName] [TemporaryPassword]'
	Where TemplateId = 19
END

-- Template ID = 20 On Behalf Leave Granted
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 20 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	20, 1, 20, 'Leave Granted', '<p>Dear All</p><p><strong><u>[LeaveCodeAndDescription]</u></strong> has been <strong style="color: rgb(0, 138, 0);">Granted</strong> To <strong>[EmployeeNumber] - [EmployeeName]</strong> For <strong>[NoOfDays]</strong> Day(s) Between <strong>[FromDate] - [ToDate]</strong></p><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong> for more information</p><p>Thank you, </p><p><strong style="color: rgb(34, 34, 34);">This is a system generated email, please do not reply.</strong></p>', 
			NULL, '[Eltizam] - ESS', 1, 'System', GETDATE(),'[LeaveCodeAndDescription] [EmployeeNumber] [EmployeeName] [NoOfDays] [FromDate] [ToDate] [ApplicationUrlString]')

	Print 'OnBehalf Leave Template For English Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[LeaveCodeAndDescription] [EmployeeNumber] [EmployeeName] [NoOfDays] [FromDate] [ToDate] [ApplicationUrlString]'
	Where TemplateId = 20
END

-- Template ID = 21 Send Probation Period Expiry Details
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 21 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	21, 1, 21, 'Eltizam - Probation Expiry Details', '<p>Dear <strong>All</strong></p><p>Please find the document attached for your reference in regards to subject above.</p><p>This is a system generated email, please do not reply.</p>', 
			NULL, '[Eltizam] - Automated Email', 1, 'System', GETDATE(), '')

	Print 'Probation Period Expiry Details Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = ''
	Where TemplateId = 21
END

-- Template ID = 22 Send Pending Leave Applications By Approver
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 22 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	22, 1, 22, 'Eltizam - Pending Applications For Approval', '<p>Dear <strong>[ApproverName]</strong></p><p>Below are the application pending for your approval </p><p>[PendingApplications]</p><br/><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to approve/reject</p><p>This is a system generated email, please do not reply.</p>', 
			'info@eltizam.com', '[Eltizam] - Automated Email', 1, 'System', GETDATE(),'[ApproverName] [PendingApplications] [ApplicationUrlString]')

	Print 'Pending Applications For Approval Details Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[ApproverName] [PendingApplications] [ApplicationUrlString]'
	Where TemplateId = 22
END

-- Template ID = 22 Send Pending Leave Applications By Approver
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 23 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	23, 1, 23, 'Eltizam - Deployment', '<p>Dear <strong>Team</strong></p><p>Deployment Process [DeploymentDate] For [StartTime] And [EndTime] has been completed.</p><p>[PendingApplications]</p><br/><p>Please login to <a href="[ApplicationUrlString]" target="_blank"><strong>Eltizam</strong></a><strong> </strong>to verify</p><p>This is a system generated email, please do not reply.</p>', 
			'info@eltizam.com', '[Eltizam] - Automated Email', 1, 'System', GETDATE(),'[DeploymentDate] [StartTime] [EndTime] [ApplicationUrlString]')

	Print 'Deployment Email Template Created Successfully...'
END
ELSE
BEGIN
	UPDATE D_EmailTemplate SET AvailableOptions = '[DeploymentDate] [StartTime] [EndTime] [ApplicationUrlString]'
	Where TemplateId = 23
END

-- Template ID = 24 Send Pending Leave Applications By Approver
IF NOT EXISTS (SELECT * FROM D_EmailTemplate WHERE FunctionId = 24 And LanguageId = 1) 
BEGIN
	INSERT D_EmailTemplate
	(TemplateId, LanguageId, FunctionId, MailSubject, MailBody, MailCC, MailFrom, ActiveStatus, CreatedBy, CreatedDate, AvailableOptions)
	VALUES(	24, 1, 24, 'Interface Exception Details', '<p>Dear <strong>All</strong></p><p>Please find the below details for the exception/error occured in the Interface Process<br/>[ErrorMessage].</p><p>This is a system generated email, please do not reply.</p>',
			NULL, '[Eltizam] - Automated Email', 1, 'System', GETDATE(),'')

	Print 'Interface Exception Details Email Template Created Successfully...'
END

SET IDENTITY_INSERT [dbo].[D_EmailTemplate] OFF
GO

SET IDENTITY_INSERT [dbo].[D_Messages] ON 

-- Template For New Leave Application Notification
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 1 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(1, 'Leave Application','Leave Application Submission', 1, 'ApplyLeave', 1, NULL, 
		   'New Leave Application',
		   '[ExceptionCode] application submitted by [EmployeeNumber] - [EmployeeName] between [LeaveStartDate] to [LeaveEndDate]',
		   'PushMessageIcon',
		   'New Leave Application',
		   '[ExceptionCode] application submitted by [EmployeeNumber] - [EmployeeName] between [LeaveStartDate] to [LeaveEndDate]',
		   'fas fa-truck-monster bg-secondary', '<div data-module-id=104 data-kioskid=214 data-menu-id=359></div>', 'SelfService/Transcations/PendingTranscationsIndex', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For New Leave Application created successfully'
END

-- Template For Approved Leave Notification
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 2 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(2, 'Leave Approved','Leave Application Approved', 2, 'ApproveLeave', 1, NULL, 
		   'Leave has been approved',
		   '[ExceptionCode] application between [LeaveStartDate] to [LeaveEndDate] has been approved.',
		   'PushMessageIcon',
		   'Leave has been approved',
		   '[ExceptionCode] application between [LeaveStartDate] to [LeaveEndDate] has been approved.',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/LeaveRecords', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Leave Application Approved Successfully'
END

-- Template For Rejected Leave Notification
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 10 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(3, 'Leave Rejected','Leave Application Rejected', 10, 'RejectLeave', 1, NULL, 
		   'Leave has been rejected',
		   '[ExceptionCode] application between [LeaveStartDate] to [LeaveEndDate] has been rejected.',
		   'PushMessageIcon',
		   'Leave has been rejected',
		   '[ExceptionCode] application between [LeaveStartDate] to [LeaveEndDate] has been rejected.',
		   'NotificationIcon', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/LeaveRecords', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Leave Application Has Been Rejected'
END

-- Template For Time Off Application
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 3 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(4, 'Time Off Application','Time Off Application Submission', 3, 'ApplyTimeOff', 1, NULL, 
		   'New Time Off Application',
		   '[ExceptionCode] application has been submitted by [EmployeeNumber] - [EmployeeName] From [LeaveStartDate] To [LeaveEndDate]',
		   'PushMessageIcon',
		   'New Time Off Application',
		   '[ExceptionCode] application has been submitted by [EmployeeNumber] - [EmployeeName] From [LeaveStartDate] To [LeaveEndDate]',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=357></div>', 'SelfService/Transactions/PendingTimeOffIndex', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For New Time Off Application Successfully Created'
END

-- Template For Approved Time Off Application
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 4 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(5, 'Time Off Approved','Time Off Application Approved', 4, 'ApproveTimeOff', 1, NULL, 
		   'Time Off has been approved',
		   '[ExceptionCode] On [LeaveStartDate] for [NoOfDays] Hour(s) has been approved.',
		   'PushMessageIcon',
		   'Time Off has been approved',
		   '[ExceptionCode] On [LeaveStartDate] for [NoOfDays] Hour(s) has been approved.',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/LeaveRecords', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Time Off Approved Created Successfully'
END

-- Template For Request Days In Lieu Application
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 5 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(6, 'Request Days In Lieu Application','Request Days In Lieu Application Submission', 5, 'ApplyRequestDaysInLieu', 1, NULL, 
		   'New Request Days In Lieu Application',
		   '[ExceptionCode] application has been submitted by [EmployeeNumber] - [EmployeeName] On [LeaveStartDate]',
		   'PushMessageIcon',
		   'New Request Days In Lieu Application',
		   '[ExceptionCode] application has been submitted by [EmployeeNumber] - [EmployeeName] On [LeaveStartDate]',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=358></div>', 'SelfService/Transactions/PendingDaysInLieuIndex', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For New Request Days In Lieu Application Successfully Created'
END

-- Template For Approved Request Days In Lieu Application
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 6 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(7, 'Request Days In Lieu Approved','Request Days In Lie Application Approved', 6, 'ApproveRequestDaysInLieu', 1, NULL, 
		   'Request Days In Lieu has been approved',
		   '[ExceptionCode] On [LeaveStartDate] has been approved.',
		   'PushMessageIcon',
		   'Request Days In Lieu has been approved',
		   '[ExceptionCode] On [LeaveStartDate] has been approved.',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/LeaveRecords', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Request Days In Lieu Approved Created Successfully'
END

--Template For Rejected Time Off

--Template For Rejected Request Days In Lieu

-- Template For Deployment Process
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 7 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(8, 'Deployment Completed','Deployment Process has been completed.', 7, 'SuccessfulDeployment', 1, NULL, 
		   'Deployment Completed',
		   'Deployment For [DeploymentDate] Between [ShiftStartTime] And [ShiftEndTime] has been completed.',
		   'PushMessageIcon',
		   'Deployment Completed',
		   'Deployment For [DeploymentDate] Between [ShiftStartTime] And [ShiftEndTime] has been completed.',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/LeaveRecords', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Deployment Process Created Successfully'
END

-- Template For UnControlled Leave Application Submission
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 22 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(9, 'Uncontrolled Leave','Uncontrolled leave has been submitted.', 22, 'Uncontrolled Leave Submitted', 1, NULL, 
		   'Uncontrolled Leave',
		   'Uncontrolled Leave [ExceptionCode] Has Been Submitted By [EmployeeNumber]-[EmployeeName] For [LeaveStartDate].',
		   'Uncontrolled Leave',
		   'Uncontrolled Leave',
		   'Uncontrolled Leave [ExceptionCode] Has Been Submitted By [EmployeeNumber]-[EmployeeName] For [LeaveStartDate].',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/UncontrolledLeave', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Uncontrolled Leave Submission Created Successfully'
END

-- Template For UnControlled Leave Application Submission
IF NOT EXISTS (SELECT * FROM D_Messages WHERE MessageModuleId = 23 And LanguageId = 1) 
BEGIN
	INSERT INTO D_Messages
	(MessageId, MessageCode, MessageName, MessageModuleId, MessageModuleName, LanguageId, EmailTemplateId, PushMessageHeader, PushMessageDetails, 
	 PushMessageIcon, NotificationHeader, NotificationDetails, NotificationIcon, NavigationUrlWeb, NavigationUrlMobile,
	 ActiveStatus, IsEmail, IsMobileNotification, IsWebNotification, CreatedBy, CreatedDate)
	VALUES(23, 'Broadcast Deployment','Broadcast Deployment Details By Employee.', 23, 'Broadcast Deployment', 1, NULL, 
		   'Broadcast Deployment',
		   'Dear [EmployeeNumber] - [EmployeeName], you have been deployed to [ShiftBand] [StartTime] [EndTime] for Vessel [VesselName] Starts [VesselStartTime], Ends [VesselEndTime] [FirstActivityStartTime] [LastActivityEndTime] [FirstEquipment] [StartLocation] [LastEquipment] [EndLocation] [ShiftNotes]',
		   'fas fa-calendar-check bg-success',
		   'Broadcast Deployment',
		   'Dear [EmployeeNumber] - [EmployeeName], you have been deployed to [ShiftBand] [StartTime] [EndTime] for Vessel [VesselName] Starts [VesselStartTime], Ends [VesselEndTime] [FirstActivityStartTime] [LastActivityEndTime] [FirstEquipment] [StartLocation] [LastEquipment] [EndLocation] [ShiftNotes]',
		   'fas fa-calendar-check bg-success', '<div data-module-id=104 data-kioskid=214 data-menu-id=353></div>', 'SelfService/DeploymentDetails', 1, 0, 1, 1, 'System',GETDATE())

	Print 'Notification Template For Broadcast Deployment Created Successfully'
END

SET IDENTITY_INSERT [dbo].[D_Messages] OFF
GO

BEGIN
	DECLARE @SecurityRoleId BigInt = 0, @MessageId BigInt = 0

	DECLARE MessagesCursor CURSOR FOR
	SELECT	MessageId 
	FROM	D_Messages WITH (NOLOCK)

	OPEN MessagesCursor
	FETCH NEXT FROM MessagesCursor INTO @MessageId

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		DECLARE SecurityRoleCursor CURSOR FOR
		SELECT	SecurityRoleID
		FROM	C_SecurityRole WITH (NOLOCK)

		OPEN SecurityRoleCursor 
		FETCH NEXT FROM SecurityRoleCursor  INTO @SecurityRoleId

		WHILE @@FETCH_STATUS = 0
		BEGIN
			If NOT EXISTS (SELECT * FROM D_MessageSecurityRole WITH (NOLOCK) WHERE SecurityRoleId = @SecurityRoleId AND MessageId = @MessageId)
			BEGIN
				INSERT INTO D_MessageSecurityRole
				(SecurityRoleId, MessageId, StartDate, EndDate, CreatedBy, CreatedDate)
				VALUES(@SecurityRoleId, @MessageId, '2021-01-01 00:00:00','9999-12-31 23:59:59', 'System',GETDATE())

			END
			FETCH NEXT FROM SecurityRoleCursor INTO @SecurityRoleId
		END

		CLOSE SecurityRoleCursor
		DEALLOCATE SecurityRoleCursor

		FETCH NEXT FROM MessagesCursor INTO @MessageId
	END

	CLOSE MessagesCursor
	DEALLOCATE MessagesCursor
END
GO

BEGIN
	DECLARE @UserId BigInt = 0, @SecurityRoleId BigInt = 0, @MessageSecurityRoleId BigInt = 0, 
			@EmployeeId BigInt = 0, @MessageId BigInt = 0

	DECLARE UserSecurityRoleCursor CURSOR FOR
	SELECT	DISTINCT C_UserSecurityRole.UserId, SecurityRoleId, C_User.EmployeeID
	FROM	C_UserSecurityRole WITH (NOLOCK) 
			INNER JOIN C_User WITH  (NOLOCK) ON C_UserSecurityRole.UserId = C_User.UserID
	WHERE	EmployeeID IS NOT NULL
	--WHERE	EmployeeID =  1315

	OPEN UserSecurityRoleCursor
	FETCH NEXT FROM UserSecurityRoleCursor INTO @UserId, @SecurityRoleId, @EmployeeId

	WHILE @@FETCH_STATUS = 0
	BEGIN
	
		DECLARE MessageSecurityRoleCursor CURSOR FOR 
		SELECT	D_MessageSecurityRole.MessageSecurityRoleId,
				D_MessageSecurityRole.MessageId
		FROM	D_MessageSecurityRole WITH (NOLOCK) 
		WHERE	D_MessageSecurityRole.SecurityRoleId = @SecurityRoleId

		OPEN MessageSecurityRoleCursor
		FETCH NEXT FROM MessageSecurityRoleCursor INTO @MessageSecurityRoleId, @MessageId

		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF NOT EXISTS (SELECT EmployeeId FROM C_EmployeeMessages WITH (NOLOCK) WHERE EmployeeId = @EmployeeId AND MessageSecurityRoleId = @MessageSecurityRoleId AND MessageId = @MessageId)
			BEGIN
				INSERT INTO C_EmployeeMessages
				(MessageSecurityRoleId, EmployeeId, MessageId, EnableMessages, EnableEmails, EnablePushNotifications,
				 IsMessagesDisabledByUser, IsEmailDisabledByUser, IsPushNotificationsDisabledByUser, 
				 MessagesDisabledDate, EmailDisabledDate, PushNotificationsDisabledDate,
				 ActiveStatus, CreatedBy, CreatedDate)
				VALUES(@MessageSecurityRoleId, @EmployeeId, @MessageId, 1, 1, 1, 0, 0, 0, NULL, NULL, NULL, 1, 'System', GETDATE())
			END

			FETCH NEXT FROM MessageSecurityRoleCursor INTO @MessageSecurityRoleId, @MessageId
		END

		CLOSE MessageSecurityRoleCursor
		DEALLOCATE MessageSecurityRoleCursor

		FETCH NEXT FROM UserSecurityRoleCursor  INTO @UserId, @SecurityRoleId, @EmployeeId
	END
	CLOSE UserSecurityRoleCursor
	DEALLOCATE UserSecurityRoleCursor
END
GO

DECLARE @RosterGroupId BigInt = 0, @TemplateId BigInt = 0

DECLARE RosterGroup_Cursor CURSOR FOR
SELECT	RosterGroupId
FROM	S_RosterGroup WITH (NOLOCK) 
ORDER BY RosterGroupId

OPEN RosterGroup_Cursor
FETCH NEXT FROM RosterGroup_Cursor INTO @RosterGroupId

WHILE @@FETCH_STATUS = 0
BEGIN
	SELECT  TOP 1 @TemplateId = TemplateId 
	FROM	S_TemplateRosterLine WITH (NOLOCK)
	WHERE	RosterGroupId = @RosterGroupId
	--AND	LastPublishDate IS NOT NULL
	ORDER BY S_TemplateRosterLine.LastPublishDate DESC


	UPDATE S_RosterGroup SET TemplateId = @TemplateId Where RosterGroupId = @RosterGroupId

	UPDATE C_EmployeeMovement SET TemplateId = @TemplateId WHERE RosterGroupId = @RosterGroupId

	SET @TemplateId = NULL
	--PRINT 'Template Id is ' + Convert(nVarchar(10),@TemplateId) + ' For Roster Group Id ' + Convert(nVarchar(10),@RosterGroupId)

	FETCH NEXT FROM RosterGroup_Cursor INTO @RosterGroupId
END

CLOSE RosterGroup_Cursor
DEALLOCATE RosterGroup_Cursor

SET IDENTITY_INSERT [dbo].[L_Validations] ON 

-- Validation Id = 1 Validate Haj Leave Process 
IF NOT EXISTS (SELECT * FROM L_Validations WHERE ValidationId  = 1) 
BEGIN
	IF EXISTS (SELECT * FROM D_ExceptionCodes WITH (NOLOCK) Where ExceptionCodeId = 1)
	BEGIN
		INSERT L_Validations
		(ValidationId, ExceptionCodeId, ProcedureToExecute, ActiveStatus, CreatedBy, CreatedDate)
		VALUES(1, 1, 'prL_ValidateHajLeave',1,'System',GETDATE())
	
		Print 'Annual Leave End Date Validation Created Successfully...'
	END
END

SET IDENTITY_INSERT [dbo].[L_validations] OFF
GO


-- Create Acting Incentive Record For Stevedore Position
IF NOT EXISTS (SELECT * FROM P_ActingIncentiveRates WHERE PositionId  = (SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='Stevedore')) 
BEGIN
	INSERT INTO P_ActingIncentiveRates(PositionId,IncentiveRate,CreatedBy,CreatedDate,UpdatedBy,UpdatedDate)
	VALUES((SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='Stevedore') ,2,'Data',getdate()  ,'Data Update',getdate())
END
GO

-- Create Acting Incentive Record For YHE Operator Position
IF NOT EXISTS (SELECT * FROM P_ActingIncentiveRates WHERE PositionId  = (SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='YHE Operator')) 
BEGIN
	INSERT INTO P_ActingIncentiveRates(PositionId,IncentiveRate,CreatedBy,CreatedDate,UpdatedBy,UpdatedDate)
	VALUES((SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='YHE Operator') ,4,'Data',getdate()  ,'Data Update',getdate())
END
GO

-- Create Activing Incentive Records For TT Driver Position
IF NOT EXISTS (SELECT * FROM P_ActingIncentiveRates WHERE PositionId  = (SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='Driver')) 
BEGIN
	INSERT INTO P_ActingIncentiveRates(PositionId,IncentiveRate,CreatedBy,CreatedDate,UpdatedBy,UpdatedDate)
	VALUES((SELECT CodeId FROM d_mastercodes WHERE CodeType = 'Position' and codevalue='TT Driver') ,3,'Data',getdate()  ,'Data Update',getdate())
END
GO



SET IDENTITY_INSERT [dbo].[S_ShiftValidationCodes] ON 
GO

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 1) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (1, N'001', N'Minimum Time Difference Between Shift Actual Start and Actual End Should match Minimum length of Schedule Period', N'Minimum Shift Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 2) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (2, N'002', N'Maximum Time Difference Between Shift Actual Start and End Should match Maximum length of Schedule Period Rule', N'Maxminum Shift Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 3) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (3, N'003', N'Minimum No of Shifts Per Period Should match with Schedule Period Shifts per Period Rule.', N'Minimum Shifts Per Period of %NoOfDays% days breached.', N'#FF0000', NULL, NULL)
END


IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 4) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (4, N'004', N'Maximum No of Shifts Per Period Should match with Schedule Period Shifts per Period Rule.', N'Maximum Shifts per Period of %NoOfDays% days breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 5) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (5, N'005', N'Total Number of Minimum working hours per Period should match with Schedule Period Total Working Hours per Period Rule.', N'Minimum Time per Period of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 6) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (6, N'006', N'Total Number of Maximum working hours per Period should match with Schedule Period Total Working Hours per Period Rule.', N'Maximum Time per Period of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 7) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (7, N'007', N'Minimum Continuous Shift Days must match with Schedule Period Minimum Continuous Days', N'Minimum Continuous Days Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 8) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (8, N'008', N'Maximum Continuous Shift Days must match with Schedule Period Maximum Continuous Days', N'Maximum Continuous Days Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 9) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (9, N'009', N'Minimum Continuous Off Days must match with Schedule Period Minimum Continuous Days Off', N'Minimum Continuous Off Days Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 10) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate])
	VALUES (10, N'010', N'Maximum Continuous Off Days must match with Schedule Period Maximum Continuous Days Off', N'Maximum Continuous Off Days Length of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 11) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (11, N'011', N'Minimum Continuous Shifts Should match with Schedule Period Shift Band Minimum Continuous Shifts', N'Minimum Continuous Shifts of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END


IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 12) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (12, N'012', N'Maximum Continuous Shifts Should match with Schedule Period Shift Band Maximum Continuous Shifts', N'Maximum Continuous Shifts of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 13) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (13, N'013', N'Minimum Continuous Off Days Between Two Different shift bands should match with Schedule Period Shift Band Minimum off days length.', N'Minimum Off Days Between Shifts of %NoOfDays% days breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 14) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (14, N'014', N'Maximum Continuous Off Days Between two different shift bands should match with Schedule Period Shift Band Maximum off days Length.', N'Maximum Off Days between Shifts of %NoOfDays% days breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 15) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate])
	VALUES (15, N'015', N'Minimum Rest Hours Between Two Shift Should match Minimum Shift Hours from Schedule Period Shift Band Minimum Rest Hours', N'Minimum Rest Hours of %NoOfDays% breached.', N'#FF0000', NULL, NULL)
END

IF NOT EXISTS (SELECT * FROM S_ShiftValidationCodes WHERE ErrorId  = 16) 
BEGIN
	INSERT [dbo].[S_ShiftValidationCodes] ([ErrorId], [ValidationCode], [ValidationDesc], [ValidationMessage], [ColorCode], [CreatedBy], [CreatedDate]) 
	VALUES (16, N'016', N'Shift Pattern Should Follow the Schedule Period Shift Band Order', N'Required Shift Pattern Not Followed.', N'#FF0000', NULL, NULL)
END

SET IDENTITY_INSERT [dbo].[S_ShiftValidationCodes] OFF
GO
SET IDENTITY_INSERT [dbo].[TA_ExceptionCodes] ON 
GO

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 1) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (1, N'Present', N'#1B5E20', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 2) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (2, N'Absent', N'#FF3D00', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 3) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (3, N'Leave', N'#FFD600', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 4) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (4, N'ClockInException', N'#EF5350', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 5) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (5, N'ClockOutException', N'#D50000', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 6) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (6, N'ClockInOutException', N'#C51162', NULL, NULL, GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 7) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate])
	VALUES (7, N'Payroll', N'#607D8B', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 8) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate])
	VALUES (8, N'Attendance', N'#64503C', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 9) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate])
	VALUES (9, N'Training', N'#64503C', 1, N'System', GETDATE())
END

IF NOT EXISTS (SELECT * FROM TA_ExceptionCodes WHERE TAExceptionId  = 10) 
BEGIN
	INSERT [dbo].[TA_ExceptionCodes] ([TAExceptionId], [TAException], [ColorCode], [ActiveStatus], [CreatedBy], [CreatedDate])
	VALUES (10, N'ReProcess', N'#64503C', 1, N'System', NULL)
END

SET IDENTITY_INSERT [dbo].[TA_ExceptionCodes] OFF
GO


SET IDENTITY_INSERT [dbo].[W_ApprovalStatus] ON 

--Validate Whether or not exists
IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 1)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(1,	'Approved', 'Approved')
	Print 'Added [Approved] Approval Status'
END
Else
BEGIN
	Print 'Approval Status [Approved] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 2)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(2,	'Rejected', 'Rejected')
	Print 'Added Approval Status [Rejected]'
END
Else
BEGIN
	Print 'Approval Status [Rejected] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 3)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(3,	'Pending', 'Application Pending')
	Print 'Added Approval Status [Pending]'
END
Else
BEGIN
	Print 'Approval Status [Pending] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 4)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(4,	'Cancel', 'Cancel')
	Print 'Added Approval Status [Cancel]'
END
Else
BEGIN
	Print 'Approval Status [Cancel] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 5)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(5,	'Cancel', 'Canceled (Cancellation Approved)')
	Print 'Added Approval Status [Canceled (Cancellation Approved)]'
END
Else
BEGIN	
	Print 'Approval Status [Canceled (Cancellation Approved)] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 6)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(6,	'Pending', 'Cancellation Pending')
	Print 'Added Approval Status [Cancellation Pending]'
END	
Else
BEGIN
	Print 'Approval Status [Cancellation Pending] Already Exists'
END

IF NOT EXISTS (SELECT * FROM W_ApprovalStatus WHERE	ApprovalStatusId = 7)
BEGIN
	INSERT INTO W_ApprovalStatus
	(ApprovalStatusId, ApprovalStatus, ApprovalStatusDesc)
	VALUES(7,	'Rejected', 'Approved (Cancellation Rejected)')
	Print 'Added Approval Status [Approved (Cancellation Rejected)]'
END
Else
BEGIN
	Print 'Approval Status [Approved (Cancellation Rejected)] Already Exists'
END


SET IDENTITY_INSERT [dbo].[W_ApprovalStatus] OFF

GO


BEGIN
	DECLARE @SecurityRoleID BigInt = 0, @RowCount Int = 0

	DECLARE Insert_New_Menu_Item CURSOR FOR
	SELECT DISTINCT SECURITYROLEID FROM C_SecurityRolePermissions

	OPEN Insert_New_Menu_Item
	FETCH NEXT FROM Insert_New_Menu_Item INTO @SecurityRoleID

	WHILE @@FETCH_STATUS = 0  
	BEGIN  
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 414 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 414, 0, 'System',GETDATE())
		END
		
		SET @RowCount = 0

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 423 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 423, 0, 'System',GETDATE())
		END

		SET @RowCount = 0

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 424 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 424, 0, 'System',GETDATE())
		END

		SET @RowCount = 0

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 425 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 425, 0, 'System',GETDATE())
		END

		SET @RowCount = 0

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 426 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 426, 0, 'System',GETDATE())
		END

		SET @RowCount = 0

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 427 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 427, 0, 'System',GETDATE())
		END
		
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 428 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 428, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 429 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 429, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 430 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 430, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 431 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 431, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 432 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 432, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 433 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 433, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 434 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 434, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 435 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 435, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 436 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 436, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 437 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 437, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 438 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 438, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 439 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 439, 0, 'System',GETDATE())
		END
		
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 440 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 440, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 441 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 441, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 442 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 442, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 443 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 443, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 444 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 444, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 445 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 445, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 446 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 446, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 447 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 447, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 448 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 448, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 449 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 449, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 450 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 450, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 451 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 451, 0, 'System',GETDATE())
		END
		
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 452 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 452, 0, 'System',GETDATE())
		END

	    SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 453 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 453, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 454 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 454, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 455 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 455, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 456 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 456, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 457 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 457, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 458 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 458, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 900 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 900, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 901 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 901, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 902 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 902, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 903 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 903, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 904 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 904, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 905 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 905, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 906 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 906, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 907 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 907, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 908 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 908, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 909 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 909, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 910 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 910, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 911 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 911, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 912 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 10425, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 913 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 10426, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 914 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 10427, 0, 'System',GETDATE())
		END

		--Vessel Schedule E10-355
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 920 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 920, 0, 'System',GETDATE())
		END

		--Employee Incentive E10-432
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 433 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 433, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 457 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 457, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 459 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 459, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 460 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 460, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 461 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 461, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 462 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 462, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 463 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 463, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 464 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 464, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 465 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 465, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 466 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 466, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 467 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 467, 0, 'System',GETDATE())
		END
	
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 462 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 462, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 463 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 463, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 471 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 471, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 472 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 472, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 473 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 473, 0, 'System',GETDATE())
		END

		
		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 474 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 474, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 475 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 475, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 476 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 476, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 477 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 477, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 478 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 478, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 479 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 479, 0, 'System',GETDATE())
		END

		SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 480 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 480, 0, 'System',GETDATE())
		END
		
	    SELECT @RowCount = Count(*) FROM C_SecurityRolePermissions WHERE MenuId = 481 AND SecurityRoleId = @SecurityRoleID	
		If (@RowCount = 0)
		BEGIN
			INSERT INTO C_SecurityRolePermissions
			(SecurityRoleId, MenuId, PermissionTypeId, CreatedBy, CreatedDate)
			VALUES(@SecurityRoleID, 481, 0, 'System',GETDATE())
		END

		FETCH NEXT FROM Insert_New_Menu_Item INTO @SecurityRoleID
	END 

	CLOSE Insert_New_Menu_Item
	DEALLOCATE Insert_New_Menu_Item

END
GO

IF NOT EXISTS (SELECT * FROM C_MiscellaneousColumns WHERE LabelName ='Shift Employee')
BEGIN
	INSERT INTO C_MiscellaneousColumns
	(ModuleId, LabelName, DataType, DefaultValue, IsMandatory, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(1, 'Shift Employee', 1, 0, 0, 1, 'System',GETDATE())
END
ELSE Print 'Miscellaneous Column [Shift Employee] Already Exists...'
GO

IF NOT EXISTS (SELECT * FROM C_MiscellaneousColumns WHERE LabelName ='Commodity')
BEGIN
	INSERT INTO C_MiscellaneousColumns
	(ModuleId, LabelName, DataType, DefaultValue, IsMandatory, ActiveStatus, CreatedBy, CreatedDate,SubModuleId)
	VALUES(2, 'Commodity', 2, '', 0, 1, 'System',GETDATE(),1)
END
ELSE Print 'Miscellaneous Column [Commodity] Already Exists...'

IF NOT EXISTS (SELECT * FROM C_MiscellaneousColumns WHERE LabelName ='Toonage')
BEGIN
	INSERT INTO C_MiscellaneousColumns
	(ModuleId, LabelName, DataType, DefaultValue, IsMandatory, ActiveStatus, CreatedBy, CreatedDate,SubModuleId)
	VALUES(2, 'Toonage', 2, '', 0, 1, 'System',GETDATE(),1)
END
ELSE Print 'Miscellaneous Column [Toonage] Already Exists...'

IF NOT EXISTS (SELECT * FROM C_MiscellaneousColumns WHERE LabelName ='Quantity')
BEGIN
	INSERT INTO C_MiscellaneousColumns
	(ModuleId, LabelName, DataType, DefaultValue, IsMandatory, ActiveStatus, CreatedBy, CreatedDate,SubModuleId) 
	VALUES(2, 'Quantity', 4, '', 0, 1, 'System',GETDATE(),1)
END
ELSE Print 'Miscellaneous Column [Quantity] Already Exists...'

IF NOT EXISTS (SELECT * FROM C_MiscellaneousColumns WHERE LabelName ='Remarks')
BEGIN
	INSERT INTO C_MiscellaneousColumns
	(ModuleId, LabelName, DataType, DefaultValue, IsMandatory, ActiveStatus, CreatedBy, CreatedDate,SubModuleId)
	VALUES(2, 'Remarks', 2, '', 0, 1, 'System',GETDATE(),1)
END
ELSE Print 'Miscellaneous Column [Remarks] Already Exists...'

GO

SET IDENTITY_INSERT [dbo].[C_InterfaceMaster] ON 

--Validate Whether Raw Clocking Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 1)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] ([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName], 
			     [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (1, N'Import', N'Rawclocking - File Import', N'Time and Attendance', N'File', N'CSV', N'-', 
			N'EMPNO,TYPE,SWIPEDATETIME,CARDNO,TERMINALNAME,LOCATIONNAME
			  14-00018,I,15/10/2018 18:00:09,001,,', 1, 
			'Script Migration', GETDATE())
	Print 'Raw Clocking - File Import Created'
END

--Validate Whether Employee Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 2)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],  
	[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (2, N'Import', N'Employee - Import', N'Employee', N'File', N'XLS, XLSX, CSV', N'-', 
			N'EmployeeNumber,BadgeNumber,FirstName,MiddleName,LastName,DateOfBirth,EmploymentBasis,MaritalStatus,Gender,
			Religion,Address1,Address2,Address3,City,PostCode,State,Country,HomePhone,MobilePhone,EmailAddress,HiredDate,Position,
			ScheduleRule,PayGroup,HourlyRate,ContractedHours,PrimaryRoleName,RosterGroupName,OUName,OTSettings,SecurityRole', 
			1, 'Script Migration', GETDATE())
	Print 'Employee - File Import Interface Row Created'
END

--Validate Whether Employee Leave Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 3)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName], 
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (3, N'Import', N'Employee Leave - File Import', N'Scheduler', N'File', N'XLS, XLSX, CSV', N'-', 
	 N'EmployeeNumber,LeaveCode,FromDate,ToDate,ApprovedBy,Remarks', 1, 'Script Migration', GETDATE())
	Print 'Employee Leave - File Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE C_InterfaceMaster SET FileType ='XLS, XLSX, CSV' Where InterfaceMasterId = 3
END

--Validate Whether Vessel Schedule File Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 4)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (4, N'Import', N'Vessel Schedule - File Import', N'Operations', N'File', N'XLS, XLSX', N'-', 
			 N'VesselName,VesselId,Berth,RequiredCranes,Priority,StartDateTime,EndDateTime', 
			 1, 'Script Migration', GETDATE())
	Print 'Vessel Schedule - File Import Interface Row Created'
END

--Validate Whether Vessel Schedule SQL Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 5)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName], 
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (5, N'Import', N'Vessel Schedule - SQL Database', N'Operations', N'SQL Connection', NULL, N'-', 
			   NULL, 1, 'Script Migration', GETDATE())
	Print 'Vessel Schedule - SQL Database Interface Row Created'
END

--Validate Whether Vessel Schedule SQL Import Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 6)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName], 
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (6, N'Import', N'Rawclocking - SQL Database', N'Time Attendance', N'SQL Connection', NULL, N'-', 
			   NULL, 1, 'Script Migration', GETDATE())
	Print 'Rawclocking - SQL Database Interface Row Created'
END

-- Validate Whether Box Movement Summary Interface Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 7)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (7, N'Import', N'TOS Productivity Summary', N'TOS Productivity Summary', N'Import From Excel', 'XLS, XLSX', N'-', 
			  'Date, ShiftBand, CMPHTarget, CMPHActual, PMPHTarget, PMPHActual, MovesTarget, MovesActual, ActualGang',
			  1, 'System', GETDATE())
	Print 'TOS Productivity Summary'
END

-- Validate Whether Probation Email Notification Interface Exists, If Not Exists Create 
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 8)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (8, N'Email', N'Probation Expiry - Email Notification',  N'Automated Email Process', N'EmailAttachment', NULL, N'-', 
			  NULL, 1, 'Administrator', GETDATE())
	Print 'Probation Expiry - Email Notification. Interface Created'
END

-- Validate Whether Probation Email Notification Interface Exists, If Not Exists Create 
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 9)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (9, N'Email', N'Pending Leave Report - Email Notification',  N'Automated Email Process', N'EmailAttachment', NULL, N'-', 
			  NULL, 1, 'Administrator', GETDATE())
	Print 'Pending Leave Report - Email Notification. Interface Created'
END

-- Validate Whether Equipment Import Interface Eixsts. If Not Exists Create.
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 10)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (10, N'Import', N'Equipment Schedule - File Import', N'Operations', N'File', N'XLS,XLSX,TXT', N'-', 
			  N'EquipmentType,EquipmentName,CranNumber,StartDateTime,EndDateTime', 
			 1, 'System', GETDATE())
	Print 'Equipment Schedule - File Import Interface Row Created'
END

-- Validate whether Equipment Import Interface Direct Database Connection Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 11)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (11, N'Import', N'Equipment Schedule - SQL Database', N'Equipment Schedule', N'SQL Connection', NULL, N'-', 
			   NULL, 1, 'System', GETDATE())
	Print 'Equipment Schedule- SQL Database Interface Row Created'
END

-- Validate whether Equipment Maintenance Interface File Import Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 12)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (12, N'Import', N'Equipment Schedule - File Import', N'Equipment Schedule', N'FILE', 'TXT', N'-', 
			   NULL, 1, 'System', GETDATE())
	Print 'Equipment Schedule - File Import Interface Row Created'
END
ELSE
BEGIN
    UPDATE  [dbo].[C_InterfaceMaster] 
	SET Name       =  N'Equipment Maintenance',
	    FileType   =  N'XLS,XLSX,CSV',
		FileFormat =  N'Equipment Type, Equipment Name, StartDate,EndDate, Reason, CreatedBy    
		              Crane,Q36,29/09/2021,30/09/2021,Scheduled,Admin' 
	Where InterfaceMasterId = 12
	Print 'Equipment Maintenance - Row Updated'
END

-- Validate whether Equipment Shift - File Import Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 13)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES(13, N'Import',N'Shifts - File Import',N'Equipment Schedule',N'File', N'XLS, XLSX,CSV', N'-',
			   NULL, 1, 'System', GETDATE())
	Print 'Shifts - File Import Interface Row Created'
END
ELSE
BEGIN
    UPDATE  [dbo].[C_InterfaceMaster] 
	SET     [FileType] = 'XLS, XLSX, CSV',
	        [FileFormat] = N'EmployeeNumber,ShiftDate,ShiftBandName,Remarks  M02325,16/06/2022,D,TEST'
    WHERE   InterfaceMasterId = 13
END

-- Validate whether RawClocking Text Import Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 15)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (15, N'Import', N'RawClockingText - File Text Import', N'Time and Attendance', N'File', N'TXT', N'-', 
			   N'EmployeeNumber,SwipeDate,SwipeTime,LocationName,Type   14-06703,16/05/2021,08:00:00,00,I', 1, 'System', GETDATE())
	Print 'RawClocking- Text File Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE C_InterfaceMaster SET Name = 'PTP-ACS Raw Clocking - File Import', Method='File', FileType ='TXT' 
	Where InterfaceMasterId = 15
END
	
-- Validate whether Equipment Login Logout Excel Import Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 16)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (16, N'Import', N'EquipmentLoginLogOut-Excel Import', N'Operations', N'File', N'XLS,XLSX,CSV', N'-', 
			   N'EquipmentName,EmployeeNumber,ClockInDateTime,Type,PickupPoint,Remarks,Source     RTG100,000903,24/02/2022 13:30,I,yardLOC2010,,Excel', 1, 'System', GETDATE())
	Print 'Equipment Login Logout Excel Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE	C_InterfaceMaster
	SET		Name ='Employee Equipment Login - Excel Import',
			FileFormat=N'EquipmentName,EmployeeNumber,ClockInDateTime,PickupPoint,Remarks,Source RTG100,000903,24/02/2022 13:30,YARDLOC,,Excel'
	WHERE	InterfaceMasterId = 16
END

-- Validate whether Leave Accrual Balance Interface Exists Or Not
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 17)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (17, N'Import', N'Leave Accrual Balance - File Import', N'Leave', N'FILE', 'XLS,XLSX', N'-', 
			   'EmployeeNumber,LeaveYear,LeaveCode,EntitlementDays,CarryForwardDays,EarnedMonth,DaysUsed,AdjustDays,EarnedDays,BalanceDays', 1, 'System', GETDATE())
	Print 'Leave Accrual Balance - File Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE C_InterfaceMaster 
	SET		ModuleName = 'Leave',
	        FileType  =  'XLS,XLSX,CSV',
			FileFormat = 'EmployeeNumber,LeaveYear,LeaveCode,EntitlementDays,CarryForwardDays,EarnedMonth,DaysUsed,AdjustDays,EarnedDays,BalanceDays'
	WHERE	InterfaceMasterId = 17
END

-- Validate whether Workflow Route Import Interface Exists Or Not.
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 18)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (18, N'Import', N'Approval Workflow Route - File Import', N'Approval Workflow Route ', N'FILE', 'XLS,XLSX', N'-', 
			   N'RouteName,ApprovalRequirement,ApproverEmployeeNumber,RouteLevel,Type Management,0 or 1,Emp020,1 0r 2,I or U', 1, 'System', GETDATE())
	Print 'Approval Workflow Route - File Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE C_InterfaceMaster
	SET	FileFormat=N'RouteName,ApprovalRequirement,ApproverEmployeeNumber,RouteLevel,Type Management,0 or 1,Emp020,1 0r 2,I or U'
	WHERE InterfaceMasterId = 18
END

-- Validate whether ACS Raw Clocking File Interface Not Exists 
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 19)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (19, N'FTP', N'PTP-ACS Raw Clocking - FTP', N'FTP Connection For PTP-ACS Raw Clocking File', N'FTP', 'TXT', N'-', 
	 N'EmployeeNumber,SwipeDate,SwipeTime,LocationName,Type   14-06703,16/05/2021,08:00:00,00,I', 1, 'System', GETDATE())
	Print 'PTP-ACS Raw Clocking - FTP Interface Row Created'
END
ELSE
BEGIN
	UPDATE C_InterfaceMaster
	SET	FileFormat=N'EmployeeNumber,SwipeDate,SwipeTime,LocationName,Type   14-06703,16/05/2021,08:00:00,00,I'
	WHERE InterfaceMasterId = 19
END

-- Validate whether Equipment Login AND Logout Excel Import Exists or not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE	InterfaceMasterId = 20)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (20, N'Import', N'EquipmentClockInandClockOut-Excel Import', N'Operations', N'File', N'XLS,XLSX,CSV', N'-', 
			   N'EquipmentName,EmployeeNumber,ClockInDateTime,ClockOutDateTime,PickupPoint,Remarks,Source    RTG100,000903,24/02/2022 13:30,24/02/2022 23:00,yardLOC2010,,Excel', 1, 'System', GETDATE())
	Print 'Equipment Login AND Logout Excel Import Interface Row Created'
END
ELSE
BEGIN
	UPDATE	C_InterfaceMaster
	SET		Name ='Employee Equipment Login/LogOut - Excel Import',
			FileFormat=N'EquipmentName,EmployeeNumber,ClockInDateTime,ClockOutDateTime,PickupPoint,Remarks,Source RTG100,000903,24/02/2022 13:30,24/02/2022 23:00,YARDLOC,,Excel'
	WHERE	InterfaceMasterId = 20
END

-- Validate Whether Or Not Vessel And Crane Schedule N4 Interface Exists Or Not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 21)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (21, N'API', N'[JIVI-N4] Vessel And Crane Schedule', N'N4 Vessel And Crane Schedule', N'JiviVesselCraneSchedule', 'JSON', N'-', 
	 N'Type,Vessel/Crane Name,SwipeTime,VesselVisitId,Berth,Priority,StartDateTime, EndDateTime,VesselStatus', 1, 'System', GETDATE())
	Print '[JIVI-N4] Vessel And Crane Schedule - API Interface Row Created'
END

-- Validate Whether Or Not Equipemnt Login LogOut N4 Interface Exists Or Not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 22)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (22, N'API', N'[JIVI-N4] Employee Equipment Login Logout', N'N4 Employee Equipment Login and Logout Data', N'JiviEmpEqLoginLogout', 'JSON', N'-', 
	 N'EmployeeName,EquipmentName,OpsStartDateTime,OpsEndDateTime,RequestTime,TypeOfCHE', 1, 'System', GETDATE())
	Print '[JIVI-N4] Employee Equipment Login Logout - API Interface Row Created'
END

-- Validate Whether BoxMovement N4 Interface Exists Or Not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 23)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (23, N'API', N'[JIVI-N4] Box Movement', N'N4 Employee Equipment Box Movement', N'JiviBoxMovement', 'JSON', N'-', 
	 N'Employee Name,Equipment Name,Login Time,Logout Time,No Of Moves,TypeOfCHE', 1, 'System', GETDATE())
	Print '[JIVI-N4] Box Movement - API Interface Row Created'
END

-- Validate Whether QCO Booking Data - SQL DataBase Exists Or Not. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 24)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (24, N'Export', N'QCO Booking Data - SQL DataBase','Operations', 'SQL Connection',NULL, N'-', 
	 NULL, 1, 'System', GETDATE())
	Print 'QCO Booking Data - SQL DataBase Row Created'
END

-- Validate whether ACS Raw Clocking File Interface Not Exists 
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 25)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (25, N'SFTP', N'Raw Clocking - SFTP', N'SFTP Connection For PTP-ACS Raw Clocking File', N'SFTP', 'TXT', N'-', 
	 N'EmployeeNumber,SwipeDate,SwipeTime,LocationName,Type   14-06703,16/05/2021,08:00:00,00,I', 1, 'System', GETDATE())
	Print 'Raw Clocking - SFTP Interface Row Created'
END

-- Validate whether Employee Leave SQL Import Exist or Not
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 27)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (27, N'SFTP', N'Employee Leave - SQL Database', N'Scheduler', N'SQL Connection', NULL, N'-', 
	         NUll, 1, 'Script Migration', GETDATE())
	Print 'Employee Leave -SQL Database Interface Row Created'
END



-- Validate Whether Or Not Berth Tool Interface. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 28)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (28, N'API', N'Berth Tool Interface', N'Berth Tool Interface', N'JiviBerthTool', 'JSON', N'-', 
	 N'-', 1, 'System', GETDATE())
	Print 'Berth Tool Interface- API Interface Row Created'
END

-- Validate Whether Or Not Employee Leave Export. If Not Exists Create
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 29)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (29, N'Export', N'Employee Leave Export', N'Scheduler', N'File', 'JSON', N'-', 
	 N'EmployeeNumber,LeaveCode,FromDate,ToDate,ApprovedBy,Remarks,ApprovalStatus,Attachments,DateOfLieuLeave,ClinicCode,IsHalfDay
	 M02332,Sick Leave,01/08/2022,01/08/2022,,AUTH,,,,', 1, 'System', GETDATE())
	Print 'Employee Leave Export Row Created'
END

-- Validate whether JIVI-MYERP Employee Master Data Import Interface Exists
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 30)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (30, N'Import', N'[JIVI - MYERP] Employee Master Data Import - SFTP', N'MYERP Employee Master Data File', N'SFTP', 'CSV', N'-', 
			N'EmployeeNumber,BadgeNumber,FirstName,MiddleName,LastName,DateOfBirth,EmploymentBasis,MaritalStatus,Gender,
			Religion,Address1,Address2,Address3,City,PostCode,State,Country,HomePhone,MobilePhone,EmailAddress,HiredDate,Position,
			ScheduleRule,PayGroup,HourlyRate,ContractedHours,PrimaryRoleName,RosterGroupName,OUName,OTSettings,SecurityRole', 1, 'System', GETDATE())
	Print '[JIVI - MYERP] Employee Master Data Import - SFTP'
END

-- Validate whether JIVI-MYERP Leave Accrual Data Import Interface Exists
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 31)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (31, N'Import', N'[JIVI - MYERP] Leave Accrual Data Import - SFTP', N'MYERP Leave Accrual Data File', N'SFTP', 'CSV', N'-', 
			'EmployeeNumber,LeaveYear,LeaveCode,EntitlementDays,CarryForwardDays,EarnedMonth,DaysUsed,AdjustDays,EarnedDays,BalanceDays', 1, 'System', GETDATE())
	Print '[JIVI - MYERP] Leave Accrual Data Import Data Import - SFTP'
END

-- Validate whether JIVI-MYERP Employee Panel Clinic Data Import Interface Exists
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 32)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (32, N'Import', N'[JIVI - MYERP] Employee Panel Clinics Import - SFTP', N'MYERP Employee Panel Clinics For Import', N'SFTP', 'CSV', N'-', 
			'EmployeeNumber,PanelClinicName,Address,', 1, 'System', GETDATE())
	Print '[JIVI - MYERP] Employee Panel Clinics Import - SFTP'
END

-- Validate whether JIVI-MYERP Employee Dates For Lieu Days Import Interface Exists
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 33)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (33, N'Import', N'[JIVI - MYERP] Employee Lieu Dates Import - SFTP', N'MYERP Employee Lieu Dates For Import', N'SFTP', 'CSV', N'-', 
			'EmployeeNumber,LieuDate,Utilized,', 1, 'System', GETDATE())
	Print '[JIVI - MYERP] Employee Lieu Dates Import - SFTP'
END
-- Validate whether JIVI-MYERP Employee Approval Workflow Data Import Interface Exists

-- Validate whether JIVI-MYERP Employee Leave Export Interface Exists
IF NOT EXISTS (SELECT * FROM C_InterfaceMaster WHERE InterfaceMasterId = 35)
BEGIN
	INSERT [dbo].[C_InterfaceMaster] 
	([InterfaceMasterId], [Type], [Name], [ModuleName], [Method], [FileType], [SoftwareName],
	 [FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	 VALUES (35, N'Export', N'[JIVI - MYERP] Employee Leave Export - SFTP', N'MYERP Employee Leave Export', N'SFTP', 'CSV', N'-', 
			'EmployeeNumber,LeaveCode,FromDate,ToDate,ApprovedBy,Remarks,ApprovalStatus,Attachments,DateOfLieuLeave,ClinicCode,IsHalfDay,', 1, 'System', GETDATE())
	Print '[JIVI - MYERP] Employee Leave Export - SFTP'
END

SET IDENTITY_INSERT [dbo].[C_InterfaceMaster] OFF
GO
SET IDENTITY_INSERT [dbo].[T_BackendProcessList] ON 

IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 1)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],[ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (1,0, N'Reconciliation Process', NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Reconciliation Process] - System Task Created'
END

IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 2)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type], [Name], [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (2,0, N'THP Process', NULL, NULL,null,null, 1, N'System',  GETDATE())

	Print '[THP Process] - System Task Created'
END


IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 3)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type], [Name], [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (3,0, N'Schedule Creation Period',NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Schedule Creation Period] - System Task Created'
END



IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 4)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type], [Name],[ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (4, 0,  N'Employee Import',NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Employee Import] - System Task Created'
END

IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 5)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type], [Name], [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (5, 0, N'Raw Clocking Import', NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Raw Clocking Import] - System Task Created'
END


IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 6)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (6,0, N'Vessel Import', NULL, NULL,null,null, 1, N'System',GETDATE())

	Print '[Vessel Import] - System Task Created'
END

IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 7)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (7, 1, N'Raw Clocking - SQL Database',NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Raw Clocking - SQL Database] - System Task Created'
END


IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 8)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (8,0,N'THP Period Creation',NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[THP Period Creation] - System Task Created'
END

--Validate Whether THP Create Period Exists Or Not. If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 9)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (9,0, N'Leave Entitlement Process', NULL, NULL,null,null, 1, N'System',GETDATE())

	Print '[Leave Entitlement Process] - System Task Created'
END


--Validate  Whether Employee Movement Process Exists Or Not, If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 10)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (10,0, N'Employee Movement', NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Employee Movement] - System Task Created'
END

--Validate  Whether Employee Termination Process Exists Or Not, If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 11)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (11,0, N'Employee Termination',  NULL, NULL,null,null, 1, N'System',GETDATE())

	Print '[Employee Termination] - System Task Created'
END


--Validate  Whether Employee Termination Process Exists Or Not, If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 12)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (12, 0,N'Public Holiday Process', NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Public Holiday Process] - System Task Created'
END


--Validate  Whether Employee Termination Process Exists Or Not, If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 13)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (13, 0,N'Weekly Public Holiday Process', NULL, NULL,null,null, 1, N'System',GETDATE())

	Print '[Weekly Public Holiday Process] - System Task Created'
END

IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 14)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (14,0, N'Convert Flexi Shift To Off Day', NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Convert Flexi Shift To Off Day] - System Task Created'
END


IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 15)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId],[Type],[Name],  [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (15,0, N'Probation Period Expiry Details',  NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Probation Period Expiry Details] - System Task Created'
END

--Validate  Whether Pending Leave Applications By Approver Email Notification Exists Or Not, If Exists Update
IF NOT EXISTS (SELECT * FROM T_BackendProcessList WHERE	BackendProcessId = 16)
BEGIN
	INSERT [dbo].[T_BackendProcessList] 
	([BackendProcessId], [Type],[Name], [ModuleName], [Method], [Remarks],[FileFormat], [ActiveStatus], [CreatedBy], [CreatedDate]) 
	VALUES (16,0, N'Pending Leave Applications',  NULL, NULL,null,null, 1, N'System', GETDATE())

	Print '[Pending Leave Applications] - System Task Created'
END

SET IDENTITY_INSERT [dbo].[T_BackendProcessList] Off 
GO

SET IDENTITY_INSERT [dbo].[IE_ClientMaster] ON 

IF NOT EXISTS (SELECT * FROM IE_ClientMaster WHERE	ClientKeyId = 1)
BEGIN
	INSERT [dbo].[IE_ClientMaster] 
	(ClientKeyId, ClientId, ClientSecret, ClientName, CreatedBy, CreatedDate)
	VALUES(1, NEWID(), NEWID(), 'ADRENALINE','System',GETDATE())

	Print 'Client Details For Adrenaline created successfully'
END

SET IDENTITY_INSERT [dbo].[IE_ClientMaster] Off 
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.S_RosterGroupDetails') AND type in ('U'))
BEGIN	
	DROP TABLE S_RosterGroupDetails
END
ELSE PRINT 'Roster Group Details Table [S_RosterGroupDetails] Not Found' 
GO
SET IDENTITY_INSERT [dbo].[M_ScreenConfiguration] ON 

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 1)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (1,1, N'PMFinalBooking', N'A', N'1,0700:1200', N'0700 - 1200', 'Script Migration', GETDATE())	
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 1

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 2)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (2,1, N'PMFinalBooking', N'A', N'2,1300:1800', N'1300 - 1800', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 2

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 3)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (3,1, N'PMFinalBooking', N'B', N'1,0700:1100', N'0700 - 1100', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 3

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 4)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (4,1, N'PMFinalBooking', N'B', N'2,1200:1700', N'1200 - 1700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,1200:1700', [ConfigAdditionalValue] = N'1200 - 1700' WHERE ID = 4

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 5)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (5,1, N'PMFinalBooking', N'B', N'3,1800:1900', N'1800 - 1900', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'3,1800:1900', [ConfigAdditionalValue] = N'1800 - 1900' WHERE ID = 5

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 6)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (6,1, N'PMFinalBooking', N'C', N'1,0700:1000', N'0700 - 1000', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'1,0700:1000',[ConfigAdditionalValue]= N'0700 - 1000',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 6

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 7)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (7,1, N'PMFinalBooking', N'C', N'2,1100:1600', N'1100 - 1600', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'2,1100:1600',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 7

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 8)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (8,1, N'PMFinalBooking', N'C', N'3,1700:1900', N'1700 - 1900', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 8

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 9)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (9,1, N'PMFinalBooking', N'D', N'1,0700:0900', N'0700 - 0900', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 9

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 10)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (10,1, N'PMFinalBooking', N'D', N'2,1000:1500', N'1000 - 1500', 'Script Migration', GETDATE())
--ELSE  UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'2,1000:1500',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 10

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 11)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (11,1, N'PMFinalBooking', N'D', N'3,1600:1900', N'1600 - 1900', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'3,1600:1900',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 11

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 12)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (12,1, N'PMFinalBooking', N'E', N'1,0700:0800', N'0700 - 0800', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'1,0700:0800',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 12

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 13)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (13,1, N'PMFinalBooking', N'E', N'2,0900:1400', N'0900 - 1400', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'2,0900:1400',[ConfigScreen] = N'PMFinalBooking'  WHERE ID = 13

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 14)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (14,1, N'PMFinalBooking', N'E', N'3,1500:1900', N'1500 - 1900', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET  [ConfigValue] =N'3,1500:1900', [ConfigScreen] = N'PMFinalBooking' WHERE ID = 14

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 15)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (15,1, N'PMFinalBooking', N'F', N'1,0800:1300', N'0800 - 1300', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 15

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 16)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (16,1, N'PMFinalBooking', N'F', N'2,1400:1900', N'1400 - 1900', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigValue] =N'2,1400:1900', [ConfigScreen] = N'PMFinalBooking' WHERE ID = 16

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 17)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (17,1, N'PMFinalBooking', N'A', N'1,1900:0000', N'1900 - 2359', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking', [ConfigAdditionalValue]=N'1900 - 2359' WHERE ID = 17

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 18)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (18,1, N'PMFinalBooking', N'A', N'2,0000:0600', N'0100 - 0600', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,0000:0600' WHERE ID = 18

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 19)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (19,1, N'PMFinalBooking', N'B', N'1,1900:2300', N'1900 - 2300', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 19

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 20)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (20,1, N'PMFinalBooking', N'B', N'2,0000:0500', N'0000 - 0500', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,0000:0500', [ConfigAdditionalValue] = N'0000 - 0500' WHERE ID = 20

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 21)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (21,1, N'PMFinalBooking', N'B', N'3,0600:0700', N'0600 - 0700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'3,0600:0700', [ConfigAdditionalValue] = N'0600 - 0700' WHERE ID = 21

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 22)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (22,1, N'PMFinalBooking', N'C', N'1,1900:2200', N'1900 - 2200', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 22

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 23)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (23,1, N'PMFinalBooking', N'C', N'2,2300:0400', N'2300 - 0400', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,2300:0400' WHERE ID = 23

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 24)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (24,1, N'PMFinalBooking', N'C', N'3,0500:0700', N'0500 - 0700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 24

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 25)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (25,1, N'PMFinalBooking', N'D', N'1,1900:2100', N'1900 - 2100', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking' WHERE ID = 25

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 26)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (26,1, N'PMFinalBooking', N'D', N'2,2200:0300', N'2200 - 0300', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,2200:0300' WHERE ID = 26

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 27)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (27,1, N'PMFinalBooking', N'D', N'3,0400:0700', N'0400 - 0700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'3,0400:0700' WHERE ID = 27

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 28)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (28,1, N'PMFinalBooking', N'E', N'1,1900:2100', N'1900 - 2100', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'1,1900:2100', [ConfigAdditionalValue] = N'1900 - 2100' WHERE ID = 28

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 29)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (29,1, N'PMFinalBooking', N'E', N'2,2100:0200', N'2100 - 0200', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,2100:0200' WHERE ID = 29

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 30)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (30,1, N'PMFinalBooking', N'E', N'3,0300:0700', N'0300 - 0700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'3,0300:0700', [ConfigAdditionalValue] = N'0300 - 0700' WHERE ID = 30

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 31)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (31,1, N'PMFinalBooking', N'F', N'1,2000:0100', N'2000 - 2300', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking', [ConfigAdditionalValue] = N'2000 - 2300'  WHERE ID = 31

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 32)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (32,1, N'PMFinalBooking', N'F', N'2,0200:0700', N'0200 - 0700', 'Script Migration', GETDATE())
--ELSE UPDATE [M_ScreenConfiguration] SET [ConfigScreen] = N'PMFinalBooking',[ConfigValue] =N'2,0200:0700' WHERE ID = 32

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 33)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (33,2, N'PMPlanning', N'ActivityGenerationRules', N'PM Rules', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName]=N'ActivityGenerationRules', [ConfigValue] =N'PM Rules',[ConfigScreen] = N'PMPlanning'  WHERE ID = 33

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 34)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (34,2, N'PMPlanning', N'AllocationRules', N'PM Deployment', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName]=N'AllocationRules', [ConfigValue] =N'PM Deployment',[ConfigScreen] = N'PMPlanning'  WHERE ID = 34

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 35)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (35,1, N'PMFinalBooking', N'SkillList', N'PMO,MTS,LB,CFS,TECH,DEPO', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName] =N'SkillList',[ConfigValue] =N'PMO,MTS,LB,CFS,TECH,DEPO',[ConfigScreen] = N'PMFinalBooking' WHERE ID = 35

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 36)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (36,3, N'RTGPlanning', N'EquipmentTypes', N'RTG', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName] =N'EquipmentTypes',[ConfigScreen] = N'RTGPlanning'  WHERE ID = 36

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 37)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (37,2, N'PMPlanning', N'EquipmentTypes', N'PM', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName] =N'EquipmentTypes',[ConfigScreen] = N'PMPlanning'  WHERE ID = 37

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 38)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (38,3, N'RTGPlanning', N'ActivityGenerationRules', N'RTG Rules', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'RTG Rules',[ConfigScreen] = N'RTGPlanning'  WHERE ID = 38

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 39)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (39,3, N'RTGPlanning', N'AllocationRules', N'RTG Deployment', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'RTG Deployment',[ConfigScreen] = N'RTGPlanning'  WHERE ID = 39

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 40)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (40,4, N'RTGFinalBooking', N'PayCodes', N'RTG Regular OT,M2M Allowance,RP Allowance', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'RTGFinalBooking',[ConfigValue]='RTG Regular OT,M2M Allowance,RP Allowance'  WHERE ID = 40

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 41)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (41,5, N'StackersPlanning', N'EquipmentTypes', N'EH,FL,RS', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'StackersPlanning'  WHERE ID = 41

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 42)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (42,5, N'StackersPlanning', N'ActivityGenerationRules', N'Stacker Rules', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'Stacker Rules',[ConfigScreen] = N'StackersPlanning'  WHERE ID = 42

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 43)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (43,5, N'StackersPlanning', N'AllocationRules', N'Stacker Deployment', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'Stacker Deployment',[ConfigScreen] = N'StackersPlanning'  WHERE ID = 43

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 44)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (44,6, N'HSSEPlanning', N'ActivityGenerationRules', N'HSSE Rules', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'HSSEPlanning'  WHERE ID = 44

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 45)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (45,6, N'HSSEPlanning', N'AllocationRules', N'HSSE Deployment', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'HSSEPlanning'  WHERE ID = 45

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 46)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (46,7, N'LashingDeployment', N'SkillList', N'TOP MAN,LASHING,CONEMAN,Tab Reader', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'TOP MAN,LASHING,CONEMAN,Tab Reader,Mooring',[ConfigScreen] = N'LashingDeployment'  WHERE ID = 46

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 47)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (47,8, N'LashingFinalBooking', N'TopManSkill', N'TOP MAN', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'TOP MAN',[ConfigScreen] = N'LashingFinalBooking'  WHERE ID = 47

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 48)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (48,8, N'LashingFinalBooking', N'ConeManSkill', N'CONEMAN', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'CONEMAN',[ConfigScreen] = N'LashingFinalBooking'  WHERE ID = 48

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 49)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (49,8, N'LashingFinalBooking', N'TabReaderSkill', N'Tab Reader', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'Tab Reader',[ConfigScreen] = N'LashingFinalBooking'  WHERE ID = 49

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 50)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (50,8, N'LashingFinalBooking', N'LasherSkill', N'LASHING', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'LASHING',[ConfigScreen] = N'LashingFinalBooking'  WHERE ID = 50

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 51)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (51,8, N'LashingFinalBooking', N'MooringSkill', N'Mooring', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'Mooring',[ConfigScreen] = N'LashingFinalBooking'  WHERE ID = 51

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 52)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (52,7, N'LashingDeployment', N'ActivityGenerationRules', N'Lashing Rules', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'LashingDeployment'  WHERE ID = 52

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 53)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (53,7, N'LashingDeployment', N'AllocationRules', N'Lashing Deployment', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'LashingDeployment'  WHERE ID = 53

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 54)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (54,9, N'QCFinalBooking', N'EquipmentTypes', N'Crane', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'QCFinalBooking'  WHERE ID = 54

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 55)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (55,9, N'QCFinalBooking', N'SkillList', N'QCC,QCO,OBC', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'QCFinalBooking'  WHERE ID = 55

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 56)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (56,10, N'Uncontrolled Leave', N'LeaveCodeList', N'MC:Sick Leave,Emergency Leave:Annual Leave', N'UCL:LEAVE', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigName]=N'LeaveCodeList', [ConfigValue] =N'MC:Sick Leave,Emergency Leave:Annual Leave', ConfigAdditionalValue ='UCL:LEAVE'  WHERE ID = 56

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 57)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (57,3, N'RTGPlanning', N'SkillList', N'RTGO', N'', 'Script Migration', GETDATE())
ELSE UPDATE[M_ScreenConfiguration] SET [ConfigScreen] = N'RTGPlanning'  WHERE ID = 57

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 58)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (58,5, N'StackersPlanning', N'SkillList', N'STKO,EH', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'STKO,EH',[ConfigScreen] = N'StackersPlanning'  WHERE ID = 58

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 59)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (59,11, N'QCOBooking', N'SkillList', N'QCO,QCC,OBC', N'', 'Script Migration', GETDATE())

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 60)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate]) 
	VALUES (60,12, N'ShiftReport', N'SkillList', N'QCO,QCC,OBC,PMO,RTGO', N'', 'Script Migration', GETDATE())
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'QCO,YCO,RSEHO,TTO,FLO,LCA,LCA_Fly Man,VOA_COA,Fix,AC,Admin,Cleaner,Electrical,Engine,Infra Supervisor,Mechanical,Painter,Plumber,Project,Tyre,Welder,Environmental Specialist,HSE Administrative Assistant,HSE Director,HSE Manager,HSE Manager Assistant,HSE Officer,HSE Officer (Female),HSE Officer (Shift),HSE Officer (Senior),HSE Officer (SMS Support),HSE Officer (SPD),HSE Superintendent,HSE Superintendent (SPD),Nurse,Paramedic,CFS & Landside Head,CFS Manager,CFS Executive,CFS Helper,Cooper,Cooper Foreman,Customer Service Executive,Customer Service Superintendent,Customs Compliance Assistant,Customs Compliance Coordinator,Customs Compliance Officer - Auction,Customs Compliance Officer - Customs,Customs Compliance Officer - Front Desk,Customs Compliance Officer - Scan,Customs Compliance Superintendent,Customs Compliance Supervisor - Customs,Customs Compliance Supervisor - Front Desk,Data Analyst,Forklift Foreman,Forklift Operator,Gate Operation Assistant,Gate Supervisor,Landside Manager,Landside Superintendent,Landside Supervisor,Logistics & Warehouse Assistant Manager,Logistics & Warehouse Coordinator,Logistics & Warehouse Superintendent,Logistics & Warehouse Superintendent - Shift,Logistics & Warehouse Supervisor - Shift,Logistics & Warehouse Supervisor - Quality,Logistics & Warehouse Supervisor - Warehouse,Operations Excellence Executive,Planner & Controller,Planning & Control Superintendent,Planning & Control Supervisor,Quality Control Coordinator,Resource & Deployment Planner,Resource & Deployment Supervisor,RSGT - Road Freight Manager / FERO,Scan Helper,Scan Operator Assistant,Yard Operation Assistant,Terminal Security Supervisor,CAMP Security Supervisor,Terminal Security Guard,CAMP Security Guard,Security,Assistant Stevedoring Manager,Berth & Yard Supervisor,Berth Planner,Controller Supervisor,Documentation Operation Assistant,Documentation Superintendent,Dynamic  Planning,Empty Inspection Supervisor,Lashing & Coning Supervisor,Management Trainee,Operation Admin Assistant,Operation Documentation Supervisor,Operation Executive,Operation Superintendent,Operation Supervisor,Operations Optimization Analyst,Operations Productivity and Reporting Analyst,Operations Productivity & Reporting Superintendent,Operations Productivity and Reporting Supervisor,OPS Admin Supervisor,Productivity & Optimization Manager,QC Remote Controller Supervisor,Reefer & Empty Superintendent,Reefer Supervisor,Reefer Technician,Resource & Training Assistant Manager,Resource Coordinator,Resource Planner,Resources Planning supervisor,Stevedoring Manager,Stowage Planner,Stowage Planning Supervisor,Trainer,Trainer Supervisor,Yard Planner,Yard Operation Assistant - SVD,ICT Manager,Senior Systems Administrator,Senior TOS Administrator,Senior Systems Engineer,Integration Developer,CRS,Engineer,INFRA,MES,RR,Supervisor,TSD,ICT Admin'  WHERE ID = 60

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 61)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (61,12, N'ShiftReport', N'ColumnName', N'Id', N'EmployeeNumber', 'Script Migration', GETDATE(),N'label:text')
--ELSE UPDATE[M_ScreenConfiguration] SET [FieldType] =N'label:text'  WHERE ID = 61

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 62)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (62,12, N'ShiftReport', N'ColumnName', N'Name', N'EmployeeName', 'Script Migration', GETDATE(),N'label:text')
--ELSE UPDATE[M_ScreenConfiguration] SET [FieldType] =N'label:text'  WHERE ID = 62

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 63)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (63,12, N'ShiftReport', N'ColumnName', N'Equipment', N'CraneNumber', 'Script Migration', GETDATE(),N'label:text')
--ELSE UPDATE[M_ScreenConfiguration] SET [FieldType] =N'label:text',[ConfigValue]=N'Equipment',[ConfigAdditionalValue]=N'CraneNumber'  WHERE ID = 63

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 64)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (64,12, N'ShiftReport', N'ColumnName', N'Role', N'RoleDescription', 'Script Migration', GETDATE(),N'label:text')
--ELSE UPDATE[M_ScreenConfiguration] SET [FieldType] =N'label:text',[ConfigValue]=N'Role',[ConfigAdditionalValue]=N'RoleDescription'  WHERE ID = 64

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 65)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (65,12, N'ShiftReport', N'ColumnName', N'Deployed Skill', N'DeployedSkillName', 'Script Migration', GETDATE(),N'label:text')
--ELSE UPDATE[M_ScreenConfiguration] SET [FieldType] =N'label:text',[ConfigValue]=N'Deployed Skill',[ConfigAdditionalValue]=N'DeployedSkillName'  WHERE ID = 65

IF  EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 66)
	DELETE [M_ScreenConfiguration]  WHERE ID = 66

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 67)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (67,12, N'ShiftReport', N'ColumnName', N'Activity Start Time', N'ActivityStartTime', 'Script Migration', GETDATE(),N'label:datetime')
--ELSE UPDATE[M_ScreenConfiguration] SET [ConfigValue] =N'Activity Start Time',[ConfigAdditionalValue] =N'ActivityStartTime',[FieldType] =N'label:datetime'  WHERE ID = 67

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 68)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (68,9, N'QCFinalBooking', N'ColumnName', N'Id', N'EmployeeNumber', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 69)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (69,9, N'QCFinalBooking', N'ColumnName', N'OT', N'OT', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 70)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (70,9, N'QCFinalBooking', N'ColumnName', N'Deployed Rank', N'DeployedRank', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 71)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (71,9, N'QCFinalBooking', N'ColumnName', N'Live Rank', N'LiveRank', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 72)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (72,9, N'QCFinalBooking', N'ColumnName', N'Name', N'EmployeeName', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 73)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (73,9, N'QCFinalBooking', N'ColumnName', N'QC', N'CraneNumber', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 74)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (74,9, N'QCFinalBooking', N'ColumnName', N'Priority', N'Priority', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 75)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (75,9, N'QCFinalBooking', N'ColumnName', N'Jerk', N'Jerk', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 76)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (76,9, N'QCFinalBooking', N'ColumnName', N'Deployed Skill', N'DeployedSkillName', 'Script Migration', GETDATE(),N'label:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 77)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (77,9, N'QCFinalBooking', N'ColumnName', N'Notes', N'Notes', 'Script Migration', GETDATE(),N'input:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 78)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (78,12, N'ShiftReport', N'ColumnName', N'Activity End Time', N'ActivityEndTime', 'Script Migration', GETDATE(),N'label:datetime')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 79)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (79,12, N'ShiftReport', N'ColumnName', N'Notes', N'Notes', 'Script Migration', GETDATE(),N'input:text')

IF EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 80)
	DELETE M_ScreenConfiguration WHERE ID = 80

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 81)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (81,13, N'EmployeeRoster', N'ColumnName', N'Employee#', N'EmployeeNumber', 'Script Migration', GETDATE(),N'input:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 82)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (82,13, N'EmployeeRoster', N'ColumnName', N'Employee Name', N'EmployeeName', 'Script Migration', GETDATE(),N'input:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 83)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (83,13, N'EmployeeRoster', N'ColumnName', N'TEL', N'MobilePhone', 'Script Migration', GETDATE(),N'input:text')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 84)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (84,13, N'EmployeeRoster', N'ColumnName', N'Total', N'TotalShift', 'Script Migration', GETDATE(),N'input:Integer')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 85)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (85,13, N'EmployeeRoster', N'ColumnName', N'DAY S1', N'TotalDayShift', 'Script Migration', GETDATE(),N'input:Integer')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 86)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (86,13, N'EmployeeRoster', N'ColumnName', N'NIGHT S2', N'TotalNightShift', 'Script Migration', GETDATE(),N'input:Integer')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 87)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (87,13, N'EmployeeRoster', N'DayShiftBand', N'S1', N'', 'Script Migration', GETDATE(),N'')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 88)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (88,13, N'EmployeeRoster', N'NightShiftBand', N'S2', N'', 'Script Migration', GETDATE(),N'')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 89)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (89,13, N'EmployeeRoster', N'ColumnName', N'Office O', N'TotalOfficeOShift', 'Script Migration', GETDATE(),N'input:Integer')
UPDATE M_ScreenConfiguration SET [ConfigAdditionalValue] = N'TotalOfficeOShift' WHERE ID = 89

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 90)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (90,13, N'EmployeeRoster', N'OfficeOShiftBand', N'S1(M)', N'', 'Script Migration', GETDATE(),N'')

IF NOT EXISTS (SELECT * FROM M_ScreenConfiguration WHERE ID = 91)
	INSERT [dbo].[M_ScreenConfiguration] ([Id], [ConfigType], [ConfigScreen], [ConfigName], [ConfigValue], [ConfigAdditionalValue],[CreatedBy],[CreatedDate],[FieldType]) 
	VALUES (91,9, N'QCFinalBooking', N'ColumnName', N'Slashed Crane', N'SlashedCranes', 'Script Migration', GETDATE(),N'label:text')

SET IDENTITY_INSERT [dbo].[M_ScreenConfiguration] OFF
GO



-- Template For New Leave Application Notification
IF NOT EXISTS (SELECT * FROM D_MessageSkill WHERE MessageId = 23) 
BEGIN
	INSERT INTO D_MessageSkill
	(MessageId, SkillId, ActiveStatus, CreatedBy, CreatedDate)
	SELECT  23, D_Skill.SkillId, 1, 'System',GETDATE()
	FROM	D_Skill WITH (NOLOCK)

	Print 'Notification Template Skills For Broadcast Deployment created successfully'
END

--Insert J_WorkloadType
SET IDENTITY_INSERT [dbo].[J_WorkloadType] ON 
GO

IF NOT EXISTS(SELECT * FROM J_WorkloadType WITH (NOLOCK) WHERE Id = 1)
BEGIN
	
	INSERT INTO J_WorkloadType
	(Id, WorkLoadType, CreatedBy, CreatedDate)
	VALUES(1, N'Vessel Type','System',GETDATE())
END
GO

IF NOT EXISTS(SELECT * FROM J_WorkloadType WITH (NOLOCK) WHERE Id = 2)
BEGIN
	
	INSERT INTO J_WorkloadType
	(Id, WorkLoadType, CreatedBy, CreatedDate)
	VALUES(2, N'Terminal Activity Type','System',GETDATE())
END
GO

IF NOT EXISTS(SELECT * FROM J_WorkloadType WITH (NOLOCK) WHERE Id = 3)
BEGIN
	
	INSERT INTO J_WorkloadType
	(Id, WorkLoadType, CreatedBy, CreatedDate)
	VALUES(3, N'VAS Activity Type','System',GETDATE())
END
GO

SET IDENTITY_INSERT [dbo].[J_WorkloadType] OFF
GO

SET IDENTITY_INSERT [dbo].[D_PasswordPolicy] ON 

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 1)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(1, 'Password Length Must X Number of Characters', 8, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 2)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(2, 'Minimum number of Lowercase characters', 1, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 3)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(3, 'Minimum number of Uppercase characters', 1, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 4)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(4, 'Minimum number of Special characters', 1, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 5)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(5, 'Maximum Password Length', 128, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 6)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(6, 'Password Expires after X number of days', 180, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 7)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(7, 'Lock user account after X number of login failures', 3, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 8)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(8, 'Minimum unique passwords required before resuing old password', 3, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 9)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(9, 'Automatic Logout user after X number of idel minutes', 10, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 10)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(10, 'Minimum Number of Numeric characters required', 1, 1, 'System',GETDATE())
END

IF NOT EXISTS (SELECT * FROM [D_PasswordPolicy] WHERE PolicyId = 11)
BEGIN
	INSERT INTO D_PasswordPolicy (PolicyId, PolicyDescription, PolicyValue, ActiveStatus, CreatedBy, CreatedDate)
	VALUES(11, 'Number of days to Notify user on password expiry ', 7, 1, 'System',GETDATE())
END

SET IDENTITY_INSERT [dbo].[D_PasswordPolicy] OFF

GO
SET IDENTITY_INSERT [dbo].[IE_ExportFileConfig] ON 

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 1)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (1,1, N'TimeAttendanceExport', N'1', N'#', N'',N'Integer',N'SeqNo',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'#',[DefaultValue] =N'',[DataType] =N'Integer',[JiViColumn] =N'SeqNo',[MappingData] =N'' WHERE ConfigId = 1

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 2)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (2,1, N'TimeAttendanceExport', N'2', N'Emp Code', N'',N'string',N'EmployeeNumber',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'2', [ColumnName] = N'Emp Code',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'EmployeeNumber',
			[MappingData] =N''  WHERE ConfigId = 2

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 3)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (3,1, N'TimeAttendanceExport', N'3', N'Name', N'',N'string',N'EmployeeName',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'3',[ColumnName] = N'Name',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'EmployeeName',
			[MappingData] =N''  WHERE ConfigId = 3

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 4)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (4,1, N'TimeAttendanceExport', N'4', N'Date', N'',N'Date',N'Date',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'4', [ColumnName] = N'Date',[DefaultValue] =N'',[DataType] =N'Date',[JiViColumn] =N'Date',
			[MappingData] =N'' WHERE ConfigId = 4

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 5)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (5,1, N'TimeAttendanceExport', N'6', N'Day Type', N'HOL ({0})',N'string',N'ShiftBand',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'5',[ColumnName] = N'Day Type',[DefaultValue] =N'HOL ({0})',[DataType] =N'string',[JiViColumn] =N'ShiftBand',
			[MappingData] =N'' WHERE ConfigId = 5

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 6)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (6,1, N'TimeAttendanceExport', N'6', N'Shift Details', N'',N'string',N'ShiftBand',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'6',[ColumnName] = N'Shift Details',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'ShiftBand',
			[MappingData] =N'' WHERE ConfigId = 6

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 7)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (7,1, N'TimeAttendanceExport', N'7', N'Exception', N'',N'string',N'ExceptionCode',N'OK:Present,Missing In:ClockInException,Missing Out:ClockOutException', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'7',[ColumnName] = N'Exception',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'ExceptionCode',
	[MappingData] =N'OK:Present,Missing In:ClockInException,Missing Out:ClockOutException' WHERE ConfigId = 7

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 8)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (8,1, N'TimeAttendanceExport', N'12', N'From Date', N'',N'Date',N'FromDate',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'12',[ColumnName] = N'From Date',[DefaultValue] =N'',[DataType] =N'Date',[JiViColumn] =N'FromDate',
			[MappingData] =N'' WHERE ConfigId = 8

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 9)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (9,1, N'TimeAttendanceExport', N'13', N'From Time', N'',N'Time',N'FromTime',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'13',[ColumnName] = N'From Time',[DefaultValue] =N'',[DataType] =N'Time',[JiViColumn] =N'FromTime',
			[MappingData] =N'' WHERE ConfigId = 9

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 10)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (10,1, N'TimeAttendanceExport', N'14', N'To Date', N'',N'Date',N'ToDate',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'14',[ColumnName] = N'To Date',[DefaultValue] =N'',[DataType] =N'Date',[JiViColumn] =N'ToDate',
			[MappingData] =N'' WHERE ConfigId = 10

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 11)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (11,1, N'TimeAttendanceExport', N'15', N'To Time', N'',N'Time',N'ToTime',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'15',[ColumnName] = N'To Time',[DefaultValue] =N'',[DataType] =N'Time',[JiViColumn] =N'ToTime',[MappingData] =N'' WHERE ConfigId = 11

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 12)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (12,1, N'TimeAttendanceExport', N'16', N'Post OT Hrs', N'0',N'Double',N'',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence]=N'16',[ColumnName] = N'Post OT Hrs',[DefaultValue] =N'0',[DataType] =N'Double',[JiViColumn] =N'',
			[MappingData] =N'' WHERE ConfigId = 12

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 13)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (13,1, N'TimeAttendanceExport', N'17', N'Manual Entry', N'1',N'Int',N'',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'17',[ColumnName] = N'Manual Entry',[DefaultValue] =N'1',[DataType] =N'Int',[JiViColumn] =N'',[MappingData] =N'' WHERE ConfigId = 13

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 14)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (14,1, N'TimeAttendanceExport', N'18', N'OT Type1', N'',N'string',N'OTType1',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'18',[ColumnName] = N'OT Type1',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'OTType1',[MappingData] =N'' WHERE ConfigId = 14

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 15)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (15,1, N'TimeAttendanceExport', N'19', N'OT1 Hrs', N'',N'Double',N'OT1Hrs',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'19',[ColumnName] = N'OT1 Hrs',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'OT1Hrs',[MappingData] =N'' WHERE ConfigId = 15

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 16)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (16,1, N'TimeAttendanceExport', N'20', N'OT Type2', N'',N'string',N'OTType2',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'20',[ColumnName] = N'OT Type2',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'OTType2',[MappingData] =N'' WHERE ConfigId = 16

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 17)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (17,1, N'TimeAttendanceExport', N'21', N'OT2 Hrs', N'',N'Double',N'OT2Hrs',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'21',[ColumnName] = N'OT2 Hrs',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'OT2Hrs',[MappingData] =N'' WHERE ConfigId = 17

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 18)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (18,1, N'TimeAttendanceExport', N'22', N'All 1', N'',N'string',N'All1',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'22',[ColumnName] = N'All 1',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'All1',[MappingData] =N'' WHERE ConfigId = 18

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 19)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (19,1, N'TimeAttendanceExport', N'23', N'Allw V1', N'',N'Double',N'AllwV1',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'23',[ColumnName] = N'Allw V1',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'AllwV1',[MappingData] =N'' WHERE ConfigId = 19

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 20)	
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (20,1, N'TimeAttendanceExport', N'24', N'All 2', N'',N'string',N'All2',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'24',[ColumnName] = N'All 2',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'All2',[MappingData] =N'' WHERE ConfigId = 20

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 21)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (21,1, N'TimeAttendanceExport', N'25', N'Allw V2', N'',N'Double',N'AllwV2',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'25',[ColumnName] = N'Allw V2',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'AllwV2',[MappingData] =N'' WHERE ConfigId = 21

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 22)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (22,1, N'TimeAttendanceExport', N'26', N'All 3', N'',N'string',N'All3',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'26',[ColumnName] = N'All 3',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'All3',[MappingData] =N'' WHERE ConfigId = 22

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 23)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (23,1, N'TimeAttendanceExport', N'27', N'Allw V3', N'',N'Double',N'AllwV3',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'27',[ColumnName] = N'Allw V3',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'AllwV3',[MappingData] =N'' WHERE ConfigId = 23

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 24)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (24,1, N'TimeAttendanceExport', N'28', N'All 4', N'',N'string',N'All4',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'28',[ColumnName] = N'All 4',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'All4',[MappingData] =N'' WHERE ConfigId = 24

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 25)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (25,1, N'TimeAttendanceExport', N'29', N'Allw V4', N'',N'Double',N'AllwV4',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'29',[ColumnName] = N'Allw V4',[DefaultValue] =N'',[DataType] =N'Double',[JiViColumn] =N'AllwV4',[MappingData] =N'' WHERE ConfigId = 25

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 26)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (26,1, N'TimeAttendanceExport', N'30', N'Leave Type', N'',N'string',N'LeaveType',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'30',[ColumnName] = N'Leave Type',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'LeaveType',[MappingData] =N'' WHERE ConfigId = 26

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 27)
	DELETE [IE_ExportFileConfig] WHERE ConfigId = 27

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 28)
	DELETE [IE_ExportFileConfig] WHERE ConfigId = 28

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 29)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (29,1, N'TimeAttendanceExport', N'31', N'Pending With', N'',N'string',N'ApprovedBy',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'31',[ColumnName] = N'Pending With',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'ApprovedBy',[MappingData] =N'' WHERE ConfigId = 29

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 30)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 30

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 31)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (31,1, N'TimeAttendanceExport', N'32', N'Status', N'',N'string',N'',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'32',[ColumnName] = N'Status',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'',[MappingData] =N'' WHERE ConfigId = 31

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 32)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 32

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 33)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (33,1, N'TimeAttendanceExport', N'33', N'Remarks', N'',N'string',N'',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'33',[ColumnName] = N'Remarks',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'',[MappingData] =N'' WHERE ConfigId = 33

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 34)
	DELETE [IE_ExportFileConfig] WHERE ConfigId = 34
--------------------------------------------- Roster Export -----------------------------------------------------------------------------
IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 35)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (35,2, N'RosterExport', N'35', N'#', N'',N'Integer',N'SeqNo',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'#',[DefaultValue] =N'',[DataType] =N'Integer',[JiViColumn] =N'SeqNo',[MappingData] =N'' WHERE ConfigId = 35

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 36)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (36,2, N'RosterExport', N'36', N'Employee Code', N'',N'string',N'EmployeeNumber',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Employee Code',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'EmployeeNumber',[MappingData] =N'' WHERE ConfigId = 36

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 37)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (37,2, N'RosterExport', N'37', N'Employee Name', N'',N'string',N'EmployeeName',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Employee Name',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'EmployeeName',[MappingData] =N'' WHERE ConfigId = 37

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 38)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (38,2, N'RosterExport', N'38', N'Assign.', N'1',N'Integer',N'',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Assign.',[DefaultValue] =N'1',[DataType] =N'Integer',[JiViColumn] =N'',[MappingData] =N'' WHERE ConfigId = 38

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 39)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (39,2, N'RosterExport', N'39', N'Rota Schedule Code', N'',N'string',N'RosterGroupName',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Rota Schedule Code',[DefaultValue] =N'',[DataType] =N'string',[JiViColumn] =N'RosterGroupName',[MappingData] =N'' WHERE ConfigId = 39

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 40)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (40,2, N'RosterExport', N'40', N'Effective From', N'',N'DateTime',N'EffectiveFrom',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Effective From',[DefaultValue] =N'',[DataType] =N'DateTime',[JiViColumn] =N'EffectiveFrom',[MappingData] =N'' WHERE ConfigId = 40

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 41)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (41,2, N'RosterExport', N'41', N'Effective To', N'',N'DateTime',N'EffectiveTo',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [ColumnName] = N'Effective To',[DefaultValue] =N'',[DataType] =N'DateTime',[JiViColumn] =N'EffectiveTo',[MappingData] =N'' WHERE ConfigId = 41

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 42)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 42

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 43)
   DELETE [IE_ExportFileConfig]  WHERE ConfigId = 43

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 44)
   DELETE [IE_ExportFileConfig]  WHERE ConfigId = 44

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 45)
   DELETE [IE_ExportFileConfig]  WHERE ConfigId = 45

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 46)
   DELETE [IE_ExportFileConfig]  WHERE ConfigId = 46

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 47)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 47

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 48)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 48

IF EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 49)
   DELETE [IE_ExportFileConfig] WHERE ConfigId = 49
--------------------------------- OT Export----------------------------------------
IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 50)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (50,1, N'TimeAttendanceExport', N'8', N'Actual Frm Dt', N'',N'Date',N'ActualStartDate',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'8',[ColumnName] = N'Actual Frm Dt',[DefaultValue] =N'',[DataType] =N'Date',[JiViColumn] =N'ActualStartDate',[MappingData] =N'' WHERE ConfigId = 50

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 51)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (51,1, N'TimeAttendanceExport', N'9', N'Actual Frm Time', N'',N'Date',N'ActualStartTime',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'9',[ColumnName] = N'Actual Frm Time',[DefaultValue] =N'',[DataType] =N'Time',[JiViColumn] =N'ActualStartTime',[MappingData] =N'' WHERE ConfigId = 51

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 52)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (52,1, N'TimeAttendanceExport', N'10', N'Actual To Dt', N'',N'Date',N'ActualEndDate',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'10',[ColumnName] = N'Actual To Dt',[DefaultValue] =N'',[DataType] =N'Date',[JiViColumn] =N'ActualEndDate',[MappingData] =N'' WHERE ConfigId = 52

IF NOT EXISTS (SELECT * FROM IE_ExportFileConfig WHERE ConfigId = 53)
	INSERT [dbo].[IE_ExportFileConfig] ([ConfigId], [FileId], [FileName], [SortSequence], [ColumnName], [DefaultValue],[DataType],[JiViColumn],[MappingData],
	[CreatedBy],[CreatedDate]) 
	VALUES (53,1, N'TimeAttendanceExport', N'11', N'Actual To Time', N'',N'Time',N'ActualEndTime',N'', 'Script Migration', GETDATE())	
ELSE UPDATE [IE_ExportFileConfig] SET [SortSequence] =N'11',[ColumnName] = N'Actual To Time',[DefaultValue] =N'',[DataType] =N'Time',[JiViColumn] =N'ActualEndTime',[MappingData] =N'' WHERE ConfigId = 53

SET IDENTITY_INSERT [dbo].[IE_ExportFileConfig] OFF
GO

SET IDENTITY_INSERT [dbo].[D_PayCodeType] ON 

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 1)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (1,N'Normal Hours',N'Normal Hours',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 1

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 2)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (2,N'Overtime',N'Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 2

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 3)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (3,N'Public Holiday',N'Public Holiday',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 3

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 4)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (4,N'Premium OverTime',N'Premium OverTime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 4

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 5)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (5,N'RamadanNormal',N'Ramadan Normal',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 5

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 6)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (6,N'Leave',N'Leave',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 6

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 7)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (7,N'Night Overtime',N'Night Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 7

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 8)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (8,N'Acting Incentive',N'Acting Incentive',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 8

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 9)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (9,N'Ramadan Overtime',N'Ramadan Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 9

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 10)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (10,N'Ramadan Premium Overtime',N'Ramadan Premium Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 10

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 11)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (11,N'Ramadan Night Overtime',N'Ramadan Night Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 11

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 12)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (12,N'Ramadan Public Holiday',N'Ramadan Public Holiday',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 12

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 13)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (13,N'Crane Jerk Incentive',N'Crane Jerk Incentive',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 13

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 14)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (14,N'Shift Band Overtime',N'Shift Band Overtime',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 14

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 15)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (15,N'Allowance',N'Allowance',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 15

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 16)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (16,N'RTG Regular OT',N'RTG Regular OT',1,1,N'RTGO', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'RTG Regular OT',[Description] =N'RTG Regular OT',[PaycodeTypeValue]=1, [SkillName] = N'RTGO',[DefaultValue]=N'' WHERE PaycodeTypeId = 16

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 17)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (17,N'Rest Day 1.5',N'Rest Day 1.5',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'Rest Day 1.5',[Description] =N'Rest Day 1.5',[PaycodeTypeValue]=1,[SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 17

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 18)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (18,N'Rest Day 2.5',N'Rest Day 2.5',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'Rest Day 2.5',[Description] =N'Rest Day 2.5',[PaycodeTypeValue]=1,[SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 18

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 19)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (19,N'Public Holiday 2.0',N'Public Holiday 2.0',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'Public Holiday 2.0',[Description] =N'Public Holiday 2.0',[PaycodeTypeValue]=1,[SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 19

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 20)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (20,N'Public Holiday 3.0',N'Public Holiday 3.0',1,1,N'', 'Script Migration', GETDATE(),N'')	
ELSE UPDATE [D_PayCodeType] SET  [PaycodeType] =N'Public Holiday 3.0',[Description] =N'Public Holiday 3.0',[PaycodeTypeValue]=1,[SkillName] = N'',[DefaultValue]=N'' WHERE PaycodeTypeId = 20

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 21)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (21,N'Jerk OT',N'Jerk OT',1,1,N'', 'Script Migration', GETDATE(),N'240')	
ELSE UPDATE [D_PayCodeType] SET  [PaycodeType] =N'Jerk OT',[Description] =N'Jerk OT',[PaycodeTypeValue]=1,[SkillName] = N'',[DefaultValue]=N'240' WHERE PaycodeTypeId = 21

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 22)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (22,N'Shift Allowance',N'Shift Allowance',1,2,N'', 'Script Migration', GETDATE(),N'60')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'Shift Allowance',[Description] =N'Shift Allowance',[PaycodeTypeValue]=2,[SkillName] = N'',[DefaultValue]=N'60' WHERE PaycodeTypeId = 22

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 23)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (23,N'RP Allowance',N'RP Allowance',1,2,N'QCO:4,RTGO:4', 'Script Migration', GETDATE(),N'60')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'RP Allowance',[Description] =N'RP Allowance',[PaycodeTypeValue]=2,[SkillName] = N'QCO:4,RTGO:4',[DefaultValue]=N'60' WHERE PaycodeTypeId = 23

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 24)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (24,N'M2M Allowance',N'M2M Allowance',1,2,N'RTGO', 'Script Migration', GETDATE(),N'60')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'M2M Allowance',[Description] =N'M2M Allowance',[PaycodeTypeValue]=2,[SkillName] = N'RTGO',[DefaultValue]=N'60' WHERE PaycodeTypeId = 24

IF NOT EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 25)
	INSERT [dbo].[D_PayCodeType] ([PaycodeTypeId], [PaycodeType], [Description], [ActiveStatus], [PaycodeTypeValue], [SkillName],[CreatedBy],[CreatedDate],[DefaultValue]) 
	VALUES (25,N'Meal Allowance',N'Meal Allowance',1,2,N'RTGO', 'Script Migration', GETDATE(),N'60')	
ELSE UPDATE [D_PayCodeType] SET [PaycodeType] =N'Meal Allowance',[Description] =N'Meal Allowance',[PaycodeTypeValue]=2,[SkillName] = N'RTGO',[DefaultValue]=N'60' WHERE PaycodeTypeId = 25

IF EXISTS (SELECT * FROM D_PayCodeType WHERE PaycodeTypeId = 26 AND  [PaycodeType] =N'Meal Allowance')
	DELETE FROM D_PayCodeType WHERE PaycodeTypeId = 26 AND  [PaycodeType] =N'Meal Allowance'

SET IDENTITY_INSERT [dbo].[D_PayCodeType] OFF
GO

BEGIN
	--Password Policy
	IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 30425)
	BEGIN 
		DELETE FROM C_SecurityRolePermissions WHERE MenuId = 30425	   
		DELETE FROM C_Menu where MenuID = 30425	
	END	

	--Panel Clinic Setup
	IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 20425)
	BEGIN
		DELETE FROM C_SecurityRolePermissions WHERE MenuId = 20425
		DELETE FROM C_Menu where MenuID = 20425	
	END

	--Operations Audit	
	IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 10423) 
	BEGIN
		DELETE FROM C_SecurityRolePermissions WHERE MenuId = 10423
		DELETE FROM C_Menu where MenuID = 10423
	END

	--Shift Trimming
	IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 10422) 
	BEGIN
		DELETE FROM C_SecurityRolePermissions WHERE MenuId = 10422
		DELETE FROM C_Menu where MenuID = 10422
	END

	-- UnControlled Leave
	--IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 10425) 
	--BEGIN
	--	DELETE FROM C_SecurityRolePermissions WHERE MenuId = 10425
	--	DELETE FROM C_Menu where MenuID = 10425
	--END

	----Upload Uncontrolled Leave
	--IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 10426)
	--BEGIN
	--	DELETE FROM C_SecurityRolePermissions WHERE MenuId = 10426
	--	DELETE FROM  C_Menu where MenuID = 10426

	--END

	----Manage Uncontrolled Leave
	--IF EXISTS(SELECT * FROM C_SecurityRolePermissions WHERE MenuId = 10427)
	--BEGIN
	--	DELETE FROM C_SecurityRolePermissions WHERE MenuId = 10427		
	--	DELETE FROM C_Menu where MenuID = 10427
	--END
END
GO 
IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_TA_Rawclocking_TypeSwipeDateEmpId' AND object_id = OBJECT_ID('TA_Rawclocking'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_TA_Rawclocking_TypeSwipeDateEmpId]
	ON [dbo].[TA_Rawclocking] ([TypeId],[SwipeDateTime],[EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_EmployeeLeaves_ShiftId' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_EmployeeLeaves_ShiftId]
	ON [dbo].[S_EmployeeLeaves] ([ShiftId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Shifts_EmployeeId_ShiftBandId' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Shifts_EmployeeId_ShiftBandId]
	ON [dbo].[S_Shifts] ([OUId],[ShiftStartTime])
	INCLUDE ([EmployeeId],[ShiftBandId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_Dashboard' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_Dashboard]
	ON [dbo].[S_Shifts] ([OUId],[ActualStartTime])
	INCLUDE ([RoleId],[ShiftBandId],[ActualEndTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_Dashboard' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_Dashboard]
	ON [dbo].[S_Shifts] ([OUId],[PickedByTHP],[ActualStartTime])
	INCLUDE ([EmployeeId],[ShiftBandId],[CombinationShiftId])
END

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_PendingReconShifts' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_PendingReconShifts]
	ON [dbo].[S_Shifts] ([OUId],[RoleId])
	INCLUDE ([EmployeeId],[ShiftBandId],[ShiftStartTime],[ShiftEndTime],[ActualStartTime],[ActualEndTime],[OnCallShift],[CombinationShiftId],[ReconStatusId],[Reconciled])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_RBRRank' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_RBRRank]
	ON [dbo].[S_Shifts] ([RBRRank])
	INCLUDE ([EmployeeId],[ActualStartTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_EmployeeLeaves_OUDate' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_EmployeeLeaves_OUDate]
	ON [dbo].[S_EmployeeLeaves] ([OUId],[FromDate])
	INCLUDE ([EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_EmployeeRoles_EmployeeId' AND object_id = OBJECT_ID('C_EmployeeRoles'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_EmployeeRoles_EmployeeId]
	ON [dbo].[C_EmployeeRoles] ([EmployeeId])
	INCLUDE ([RoleId],[IsPrimaryRole])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_ForShift' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_ForShift]
	ON [dbo].[J_Activity] ([WorkloadId])
	INCLUDE ([StartTime],[ShiftId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_StartEndTime' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_StartEndTime]
	ON [dbo].[S_Shifts] ([ActualStartTime],[ActualEndTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_SkillShiftBandAllocationNo' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_SkillShiftBandAllocationNo]
	ON [dbo].[J_Activity] ([OUId],[WorkType],[ProgresstionState],[StartTime],[EndTime],[ShiftId])
	INCLUDE ([SkillId],[ShiftBandId],[AllocationNo])
END
GO


IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_ScheduleId' AND object_id = OBJECT_ID('J_ActivityAttributes'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_ScheduleId]
	ON [dbo].[J_ActivityAttributes] ([ActivityId])
	INCLUDE ([ScheduleId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_THPEmployeeDetails_ShiftDate' AND object_id = OBJECT_ID('S_THPEmployeeDetails'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_THPEmployeeDetails_ShiftDate]
	ON [dbo].[S_THPEmployeeDetails] ([ShiftDate])
	INCLUDE ([EmployeeId],[ShiftCounter],[ActivityCounter])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Activity_With_ShiftId' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Activity_With_ShiftId]
	ON [dbo].[J_Activity] ([ShiftId])
END
GO


IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_Search_Condition' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_Search_Condition]
	ON [dbo].[S_Shifts] ([OUId],[ActualStartTime],[ActualEndTime])
	INCLUDE ([EmployeeId],[RoleId],[ShiftBandId],[ShiftStartTime],[ShiftEndTime],[OnCallShift],[Notes],[ShiftCost])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_TRN_ApprovalRouteDetails_UserAndActionDate' AND object_id = OBJECT_ID('W_TRN_Approval_RouteDetails'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_TRN_ApprovalRouteDetails_UserAndActionDate]
	ON [dbo].[W_TRN_Approval_RouteDetails] ([UserAction],[ActionDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_L_Leaves_SendEmail_PendingForApproval' AND object_id = OBJECT_ID('L_Leaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_L_Leaves_SendEmail_PendingForApproval]
	ON [dbo].[L_Leaves] ([ApprovalStatusId])
	INCLUDE ([ExceptionCodeId],[LeaveStart],[LeaveEnd],[NoOfDays],[AppliedDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_L_RequestDaysInLieu_SendEmail_PendingForApproval' AND object_id = OBJECT_ID('L_RequestDaysInLieu'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_L_RequestDaysInLieu_SendEmail_PendingForApproval]
	ON [dbo].[L_RequestDaysInLieu] ([ApprovalStatusId])
	INCLUDE ([RequestedDate],[AppliedDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'CIDX_J_Activity_Operations' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [CIDX_J_Activity_Operations]
	ON [dbo].[J_Activity] ([OUId],[WorkType],[ProgresstionState],[StartTime],[EndTime],[ShiftId])
	INCLUDE ([SkillId],[ShiftBandId],[AllocationNo])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'CIDX_J_ActivityAttributes' AND object_id = OBJECT_ID('J_ActivityAttributes'))
BEGIN
	CREATE NONCLUSTERED INDEX [CIDX_J_ActivityAttributes]
	ON [dbo].[J_ActivityAttributes] ([ActivityId])
	INCLUDE ([ScheduleId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'CIDX_S_Shifts_Operations' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [CIDX_S_Shifts_Operations]
	ON [dbo].[S_Shifts] ([OUId],[ActualStartTime],[ActualEndTime])
	INCLUDE ([EmployeeId],[RoleId],[ShiftBandId],[CombinationShiftId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_THPEmployeeDetails_Deployment' AND object_id = OBJECT_ID('S_THPEmployeeDetails'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_THPEmployeeDetails_Deployment]
	ON [dbo].[S_THPEmployeeDetails] ([EmployeeId],[ShiftDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_THPEmployeeSkillDetails_Deployment' AND object_id = OBJECT_ID('S_THPEmployeeSkillDetails'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_THPEmployeeSkillDetails_Deployment]
	ON [dbo].[S_THPEmployeeSkillDetails] ([EmployeeId],[ShiftDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_EmployeeLeaves_Report' AND object_id = OBJECT_ID('C_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_EmployeeLeaves_Report]
	ON [dbo].[C_Employee] ([OUId],[IsTerminated])
	INCLUDE ([EmployeeNumber],[DisplayName])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_SecurityRolePermissions' AND object_id = OBJECT_ID('C_SecurityRolePermissions'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_SecurityRolePermissions]
	ON [dbo].[C_SecurityRolePermissions] ([PermissionTypeId])
	INCLUDE ([SecurityRoleId],[MenuId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_UserSecurityRoleOU_OUId' AND object_id = OBJECT_ID('C_UserSecurityRoleOU'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_UserSecurityRoleOU_OUId]
	ON [dbo].[C_UserSecurityRoleOU] ([OUId])
	INCLUDE ([UserSecurityRoleId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_SecurityRolePermissions_SecurityRoleId' AND object_id = OBJECT_ID('C_SecurityRolePermissions'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_SecurityRolePermissions_SecurityRoleId]
	ON [dbo].[C_SecurityRolePermissions] ([SecurityRoleId])
	INCLUDE ([MenuId],[PermissionTypeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_Employee_AddShift' AND object_id = OBJECT_ID('C_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_Employee_AddShift]
	ON [dbo].[C_Employee] ([OUId])
	INCLUDE ([RosterGroupId],[EmployeeNumber],[DisplayName],[HourlyRate],[ContractedHours])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_SearchCondition' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_SearchCondition]
	ON [dbo].[S_Shifts] ([OUId],[ActualStartTime],[ActualEndTime])
	INCLUDE ([EmployeeId],[RoleId],[ShiftBandId],[CombinationShiftId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_EmployeeLeaves_EmployeeId' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_EmployeeLeaves_EmployeeId]
	ON [dbo].[S_EmployeeLeaves] ([OUId],[FromDate],[EndDate])
	INCLUDE ([EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_Employee_OU_RosterGroup' AND object_id = OBJECT_ID('C_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_Employee_OU_RosterGroup]
	ON [dbo].[C_Employee] ([OUId])
	INCLUDE ([EmployeeId],[RosterGroupId],[EmployeeNumber],[DisplayName],[HourlyRate],[ContractedHours])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_OUShiftBand' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_OUShiftBand]
	ON [dbo].[J_Activity] ([OUId],[ShiftBandId],[WorkType],[StartTime],[EndTime])
	INCLUDE ([ActivityId],[SkillId],[ShiftId],[AllocationNo])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_LiveRanking' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_LiveRanking]
	ON [dbo].[S_Shifts] ([OUId],[ShiftStartTime],[ShiftEndTime])
	INCLUDE ([ShiftId],[EmployeeId],[RoleId],[ShiftBandId],[ActualStartTime],[ActualEndTime],[RBRRank])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_LiveRanking_RoleId' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_LiveRanking_RoleId]
	ON [dbo].[S_Shifts] ([OUId],[RoleId],[ShiftStartTime],[ShiftEndTime])
	INCLUDE ([ShiftId],[EmployeeId],[ShiftBandId],[ActualStartTime],[ActualEndTime],[RBRRank])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_EmployeeWorkflow_EmployeeId' AND object_id = OBJECT_ID('C_EmployeeWorkflow'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_EmployeeWorkflow_EmployeeId]
	ON [dbo].[C_EmployeeWorkflow] ([EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_ShiftValidations_ShiftDate' AND object_id = OBJECT_ID('S_ShiftValidations'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_ShiftValidations_ShiftDate]
	ON [dbo].[S_ShiftValidations] ([ShiftDate])
	INCLUDE ([ShiftId],[EmployeeId],[SchedulePeriodId],[IsError],[ErrorId],[ErrorDesc],[CreatedBy],[CreatedDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_Employee_UserId' AND object_id = OBJECT_ID('C_User'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_Employee_UserId]
	ON [dbo].[C_User] ([EmployeeID])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_A_Employee_ActionDate' AND object_id = OBJECT_ID('A_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_A_Employee_ActionDate]
	ON [dbo].[A_Employee] ([EmployeeId], [ActionDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_M_EquipmentSchedule_EquipmentId' AND object_id = OBJECT_ID('M_EquipmentSchedule'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_M_EquipmentSchedule_EquipmentId]
	ON [dbo].[M_EquipmentSchedule] ([EquipmentId])
	INCLUDE ([StartDate],[EndDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_M_EquipmentSchedule_CreatedByDate' AND object_id = OBJECT_ID('M_EquipmentSchedule'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_M_EquipmentSchedule_CreatedByDate]
	ON [dbo].[M_EquipmentSchedule] ([CreatedDate],[CreatedBy])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Workload_OUSkillWorkType' AND object_id = OBJECT_ID('J_Workload'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Workload_OUSkillWorkType]
	ON [dbo].[J_Workload] ([OUId],[SkillId],[WorkType])
	INCLUDE ([StartTime],[EndTime],[CraneScheduleId],[EquipmentScheduleId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_StartTime_CreatedBy' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_StartTime_CreatedBy]
	ON [dbo].[J_Activity] ([CreatedBy],[StartTime])
	INCLUDE ([OUId],[SkillId],[ShiftBandId],[EndTime],[WorkType],[ShiftId],[RuleId],[GroupNo],[AllocationNo],[ProgresstionState],[DeployedDate],[DeployedUser],[CreatedDate],[UpdatedBy],[UpdatedDate],[WorkloadId],[RBRRank])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_OURoleEmpStartEndTimes' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_OURoleEmpStartEndTimes]
	ON [dbo].[S_Shifts] ([OUId],[EmployeeId],[RoleId],[ActualStartTime],[ActualEndTime])
	INCLUDE ([ShiftBandId],[CombinationShiftId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_L_EmployeeLeaveProfiles_YearExceptionId' AND object_id = OBJECT_ID('L_EmployeeLeaveProfiles'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_L_EmployeeLeaveProfiles_YearExceptionId]
	ON [dbo].[L_EmployeeLeaveProfiles] ([LeaveYear],[ExceptionId])
	INCLUDE ([EmployeeId],[LeaveProfileId],[EntitlementDays],[CarryForwardDays],[EarnedDays],[DaysUsed],[BalanceDays])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_EmployeeWorkflow_EmpModuleDates' AND object_id = OBJECT_ID('C_EmployeeWorkflow'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_EmployeeWorkflow_EmpModuleDates]
	ON [dbo].[C_EmployeeWorkflow] ([EmployeeId],[ModuleId],[StartDate],[EndDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_EmployeeLeaveProfile_EmployeeId' AND object_id = OBJECT_ID('C_EmployeeLeaveProfile'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_EmployeeLeaveProfile_EmployeeId]
	ON [dbo].[C_EmployeeLeaveProfile] ([EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_L_Leaves_StartEndApprStatus' AND object_id = OBJECT_ID('L_Leaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_L_Leaves_StartEndApprStatus]
	ON [dbo].[L_Leaves] ([LeaveStart],[LeaveEnd],[ApprovalStatusId])
	INCLUDE ([EmployeeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_Employee_RosterGroupId' AND object_id = OBJECT_ID('C_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_Employee_RosterGroupId]
	ON [dbo].[C_Employee] ([RosterGroupId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_L_Leaves_EmpStartEndAppStatusId' AND object_id = OBJECT_ID('L_Leaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_L_Leaves_EmpStartEndAppStatusId]
	ON [dbo].[L_Leaves] ([EmployeeId],[LeaveStart],[LeaveEnd],[ApprovalStatusId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Activity_MaxGroup_Allocation_No' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Activity_MaxGroup_Allocation_No]
	ON [dbo].[J_Activity] ([ShiftBandId],[StartTime])
	INCLUDE ([GroupNo],[AllocationNo])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_M_VesselSchedule_BerthId' AND object_id = OBJECT_ID('M_VesselSchedule'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_M_VesselSchedule_BerthId]
	ON [dbo].[M_VesselSchedule] ([BerthId])
	INCLUDE ([OUId],[VesselName],[VisitId],[StartDate],[EndDate],[ETA],[ETD],[NoOfCraneReq],[Priority],[Status],[CraneScheduled],[ResourceSetId],[IsImported],[CreatedBy],[CreatedDate],[UpdatedBy],[UpdatedDate],[VesselType],[Remarks])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Workload_VesselScheduleId_SkillId' AND object_id = OBJECT_ID('J_Workload'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Workload_VesselScheduleId_SkillId]
	ON [dbo].[J_Workload] ([VesselScheduleId])
	INCLUDE ([SkillId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_J_Workload_CraneScheduleId' AND object_id = OBJECT_ID('J_Workload'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_J_Workload_CraneScheduleId]
	ON [dbo].[J_Workload] ([CraneScheduleId])
END
GO


IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_Employee_OUId_OvertimeId' AND object_id = OBJECT_ID('C_Employee'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_Employee_OUId_OvertimeId]
	ON [dbo].[C_Employee] ([OUId])
	INCLUDE ([EmployeeNumber],[DisplayName],[OvertimeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_ShiftCount_Summary' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_ShiftCount_Summary]
	ON [dbo].[S_Shifts] ([OUId],[RoleId],[ActualStartTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_ResourceCount_Summary' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_ResourceCount_Summary]
	ON [dbo].[J_Activity] ([OUId],[StartTime])
	INCLUDE ([SkillId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_LeaveCount_Summary' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_LeaveCount_Summary]
	ON [dbo].[S_EmployeeLeaves] ([OUId],[FromDate])
	INCLUDE ([ExceptionCodeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Search_EmployeeRoster' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Search_EmployeeRoster]
	ON [dbo].[S_Shifts] ([OUId],[ShiftBandId],[ActualStartTime],[ActualEndTime])
	INCLUDE ([EmployeeId],[RoleId],[ShiftStartTime],[ShiftEndTime],[OnCallShift],[Notes],[ReconStatusId],[Reconciled],[ShiftCost],[RBRRank])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Search_EmployeeShifts' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Search_EmployeeShifts]
	ON [dbo].[S_Shifts] ([ActualStartTime],[ActualEndTime])
	INCLUDE ([OUId],[ShiftBandId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_C_EmployeeSkills_EmployeeRoster' AND object_id = OBJECT_ID('C_EmployeeSkills'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_C_EmployeeSkills_EmployeeRoster]
	ON [dbo].[C_EmployeeSkills] ([IsPrimary])
	INCLUDE ([EmployeeId],[SkillId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_SchedulePeriod_ByPeriodNo' AND object_id = OBJECT_ID('S_SchedulePeriod'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_SchedulePeriod_ByPeriodNo]
	ON [dbo].[S_SchedulePeriod] ([OUId],[ScheduleRuleId],[StartDate],[EndDate])
	INCLUDE ([PeriodNo])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_SchedulePeriod_ShiftsByEmployee' AND object_id = OBJECT_ID('S_SchedulePeriod'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_SchedulePeriod_ShiftsByEmployee]
	ON [dbo].[S_SchedulePeriod] ([OUId],[ScheduleRuleId],[StartDate],[EndDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_SchedulePeriod_ScheduleRuleId' AND object_id = OBJECT_ID('S_SchedulePeriod'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_SchedulePeriod_ScheduleRuleId]
	ON [dbo].[S_SchedulePeriod] ([OUId],[ScheduleRuleId])
	INCLUDE ([EndDate],[PeriodNo])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_RawClocking_Search' AND object_id = OBJECT_ID('TA_Rawclocking'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_RawClocking_Search]
	ON [dbo].[TA_Rawclocking] ([EmployeeId],[SwipeDateTime])
	INCLUDE ([TypeId],[CardNo],[TerminalName],[EmployeeNo],[CollectionDateTime],[Allocated],[ReconDate],[ReconBy],[CreatedBy],[CreatedDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_S_Shifts_ShiftTrimming' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_S_Shifts_ShiftTrimming]
	ON [dbo].[S_Shifts] ([ShiftStartTime])
	INCLUDE ([EmployeeId],[RoleId],[ShiftBandId],[ShiftEndTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_HR_Attendance_Report' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_HR_Attendance_Report]
	ON [dbo].[S_Shifts] ([ShiftStartTime])
	INCLUDE ([ShiftId],[OUId],[EmployeeId],[RoleId],[ShiftBandId],[ShiftEndTime],[InStatus],[OutStatus],[InTime],[OutTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_AvailableShiftsFor_PMDeployment' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_AvailableShiftsFor_PMDeployment]
	ON [dbo].[S_Shifts] ([ShiftBandId],[ActualStartTime])
	INCLUDE ([EmployeeId],[ActualEndTime])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Leave_ShiftCount_Report' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Leave_ShiftCount_Report]
	ON [dbo].[S_Shifts] ([OUId],[ShiftStartTime],[ShiftEndTime])
	INCLUDE ([RoleId],[RosterGroupId],[OnCallShift])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_EmployeeMessages_Search' AND object_id = OBJECT_ID('C_EmployeeMessages'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_EmployeeMessages_Search]
	ON [dbo].[C_EmployeeMessages] ([MessageId])
	INCLUDE ([EmployeeId],[EnableMessages],[EnableEmails],[EnablePushNotifications],[IsMessagesDisabledByUser],[MessagesDisabledDate],[IsEmailDisabledByUser],[EmailDisabledDate],[IsPushNotificationsDisabledByUser],[PushNotificationsDisabledDate],[ActiveStatus])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_QC_FinalBookingReport' AND object_id = OBJECT_ID('C_EmployeeSkills'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_QC_FinalBookingReport]
	ON [dbo].[C_EmployeeSkills] ([EmployeeId])
	INCLUDE ([SkillId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_User_ActiveStatus' AND object_id = OBJECT_ID('C_User'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_User_ActiveStatus]
	ON [dbo].[C_User] ([UserName],[IsActive])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_EmployeeShifts_LastRBR_Rank' AND object_id = OBJECT_ID('S_Shifts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_EmployeeShifts_LastRBR_Rank]
	ON [dbo].[S_Shifts] ([OUId],[EmployeeId],[ActualStartTime],[RBRRank])
END
GO


IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_ShiftTrimming_ShiftAndDate' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_ShiftTrimming_ShiftAndDate]
	ON [dbo].[S_EmployeeLeaves] ([ShiftId],[FromDate])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_FinalBookingReport_ActivitySkill' AND object_id = OBJECT_ID('J_Activity'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_FinalBookingReport_ActivitySkill]
	ON [dbo].[J_Activity] ([SkillId])
	INCLUDE ([StartTime],[EndTime],[WorkType],[ShiftId],[GroupNo],[AllocationNo],[WorkloadId],[RBRRank],[LocationId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_PShiftCosts_ShiftReport' AND object_id = OBJECT_ID('P_ShiftCosts'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_PShiftCosts_ShiftReport]
	ON [dbo].[P_ShiftCosts] ([ShiftId])
	INCLUDE ([PayCodeId],[ActualHour])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_SEmployeeLeaves_ShiftReport_EmployeeExecpId' AND object_id = OBJECT_ID('S_EmployeeLeaves'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_SEmployeeLeaves_ShiftReport_EmployeeExecpId]
	ON [dbo].[S_EmployeeLeaves] ([FromDate])
	INCLUDE ([EmployeeId],[ExceptionCodeId])
END
GO

IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_Workload_SkillShiftBandWorkType' AND object_id = OBJECT_ID('J_Workload'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_Workload_SkillShiftBandWorkType]
	ON [dbo].[J_Workload] ([OUId],[SkillId],[WorkType],[ShiftBandId])
	INCLUDE ([StartTime],[EndTime],[EquipmentScheduleId],[LocationId])
END
GO


IF NOT EXISTS(SELECT * FROM sys.indexes WHERE name = 'NCIDX_THPEmployeePeriods_EmployeeId' AND object_id = OBJECT_ID('S_THPEmployeePeriods'))
BEGIN
	CREATE NONCLUSTERED INDEX [NCIDX_THPEmployeePeriods_EmployeeId]
	ON [dbo].[S_THPEmployeePeriods] ([OUId],[PeriodStart],[PeriodEnd])
	INCLUDE ([EmployeeId])
END
GO

Anon7 - 2022
AnonSec Team