USE [APTIFY]
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_GetInterestAreas] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_GetInterestAreas]
as
select 
    tc.ID [ID], tc.Name [Name]
from 
	dbo.TopicCode tc
	inner join 
	dbo.TopicCodeEntity tce on tce.TopicCodeID = tc.ID
	inner join
	dbo.Entity e on e.ID = tce.EntityID
where 
	e.Name = 'Persons'
	and
	tc.[Status] = 'Active'
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_InsertTrackingActivity] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_InsertTrackingActivity]
(
	@TrackingActivityId bigint,
	@ActivityCode varchar(20),
	@ActivitySubCode varchar(50),
	@CustomMemberId varchar(50),
	@EmailAddress varchar(100),
	@RecipientId bigint,
	@DateStampUTC datetime,
	@UnsubscribeCategory varchar(50),
	@GroupName varchar(50),
	@MessageName varchar(50),
	@LinkUrl varchar(1500),
	@LinkLabel varchar(50),
	@MessageCategory varchar(50)
)
as
if isnumeric(@CustomMemberId) <> 1
	return;

declare @PersonID int = Cast(@CustomMemberId as int)

insert into dbo.RealMagnetTrackingActivity
(
	TrackingActivityId, 
	ActivityCode, 
	ActivitySubCode, 
	CustomMemberId, 
	EmailAddress, 
	RecipientId, 
	ActivityDateTime, 
	UnsubscribeCategory, 
	GroupName, 
	MessageName,
	LinkUrl, 
	LinkLabel,
	MessageCategory 
)
values
(
	@TrackingActivityId,
	@ActivityCode, 
	@ActivitySubCode,
	@PersonID, 
	@EmailAddress, 
	@RecipientId, 
	@DateStampUTC,
	@UnsubscribeCategory, 
	@GroupName, 
	@MessageName,
	@LinkUrl, 
	@LinkLabel,
	@MessageCategory
)
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_UpdateInterestAreaSubscription] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_UpdateInterestAreaSubscription]
(
	@TrackingActivityID bigint,
	@ActivityCode varchar(20),
	@ActivitySubCode varchar(50),
	@CustomMemberID varchar(50),
	@DateStampUTC datetime,
	@InterestAreaID varchar(50)
)
as
if isnumeric(@CustomMemberId) <> 1
	return;

declare @PersonID int = cast(@CustomMemberID as int)
declare @TopicCodeID int = cast(@InterestAreaID as int)

if @PersonID is not null and @TopicCodeID is not null and (@ActivityCode = 'Unsubscribed' or @ActivityCode = 'Subscribed') 
begin
	declare @IsSet nvarchar(10) 
	declare @PersonsEntityID int
	
	set @PersonsEntityID = (select E.ID from dbo.Entities E where E.Name = 'Persons')
	
	if @ActivityCode = 'Unsubscribed' set @IsSet = 'No'
	else set @IsSet = 'Yes'
	
	if (exists (select 1 from dbo.TopicCode tc where tc.ID = @TopicCodeID and tc.[Status] = 'Active' and tc.ValueType = 'Yes/No'))
	   and
	   (not exists (select 1 from dbo.TopicCodeLink tcl inner join  dbo.TopicCode tc on tc.ID = tcl.TopicCodeID 
	                where tcl.EntityID = @PersonsEntityID AND tcl.RecordID = @PersonID and tcl.TopicCodeID = @TopicCodeID))
	begin
		insert into dbo.TopicCodeLink (EntityID, RecordID, TopicCodeID, DateAdded, [Status], Value)
		values (@PersonsEntityID, @PersonID, @TopicCodeID, @DateStampUTC, 'Active', @IsSet)
	end
	else
	begin
		update tcl set tcl.Value = @IsSet
		from dbo.TopicCodeLink tcl 
		inner join dbo.TopicCode tc on tc.ID = tcl.TopicCodeID
		where
			tc.[Status] = 'Active' AND
			tc.startdate <= GETDATE() AND
			(tc.enddate >= GETDATE() OR
				tc.enddate = '19000101' OR
				tc.enddate IS NULL
			) AND
			tc.ValueType = 'Yes/No' AND
			tcl.EntityID = @PersonsEntityID AND
			tcl.RecordID = @PersonID AND
			tcl.TopicCodeID = @TopicCodeID
	end
end
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_GetEntities] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_GetEntities]
(
	@LoginName varchar(100)
)
as
select convert(varchar(20),e.ID) [ID], e.Name [Name]
from dbo.Entities e
where e.Name = 'Persons'
union all
select 'Views', 'Views'
GO

/****** Object:  StoredProcedure [dbo].[RealMagnet_GetQueryData] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_GetQueryData]
(
	@LoginName varchar(100),
	@EntityID varchar(100),
	@QueryID varchar(100),
	@KindID varchar(100)
)
as

declare @ViewSql nvarchar(3500);

if @EntityID = 'Views'
	select 
		@ViewSql = 'select * from ' + quotename(S.name) + '.' + quotename(V.name) + ';'
	from
		sys.views V
		inner join
		sys.schemas S
			on S.schema_id = V.schema_id
	where V.object_id = @QueryID
else
	select 
		@ViewSql = [SQL] 
	from dbo.ViewSQL vs with(nolock)
		inner join dbo.[Views] v with(nolock) on v.ID = vs.ViewID and v.ID = @QueryID and v.EntityID = @EntityID
	
exec sys.sp_executesql @ViewSql
GO

/****** Object:  StoredProcedure [dbo].[RealMagnet_GetQueries] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_GetQueries]
(
	@LoginName varchar(100),
	@EntityID varchar(100)
)
as
if @EntityID = 'Views'
	select
		V.object_id as ID,
		V.name as Name,
		'SQL_View' as KindId,
		'SQL View' as KindName,
		S.schema_id as OwnerId,
		S.name as OwnerName
	from
		sys.views V
		inner join
		sys.schemas S
			on S.schema_id = V.schema_id
	where V.name like 'RealMagnet[_]%'
else
	select 
		v.ID,
		RTRIM(LTRIM(v.Name)) as [Name],
		'ViewSQL' [KindID],
		'ViewSQL' [KindName],
		v.OwnerID,
		v.OwnerID [OwnerName]
	from dbo.Views v with(nolock)
	inner join dbo.Entity e with(nolock) on e.ID = v.EntityID 
	inner join dbo.ViewSQL vsql with(nolock) on v.ID = vsql.ViewId
	inner join dbo.ViewCategories vc with(nolock) on vc.EntityID = v.EntityID and vc.Name like '%RealMagnet%' and vc.EnableSharing = 1 and v.ViewCategoryID = vc.ID
	inner join dbo.Users u with(nolock) on u.UserID = v.OwnerID or v.OwnerID = '-1'
	where v.EntityID = @EntityID and vsql.SQL not like '%PROMPT%'
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_GetFields] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_GetFields]
(
	@LoginName varchar(100),
	@EntityID varchar(100),
	@QueryID varchar(100),
	@KindID varchar(100)
)
as
if @EntityID = 'Views'
	select 
		C.name as ID,
		C.name as Name
	from 
		sys.columns C
	where 
		C.object_id = @QueryID
else
	select vf.FieldName as ID, vf.[Description] as Name from dbo.ViewFields vf with(nolock)
		inner join dbo.Views v with(nolock) 
			on v.ID = vf.ViewID and v.EntityID = @EntityID
	where
		v.ID = @QueryID	
GO
/****** Object:  StoredProcedure [dbo].[RealMagnet_InsertProspect] ******/
create type [dbo].[RealMagnet_NameValuePair] as table
(
	 Name nvarchar(50) NOT NULL PRIMARY KEY
	,Value nvarchar(200) NOT NULL
)
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[RealMagnet_InsertProspect]
(
	 @RecipientID bigint
	,@Properties RealMagnet_NameValuePair readonly
)
as

declare 
	 @first_name  nvarchar(200) = (select [Value] from @Properties where Name = 'FIRST_NAME')
	,@last_name   nvarchar(200) = (select [Value] from @Properties where Name = 'LAST_NAME')
	,@email_addr  nvarchar(200) = (select [Value] from @Properties where Name = 'EMAIL')
	,@phone       nvarchar(200) = (select [Value] from @Properties where Name = 'PHONE')
	,@fax         nvarchar(200) = (select [Value] from @Properties where Name = 'FAX')
	,@address1    nvarchar(200) = (select [Value] from @Properties where Name = 'ADDRESS1')
	,@address2    nvarchar(200) = (select [Value] from @Properties where Name = 'ADDRESS2')
	,@city        nvarchar(200) = (select [Value] from @Properties where Name = 'CITY')
	,@state       nvarchar(200) = (select [Value] from @Properties where Name = 'STATE')
	,@zip_code    nvarchar(200) = (select [Value] from @Properties where Name = 'ZIP')
	,@company     nvarchar(200) = (select [Value] from @Properties where Name = 'COMPANY')
	,@person_id   int = null 
	,@matches     int = 0
	,@address_id  int = null
	,@phone_id    int = null
	,@fax_id      int = null
	,@company_id  int = null
	;

select @matches = count(distinct ID) 
from dbo.Person 
where Email1 = @email_addr 
--	and FirstName = @first_name 
--	and LastName = @last_name
	;
	
if 1 = @matches
	begin
	
	select top 1 @RecipientID, ID, null as Message
	from Person
	where Email1 = @email_addr 
--		and FirstName = @first_name 
--		and LastName = @last_name
		;
	return ;

	end
	
if 1 < @matches
	begin
	
	select @RecipientID, null, 'Multiple matches found.'
	return ;

	end

if @company is not null
	begin
	
	select top 1 @company_id = ID from Company where Name = @company
	
	if @company_id is null
		begin

		exec dbo.spCreateCompany
			 @ID=@company_id output
			,@Name=@company
			,@AddressID=null
			,@logo=null
			,@MainPhoneID=null
			,@MainFaxID=null
			,@MainEmail=null
			,@InfoEmail=null
			,@JobsEmail=null
			,@WebSite=null
			,@BillingAddressID=null
			,@POBoxAddressID=null
			,@MailCode=null
			,@CRRT=null
			,@USCongress=null
			,@StateSenate=null
			,@StateHouse=null
			,@CountyDistrict=null
			,@JoinDate='1900-01-01 00:00:00.000'
			,@TerminationDate='1900-01-01 00:00:00.000'
			,@OrganizationID=null
			,@MainAccountManagerID=null
			,@VerifyStatus=null
			,@Established='1900-01-01 00:00:00.000'
			,@Revenue=0
			,@UnpubRevenue=0
			,@PrimaryProductCodeID=0
			,@SICCode=null
			,@OfficeType=null
			,@AbbreviatedName=null
			,@DivisionName=null
			,@FedTaxID=null
			,@OwnType=null
			,@PrimaryShareholder=null
			,@Atmosphere=null
			,@DirLetter=null
			,@DirSort=null
			,@DirDescription=null
			,@CreditLimit=0
			,@DnBRating=null
			,@BillingTerms=null
			,@APVendorID=null
			,@DomainName=null
			,@EmailPattern=null
			,@Directions=null
			,@OldID=null
			,@Comments=null
			;
		end
	end
	
if  @address1 is not null 
	or @address2 is not null 
	or @city is not null 
	or @state is not null
	or @zip_code is not null
	begin
	
	set @address1=coalesce(@address1,'');
	
	exec dbo.spCreateAddress
		 @address_id output
		,@AddressTypeID=2
		,@Line1=@address1
		,@Line2=@address2
		,@Line3=null
		,@Line4=null
		,@City=@city
		,@County=null
		,@StateProvince=@state
		,@PostalCode=@zip_code
		,@DefaultStartDate='1900-01-01 00:00:00.000'
		,@DefaultEndDate='1900-01-01 00:00:00.000'
		,@OwnerEntity=null
		,@OwnerRecordID=null
		;

	end
	
if @phone is not null
	begin

	insert into dbo.PhoneNumber(
		 AreaCode
		,CountryCode
		,Locked
		,Phone
		,PhoneExtension
		) values (
		 ''
		,''
		,0
		,@phone
		,''
		);

	select @phone_id=scope_identity();
		
	end

if @fax is not null
	begin

	insert into dbo.PhoneNumber(
		 AreaCode
		,CountryCode
		,Locked
		,Phone
		,PhoneExtension
		) values (
		 ''
		,''
		,0
		,@fax
		,''
		);

	select @fax_id=scope_identity();
		
	end
	
set @first_name=coalesce(@first_name,'')	

exec dbo.spCreatePerson
	 @ID=@person_id output
	,@Prefix=null
	,@photo=null
	,@FirstName=@first_name
	,@MiddleName=null
	,@LastName=@last_name
	,@Suffix=null
	,@CompanyID=@company_id
	,@Department=null
	,@Title=null
	,@AddressID=@address_id
	,@PhoneID=@phone_id
	,@FaxID=@fax_id
	,@CellPhoneID=null
	,@PagerPhoneID=null
	,@Email1=@email_addr
	,@Email2=null
	,@Email3=null
	,@BillingAddressID=null
	,@HomeAddressID=null
	,@HomePhoneID=null
	,@POBoxAddressID=null
	,@SocialSecurity=null
	,@MainAccountManager=null
	,@Ranking=0
	,@ReferredBy=null
	,@ReferralType=null
	,@WebSite=null
	,@Birthday='1900-01-01 00:00:00.000'
	,@Supervisor=null
	,@AssistantsName=null
	,@AssistantsPhoneID=null
	,@Nickname=null
	,@SpouseName=null
	,@Kids=null
	,@ImportantDate1='1900-01-01 00:00:00.000'
	,@ImportantDescription1=null
	,@ImportantDate2='1900-01-01 00:00:00.000'
	,@ImportantDescription2=null
	,@ImportantDate3='1900-01-01 00:00:00.000'
	,@ImportantDescription3=null
	,@Atmosphere=null
	,@MailCode=null
	,@CRRT=null
	,@USCongress=null
	,@StateSenate=null
	,@StateHouse=null
	,@CountyDistrict=null
	,@NextContactDate='1900-01-01 00:00:00.000'
	,@ContactManagerID=null
	,@VerifyStatus=null
	,@FunctionalTitle=null
	,@ContactRank=null
	,@DirRank=0
	,@PrimaryFunctionID=null
	,@JoinDate=null
	,@TerminationDate=null
	,@BillingTerms=null
	,@APVendorID=null
	,@Directions=null
	,@Comments=null
	,@CESScore=null
	;
	
select @RecipientId, cast( @person_id as varchar(50)), null
GO
