USE [cloudERP]
GO
/****** Object:  StoredProcedure [db_accounts].[pr_accountsgrouptree]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_accountsgrouptree] 1,1
-- =============================================
create PROCEDURE [db_accounts].[pr_accountsgrouptree] 
@coid int,
@boid int
AS
BEGIN
	SET NOCOUNT ON;
WITH x AS
(
    -- anchor:
    SELECT ID, name, parentgroupid, [level] = 0 FROM db_accounts.accountgroups WHERE isnull(parentgroupid,0)=0 and coid = @coid and boid = @boid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.name , t.parentgroupid,[level] = x.[level] + 1 FROM x INNER JOIN db_accounts.accountgroups AS t
    ON t.parentgroupid = x.ID where coid= @coid and boid=@boid
	
)
SELECT ID, name, parentgroupid parentid, [level] FROM x 
ORDER BY [level]
OPTION (MAXRECURSION 100);

	
END









GO
/****** Object:  StoredProcedure [db_accounts].[pr_CashBook]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_CashBook]  2,1,1,'2019-02-21','2019-05-25'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_CashBook] 
	@fyid int,
	@coid int,
	@boid int,
	@fromdate DATE,
	@todate DATE
AS
BEGIN
	SET NOCOUNT ON;
	
	declare @cashaccountid int, @mindate date, @maxdate date;

	select @cashaccountid = cashaccountid from db_general.company_control where coid = @coid and boid=@boid;

	IF OBJECT_ID('tempdb..#tempcashsummary') IS NOT NULL DROP TABLE #tempcashsummary
	create table #tempcashsummary 
	(
		cdate			varchar(10),
		openingbalance	decimal(15,2),
		rowtotal		decimal(15,2),
		cramount		decimal(15,2),
		dramount		decimal(15,2)
		
	);
	IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
	create table #tempvoucher 
	(
		ID				bigint,
		vno				VARCHAR(20),
		vdate			date,
		accountid		bigint,
		accounthead		varchar(200),
		narration		varchar(500),
		dramount		decimal(13,2),
		cramount		decimal(13,2),
		rowtotal		decimal(13,2),
		rowno			int
	);

--adding row into temporary cash summary table	
insert into #tempcashsummary (cdate,openingbalance,rowtotal,cramount,dramount) 
SELECT  TOP (DATEDIFF(DAY, @fromdate, @todate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @fromdate),0,0,0,0 
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

select @mindate = min(cdate), @maxdate = max(cdate) from #tempcashsummary

--adding row into temporary voucher table	
insert into #tempvoucher (id,vno,vdate,accountid,narration,dramount,cramount,rowno)
select id,(vouchertype+vouchercategory+ltrim(voucherno)) voucher,voucherdate,accountid,rtrim(narration),
(case when drcr = 'D' then voucheramount else 0 end) dramount, 
(case when drcr = 'C' then voucheramount else 0 end) cramount, 
ROW_NUMBER() OVER(ORDER BY voucherdate,voucherno) rownum 
from db_accounts.voucher where (voucherdate between @fromdate and @todate)
and vouchertype = 'C' and accountid <> @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid


-- update rowtotal 
update #tempvoucher set rowtotal = cramount -dramount 

-- update accounthead from accoutheads table in temp voucher table
update #tempvoucher set accounthead = a.accounthead 
from db_accounts.accountheads a where a.id = #tempvoucher.accountid


-- update opening balance from yearopening table 
update #tempcashsummary set openingbalance = a.openingbalance
from (select openingbalance from db_accounts.yearopening where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid) a

-- update opening balance of row 1 from yearopening table 
update #tempcashsummary set openingbalance += a.vamount
from (select isnull(sum(voucheramount),0) vamount from db_accounts.voucher where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid and drcr='D' and voucherdate < @fromdate) a 

update #tempcashsummary set openingbalance -= a.vamount
from (select isnull(sum(voucheramount),0)  vamount from db_accounts.voucher where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid and drcr='C' and voucherdate < @fromdate) a 


-- update row total in temp cash summary
update #tempcashsummary set rowtotal = a.rowtotal,
dramount = a.dramount, cramount= a.cramount 
from (select vdate, sum(rowtotal) rowtotal,sum(dramount) dramount,sum(cramount) cramount  from #tempvoucher group by vdate) a 
where a.vdate = #tempcashsummary.cdate

select cdate, openingbalance + (select isnull(sum(rowtotal),0)  from #tempcashsummary c2 where c2.cdate <c1.cdate) openingbalance, 
cramount,dramount,
openingbalance + (select sum(rowtotal) from #tempcashsummary c2 where c2.cdate <=c1.cdate) closingbalance
from #tempcashsummary c1


select * from #tempvoucher

--drop temp tables
DROP TABLE #tempvoucher;
drop table #tempcashsummary
	
	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_confirmpaymentrequirment]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,30-12-2019>
-- Description:	<Description,Save Payment advice>
CREATE PROCEDURE [db_accounts].[pr_confirmpaymentrequirment] 
@payment [db_accounts].[pmtreqconfirmation_tvp] readonly,
@accesstoken char(30)=null
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;   
SET NOCOUNT ON;
BEGIN TRANSACTION 
		UPDATE [db_accounts].[hdr_paymentrequirement] 
			       set
		           [passedamt]=a.[passedamt],
                   [managementnotes]=a.[managementnotes],
                   [isconfirmed]='Y',
                   confirmedby=a.userid,
                   [confirmedon]=getdate()
                   FROM   @payment a
  				   WHERE [db_accounts].[hdr_paymentrequirement].id= a.id 
				   and   [db_accounts].[hdr_paymentrequirement].coid= a.coid
				   and   [db_accounts].[hdr_paymentrequirement].boid= a.boid
				   and   [db_accounts].[hdr_paymentrequirement].fyid= a.fyid
				   
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing confirming payment record.', 16, 1)
							RETURN
					END

		COMMIT
END
GO
/****** Object:  StoredProcedure [db_accounts].[pr_getAccountStatement]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAccountStatement]  2,1,1,'2,11131,11127','2019-01-01','2019-02-25'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getAccountStatement] 
	@fyid int,
	@coid int,
	@boid int,
	@accountid nvarchar(max),	
	--@groupid nvarchar(max)=NULL ,	
	@FROMDATE DATE,
	@TODATE DATE
AS
BEGIN
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#tempaccounthead') IS NOT NULL DROP TABLE #tempaccounthead
	create table #tempaccounthead 
	(
		ID				bigint,
		accounthead		VARCHAR(200),
		groupid			int,
		groupname		varchar(500),
		openingbalance	decimal(15,2),
		closingbalance	decimal(15,2),
		--drsum	decimal(15,2),
		--crsum	decimal(15,2),
		minrowno		int,
		
	);
	IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
	create table #tempvoucher 
	(
		ID				bigint,
		vno				VARCHAR(10),
		vdate			DATE,
		narration		varchar(500),
		dramount		decimal(13,2),
		cramount		decimal(13,2),
		rowtotal		decimal(13,2),
		rowno			int,
		accountid		bigint
	);

--adding row into temporary accounthead table	
insert into #tempaccounthead (id,accounthead,groupid, groupname,openingbalance,closingbalance) 	 
select ah.id , accounthead,ag.id,ag.name,0,0 from db_accounts.accountheads ah
join db_accounts.accountGroups ag on ah.groupid = ag.id
where ah.id in (select * from dbo.fnSplitString(@accountid, ',') )
order by ah.id

-- update opening balance for accounthead
update #tempaccounthead set openingbalance = isnull(a.openingbalance ,0) 
from db_accounts.yearopening a 
where #tempaccounthead.id = a.accountid

-- update opening balance by adding debit amount from voucher table
update #tempaccounthead set openingbalance = isnull(openingbalance,0) + isnull(v.dramount,0)
from (select accountid, sum(voucheramount) dramount from db_accounts.voucher 
where drcr='D' and voucherdate < @fromdate 
group by accountid
) v where v.accountid = #tempaccounthead.id

-- update opening balance by subtracting credit amount from voucher table
update #tempaccounthead set openingbalance = isnull(openingbalance,0) - isnull(v.cramount,0)
from (select accountid, sum(voucheramount) cramount from db_accounts.voucher 
where drcr='C' and voucherdate < @fromdate 
group by accountid
) v where v.accountid = #tempaccounthead.id

update #tempaccounthead set closingbalance = openingbalance

-- update closing balance by adding debit amount from voucher table
update #tempaccounthead set closingbalance = isnull(closingbalance,0) + isnull(v.dramount,0)
from (select accountid, sum(voucheramount) dramount from db_accounts.voucher 
where drcr='D' and voucherdate >= @fromdate and voucherdate <=@todate
group by accountid
) v where v.accountid = #tempaccounthead.id



-- update closing balance by subtracting credit amount from voucher table
update #tempaccounthead set closingbalance = isnull(closingbalance,0) - isnull(v.cramount,0)
from (select accountid, sum(voucheramount) cramount from db_accounts.voucher 
where drcr='C' and voucherdate >= @fromdate and voucherdate <=@todate
group by accountid
) v where v.accountid = #tempaccounthead.id

-------------------------------- add data into temp voucher table -----------------------------------------
INSERT into #tempvoucher (id,vno,vdate,narration,dramount,cramount,rowtotal,accountid,rowno) 
SELECT a.id, a.vouchertype + a.vouchercategory + cast(a.voucherno as varchar(10)),a.voucherdate,a.narration,
case when a.drcr='D' then voucheramount else 0 end,
case when a.drcr='C' then voucheramount else 0 end,
case when a.drcr='D' then voucheramount else -1* isnull(voucheramount,0) end,
a.accountid,
ROW_NUMBER() OVER(ORDER BY a.voucherdate,a.voucherno) rownum 
from db_accounts.voucher a where a.accountid in (select * from dbo.fnSplitString(@accountid, ',') )
order by a.id
---order by a.id
--, a.vouchertype,a.vouchercategory 


-- update minimum row number in #tempaccounthead table
update #tempaccounthead set minrowno = a.rowno 
from (select accountid, min(rowno) rowno, max(rowno) mrowno from #tempvoucher group by accountid) as a 
where a.accountid = #tempaccounthead.id

--update running balance of first row of each account
update #tempvoucher set rowtotal = rowtotal + openingbalance
from #tempaccounthead 
where #tempvoucher.rowno=#tempaccounthead.minrowno and #tempaccounthead.id = #tempvoucher.accountid

/*; with cursorA as (
select id,vno,vdate,narration,dramount,cramount, sum(rowtotal) asum from #tempvoucher 
group by id,vno,vdate,narration,dramount,cramount),
cursorB as ( select asum, id,vno,vdate,narration,dramount,cramount, 
row_number() over(order by id,vno,vdate,narration,dramount,cramount) rownum from cursorA)
select id,vno,vdate,narration,dramount,cramount,
(select sum(asum) from cursorB c2 where c2.rownum <=c1.rownum) as runningtotal from cursorB c1;*/

--update #tempaccounthead set drsum = SUM(dramount)
--from #tempvoucher 
--where  #tempaccounthead.id = #tempvoucher.accountid


--UPDATE  #tempaccounthead SET drsum=(select SUM(dramount),accountid from #tempvoucher WHERE #tempvoucher.accountid=#tempaccounthead.ID  GROUP BY accountid ) 

select * from #tempaccounthead;

select id,vno,vdate,ltrim(rtrim(narration)) narration,dramount,cramount,accountid,
(select sum(rowtotal) from #tempvoucher c2 where c2.rowno <=c1.rowno
and c2.accountid = c1.accountid
) as runningtotal from #tempvoucher c1
order by accountid,rowno;
SELECT c.companyname,cb.unitname ,(cb.address1+' '+cb.address2) as unitadd,('Statement of Account from '+LTRIM(@FROMDATE)+' to ' +LTRIM(@TODATE)) AS reportdata FROM db_general.company_branches cb,db_masters.company c WHERE c.coid=@COID AND boid=@boid

--drop temp tables
DROP TABLE #tempvoucher;
drop table #tempaccounthead
	
	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getAccountswitoutCashBank]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getCashBankAccounts]1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getAccountswitoutCashBank] 
	@coid int = 1,
	@boid int = 1
AS
BEGIN
	SET NOCOUNT ON;
		
	select id,accounthead name from [db_accounts].[accountHeads] where groupid not in (35,36) 
	--cash group id  =35
	-- bank group id = 36

END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_getAllAccounts]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAllAccounts] 1,1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getAllAccounts] 
	@coid int = 1,
	@boid int = 1,
	@fyid int=1
AS
BEGIN
	SET NOCOUNT ON;
	
	
	select accountid, name + ' ' + address1 + ' ' + address2 + ' ' + isnull(cityname,'')  as name from db_masters.customer cu
	left join db_masters.city c on cu.city = c.id 
	where cu.coid=@coid AND cu.boid=@boid 
	--order by name + ' ' + address1 + ' ' + address2 + ' ' + isnull(cityname,'') 
	union
	select accountid, name + ' ' + address1 + ' ' + address2 + ' ' + isnull(cityname,'')  as name from db_masters.supplier sa
	left join db_masters.city c on sa.city = c.id 
	where sa.coid=@coid AND sa.boid=@boid  
	union
	select id,accounthead name from [db_accounts].[accountHeads] 
	where coid=@coid AND boid=@boid  and fyid = @fyid 
	and groupid not in (select screditorsid from db_general.company_control where coid=@coid AND boid=@boid
	union
	select sdebtorsid from db_general.company_control where coid=@coid AND boid=@boid
	)
	

	--select top 1 * from [db_accounts].[accountHeads] 
	--cash group id  =35
	-- bank group id = 36

END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_getAllAccountsforyearopening]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAllAccountsforyearopening]  1,1,1,'G','','accounthead','desc',1,20
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getAllAccountsforyearopening] 
	@coid int = 1,
	@boid int = 1,
    @fyid int=1,
	@type CHAR(1),
	@search VARCHAR(100)=NULL,
	@sort nvarchar(100)='accounthead',
	@sortorder nvarchar(100)='asc',
	@PageNumber INT=Null,
	@PageSize INT=Null
	
AS
BEGIN
	SET NOCOUNT ON;
		IF OBJECT_ID('tempdb..#tempaccount') IS NOT NULL DROP TABLE #tempaccount
		 create table #tempaccount 
(
accountid		     bigint,
accounthead VARCHAR(max),
actype  CHAR(1),
debit  decimal(13,2) default 0,
credit       decimal(13,2) default 0, 
address1 VARCHAR(max),
address2 VARCHAR(max),
city VARCHAR(50),
state VARCHAR(50),
country VARCHAR(50),
accountname VARCHAR(max),
);


INSERT INTO #tempaccount(accountid,accounthead,actype)
select id, accounthead, 'G' from db_accounts.accountheads 

update #tempaccount set actype = 'G'
from db_accounts.accountheads  as Y where #tempaccount.accountid = Y.id
and id not in (select accountid from db_masters.customer)
and id not in (select accountid from db_masters.supplier)

update #tempaccount set debit = isnull(Y.openingbalance,0)
from db_accounts.yearopening  as Y where #tempaccount.accountid = Y.accountid
and Y.openingbalance > 0

update #tempaccount set credit = isnull(Y.openingbalance*-1,0)
from db_accounts.yearopening  as Y where #tempaccount.accountid = Y.accountid
and Y.openingbalance < 0

update #tempaccount set accounthead = (isnull(cu.name,'') + ' ' + isnull(cu.address1,'') + ' ' + isnull(cu.address2,''))  , actype = 'C' 
from db_masters.customer cu where #tempaccount.accountid = cu.accountid and cu.name is not null


update #tempaccount set accounthead = (isnull(su.name,'') + ' ' + isnull(su.address1,'') + ' ' + isnull(su.address2,''))  , actype = 'S',accountname = su.name,
        #tempaccount.address1=su.address1, #tempaccount.address2=su.address2, #tempaccount.city=c.[cityname], #tempaccount.state=s.[statename], #tempaccount.country=co.[countryname]
from db_masters.supplier su 
join [db_masters].[country] co on su.country = co.id 
join [db_masters].[statemaster] s on su.state = s.id 
join [db_masters].[city] c on su.city = c.id 
where #tempaccount.accountid = su.accountid 
and su.name is not null



declare @sql nvarchar(max);
	IF (@type='A')
	BEGIN
	set @sql='SELECT * from #tempaccount' 
	END
	IF (@type='C')
	BEGIN
	set @sql='SELECT * from #tempaccount WHERE actype=''C''' 
	--AND name LIKE CONCAT('%@', @search, '@%')
	END
	IF (@type='S')
	BEGIN
	set @sql='SELECT * from #tempaccount WHERE actype=''S''' 
	END
	IF (@type='G')
	BEGIN
	set @sql='SELECT * from #tempaccount WHERE actype=''G''' 
	end
	if(@search!='')
		begin
		if(@type!='A')
		begin
		set @sql += ' and  accounthead like '+''''+cast(@search as varchar(50)) + '%'''
		end
		 if(@type='A')
		begin
		set @sql += ' where  accounthead like '+''''+cast(@search as varchar(50)) + '%'''
		end
		end
	SET @sql +=' order by ' + cast(@sort   as varchar(15)) + ' ' + cast(@sortorder   as varchar(15))  + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end 
	print @sql
	Exec sp_executesql @SQL
	IF (@type='A')
	BEGIN
	set @sql='SELECT Count(accountid) as records from #tempaccount'	
	if(@search!='')
		begin
		set @sql += ' where  accounthead like '+''''+cast(@search as varchar(50)) + '%'''
		end
	Exec sp_executesql @SQL
	END
	IF (@type!='A')
	BEGIN
	set @sql='SELECT Count(accountid) as records from #tempaccount WHERE actype='''+@type+'''' 
	if(@search!='')
		begin
		set @sql += ' and  accounthead like '+''''+cast(@search as varchar(50)) + '%'''
		end
		print @sql
		Exec sp_executesql @SQL
	END
	
	
END






GO
/****** Object:  StoredProcedure [db_accounts].[pr_getCashBankAccounts]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getCashBankAccounts]1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getCashBankAccounts] 
	@coid int = 1,
	@boid int = 1
AS
BEGIN
	SET NOCOUNT ON;
		
	select id,accounthead name from [db_accounts].[accountHeads] where groupid in (35,36) 
	--cash group id  =35
	-- bank group id = 36

END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_getcashbook]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAccountStatement] 1,10,'VOUCHERDATE',1,1,11131
-- =============================================
create PROCEDURE [db_accounts].[pr_getcashbook]
@COID INT,
@BOID INT,
@FYID INT,
@FROMDATE DATE=NULL,
@TODATE DATE ,
@trntype varchar(1)   
AS
BEGIN	
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
DECLARE @temptrial TABLE
(
ID		int,
Accid        bigint,
CustName     varchar(100),
GROUPID     bigint,
ACCTYPE      CHAR(1), 
CLbal       decimal(13,2)
);
DECLARE @temptrialsum TABLE
(
sumdebit       decimal(15,2),
sumcredit       decimal(15,2)
);
 create table #tempvoucher 
(
ID		     bigint,
Accid        bigint,
accounthead     varchar(100),
GROUPID     bigint,
baldr        decimal(13,2),
balcr        decimal(13,2),
yropbal        decimal(13,2),
bal        decimal(13,2)
);
DELETE FROM @temptrial
DECLARE  @sdebtorsid BIGINT,   @screditorsid BIGINT
SET @sdebtorsid=(SELECT sdebtorsid FROM  db_general.company_control)
SET @screditorsid=(SELECT screditorsid FROM  db_general.company_control)

insert #tempvoucher(accounthead,Accid,yropbal,balcr,baldr,GROUPID)(
SELECT accounthead,y.accountid,y.openingbalance,0,0,y.parentgroupid FROM db_accounts.yearopening Y INNER JOIN 
db_accounts.accountHeads h ON h.ID=Y.accountid WHERE   Y.fyid=@FYID and Y.BOID=@BOID
 )

UPDATE #tempvoucher SET balcr= (select ISNULL(SUM(voucheramount),0)   from db_accounts.voucher v
where drcr='C'AND  #tempvoucher.Accid=v.accountid
and  fyid=@FYID and BOID=@BOID and VOUCHERDATE<=@TODATE  
group by accountid)

UPDATE #tempvoucher SET balDr= (select ISNULL(SUM(voucheramount),0)  
from db_accounts.voucher v
where drcr='D'AND  #tempvoucher.Accid=v.accountid
and  fyid=@FYID and BOID=@BOID and  VOUCHERDATE<=@TODATE  
group by accountid)
--SELECT * FROM    #tempvoucher 

UPDATE #tempvoucher SET bal=(SELECT ISNULL(Y.baldr,0)+ISNULL(Y.balcr,0)+ISNULL(Y.yropbal,0)  from #tempvoucher y 
where #tempvoucher.Accid=Y.Accid)

IF (@trntype='G')
BEGIN  
  INSERT into #tempvoucher(accounthead,balcr ,GROUPID)(
  SELECT 'ADVANCE FROM CUSTOMERS', sum(t.bal),groupid from #tempvoucher t WHERE  groupid=@sdebtorsid AND t.bal<0 GROUP BY groupid
 )
 INSERT into #tempvoucher(accounthead,baldr,GROUPID)(
  SELECT 'SUNDRY DEBTORS', sum(t.bal),groupid from #tempvoucher t WHERE  groupid=@sdebtorsid AND t.bal>0 GROUP BY groupid
 )
 INSERT into #tempvoucher(accounthead,balcr,GROUPID)(
  SELECT 'SUNDRY CREDITORS', sum(t.bal),groupid from #tempvoucher t WHERE  groupid=@screditorsid AND t.bal<0 GROUP BY groupid
 )
  INSERT into #tempvoucher(accounthead,baldr,GROUPID)(
  SELECT 'ADVANCE PAID TO SUPPLIERS', sum(t.bal),groupid from #tempvoucher t WHERE  groupid=@screditorsid AND t.bal>0 GROUP BY groupid
 ) 
 SELECT accounthead,CASE WHEN  isNULL((bal),0)>0 THEN isNULL((bal),0) ELSE 0 END debit,CASE WHEN isNULL((bal),0)<0 THEN isNULL((bal),0) ELSE 0 END credit   FROM    #tempvoucher WHERE bal !=0 
SELECT  isNULL(SUM(baldr),0) sumdebit, isNULL(SUM(balcr),0)  sumcredit  
FROM    #tempvoucher WHERE bal !=0 
--SELECT * FROM #tempvoucher
END
  
 IF (@trntype='C')
BEGIN
UPDATE #tempvoucher SET accounthead=(SELECT c.name+ ' '+c.address1 + ' '+c.address2  from db_masters.customer c  
where #tempvoucher.Accid=c.accountid)

 SELECT accounthead,CASE WHEN  isNULL((bal),0)>0 THEN isNULL((bal),0) ELSE 0 END debit,CASE WHEN  isNULL((bal),0)<0 THEN (bal) ELSE 0 END credit   FROM    #tempvoucher WHERE bal !=0  AND GROUPID=27
SELECT  isNULL(SUM(baldr),0) sumdebit, isNULL(SUM(balcr),0)  sumcredit   
FROM    #tempvoucher WHERE bal !=0  AND GROUPID=@sdebtorsid
 END
  IF (@trntype='S')
BEGIN
UPDATE #tempvoucher SET accounthead=(SELECT c.name+ ' '+c.address1 + ' '+c.address2  from db_masters.supplier  c  
where #tempvoucher.Accid=c.accountid)
 SELECT accounthead,CASE WHEN  isNULL((bal),0)>0 THEN isNULL((bal),0) ELSE 0 END debit,CASE WHEN  isNULL((bal),0)<0 THEN isNULL((bal),0) ELSE 0 END credit   FROM    #tempvoucher WHERE bal !=0 AND GROUPID=34 
SELECT  isNULL(SUM(baldr),0) sumdebit, isNULL(SUM(balcr),0)  sumcredit 
FROM    #tempvoucher WHERE bal !=0 AND GROUPID=@screditorsid
 END
 SELECT c.companyname,cb.unitname ,cb.address1,cb.address2 FROM db_general.company_branches cb,db_masters.company c WHERE c.coid=@COID AND boid=@boid


END;


GO
/****** Object:  StoredProcedure [db_accounts].[pr_getChequeCalendar]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Er. Ravinder Pal>
-- Create date: <Create Date,04-01-2020>
-- Description:	<Description,Get supplier data>
--[db_accounts].[pr_getChequeCalendar]  1,1,12,2019
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getChequeCalendar] 
	@coid int = 1,
	@boid int = 1,
    @month int = 1,
	@year int = 1,
	@accesstoken char(30)=null
AS
BEGIN
	SET NOCOUNT ON;
	

	

	Select c.id, c.month, c.year, 
					Sun SUN,Mon MON, Tue TUE,
					Wed WED,Thu THU, Fri FRI, Sat SAT,
					isnull(Sun.amt,0) PAY_SUN,isnull(Mon.amt,0) PAY_MON,isnull(Tue.amt,0) PAY_TUE,
					isnull(Wed.amt,0) PAY_WED,isnull(Thu.amt,0) PAY_THU,isnull(Fri.amt,0) PAY_FRI,isnull(Sat.amt,0) PAY_SAT
	From  	[db_accounts].[calendar] C
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Sunday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Sun
	on Sun.dy=c.sun and  Sun.Mth=c.month and Sun.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Monday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Mon
	on Mon.dy=c.mon and  Mon.Mth=c.month and Mon.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Tuesday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Tue
	on Tue.dy=c.tue and  Tue.Mth=c.month and Tue.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Wednesday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Wed
	on Wed.dy=c.wed and  Wed.Mth=c.month and Wed.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Thursday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Thu
	on Thu.dy=c.thu and  Thu.Mth=c.month and Thu.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Friday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Fri
	on Fri.dy=c.fri and  Fri.Mth=c.month and Fri.yr=c.year
	left join (select month(transdate) Mth,day(transdate) dy, year(transdate) yr,  Sum(tranamt) amt from [db_accounts].[chequeissueddetail] Where DATENAME(dw,transdate)='Saturday' and coid=@coid and boid=@boid group by month(transdate) ,day(transdate), year(transdate)) Sat
	on Sat.dy=c.sat and  Sat.Mth=c.month and Sat.yr=c.year
	Where c.month=@month
	and   c.year=@year
	Order by c.id

	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getcurrentvoucherdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getcurrentvoucherdata] 1,1,2,'2019-05-24',12,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getcurrentvoucherdata]
	 
@coid INT,
@boid INT,
@fyid INT,
@voucherdate DATE,
@voucherno bigint ,
@trntypeid int  
AS
BEGIN	
SET NOCOUNT ON;

  select a.id,a.rowno, A.voucherdate, A.voucherno, CASE WHEN drcr='D' THEN A.voucheramount ELSE 0 END debit,
    CASE WHEN drcr='C' THEN A.voucheramount ELSE 0 END credit ,A.drcr,a.accountid,
  h.accounthead  ,rTRIM(A.narration) as narration,c.name,vouchertype,vouchercategory
 from [db_accounts].[voucher] A 
 JOIN [db_accounts].[accountHeads] h ON a.accountid = h.id
 --JOIN [db_accounts].[accountHeads] i ON a.oppositeacid = i.id
 JOIN [db_masters].[voucher_categories] c ON a.trntype = c.id
  where  A.FYID=@FYID and A.coid=@coid and A.boid=@boid  AND c.id=@trntypeid
  AND A.voucherno=@voucherno AND A.voucherdate=@voucherdate 
  --AND A.voucherno=@voucherno AND A.voucherdate=@voucherdate AND rowno>0
 
 --commit by mohit

--DECLARE @count INT= (SELECT  COUNT(a.id)
-- from [db_accounts].[voucher] A 
-- JOIN [db_accounts].[accountHeads] h ON a.accountid = h.id
-- JOIN [db_accounts].[accountHeads] i ON a.oppositeacid = i.id
-- JOIN [db_masters].[voucher_categories] c ON a.trntype = c.id
--  where  A.FYID=@FYID and A.coid=@coid and A.boid=@boid  AND c.id=@trntypeid
--  AND A.voucherno=@voucherno AND A.voucherdate=@voucherdate AND rowno=0)
--  IF (@count=0)
--  BEGIN
--   SELECT 0 AS id , A.voucherdate, A.voucherno,  SUM(A.voucheramount)  AS voucheramount,0 AS cashbankid,
--  ''  caskbankname ,A.subtrntypeid
--from [db_accounts].[voucher] A 
-- JOIN [db_accounts].[accountHeads] h ON a.accountid = h.id
-- --JOIN [db_accounts].[accountHeads] i ON a.oppositeacid = i.id
-- JOIN [db_masters].[voucher_categories] c ON a.trntype = c.id
--  where drcr='D' and A.FYID=@FYID and A.coid=@coid and A.boid=@boid  AND c.id=@trntypeid
--  AND A.voucherno=@voucherno AND A.voucherdate=@voucherdate 
--  GROUP BY A.voucherdate, A.voucherno,A.subtrntypeid
--  END
--  ELSE
--  BEGIN



--END;
end

GO
/****** Object:  StoredProcedure [db_accounts].[pr_getFAUserGroups]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getFAUserGroups] 1,1,'name','asc',1,10,0,'asset'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getFAUserGroups] 
	@coid int,
	@boid int,
	@sort nvarchar(100)='NAME',
	@sortorder nvarchar(100)='asc',
	@PageNumber INT=Null,
	@PageSize INT=Null,	
	@parentgroupid Int = NULL,
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'SELECT child.id,child.NAME,child.PARENTGROUPID,child.Subledger,child.position,child.CUR_BAL,
	child.SCHEDULE,child.[YEAR],child.COID,child.BOID, parent.name parentgroup
	from [db_accounts].[accountGroups] child 
	left join [db_accounts].[accountGroups] parent on child.parentgroupid = parent.id 
	where child.visible = 1 and child.coid= ' + cast(@coid as varchar(2)) + ' and child.boid =' + cast(@boid as varchar(2)) 
	if (@parentgroupid !=0)
		begin
		set @sql+=' and child.PARENTGROUPID =  '+ cast(@parentgroupid as varchar(3))  
		end
	if(@search!='')
		begin
		 set @sql += ' and child.NAME like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	set @sql +=' order by child.' + @sort + '  ' + @sortorder + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end

	--print @sql
	EXEC sp_executesql @SQL

	set @sql= 'SELECT count(id) records from [db_accounts].[accountGroups] where
	 coid= ' + cast(@coid as varchar(2)) + ' and boid =' + cast(@boid as varchar(2)) 
	if (@parentgroupid !=0)
		begin
		set @sql+=' and PARENTGROUPID =  '+ cast(@parentgroupid as varchar(3))  
		end
	if(@search!='')
		begin
		 set @sql += ' and NAME like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	--print @sql
	EXEC sp_executesql @SQL
	
END


GO
/****** Object:  StoredProcedure [db_accounts].[pr_getGLAccountHeadsList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getGLAccountHeadsList] 1,1,'ACCOUNTHEAD','desc',1,10,0,'punj'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getGLAccountHeadsList] 
	@coid int,
	@boid int,
	@sort nvarchar(100)='ACCOUNTHEAD',
	@sortorder nvarchar(100)='asc',
	@PageNumber INT=Null,
	@PageSize INT=Null,
	@id int =null,	
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql= 'select  h.ID,g.id groupname,g.name,  h.ACCOUNTHEAD accounthead, h.yob 
	from [db_accounts].[accountHeads] h,[db_accounts].[accountGroups] g 
	where   h.groupid=g.id and h.id not in (select accountid from db_masters.customer)
and h.id not in (select accountid from db_masters.supplier) and h.coid= ' + cast(@coid as varchar(2)) + ' and h.boid =' + cast(@boid as varchar(2))
	if (@id >0)
		begin
				set @sql+=' and h.id =  '+ cast(@id as varchar(3))  
	    end
	if(@search!='')
		begin
		 set @sql += ' and h.ACCOUNTHEAD like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	SET @sql +=' order by h.' + @sort + ' ' + @sortorder + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end 

	--print @sql
	Exec sp_executesql @SQL

	set @sql= 'select  count(h.ID) from [db_accounts].[accountHeads] h,[db_accounts].[accountGroups] g 
	where h.groupid=g.id and h.id not in (select accountid from db_masters.customer)
and h.id not in (select accountid from db_masters.supplier) '
	if (@id >0)
		begin
				set @sql+=' and h.id =  '+ cast(@id as varchar(3))  
	    end
	if(@search!='')
		begin
		 set @sql += ' and h.ACCOUNTHEAD like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	--print @sql
	Exec sp_executesql @SQL
	END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_getlastvoucherno]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getlastvoucherno] 
    @coid int,
	@boid int,
	@fyid int,
	@vouchertypeid INT,
	@cashbankid int
As
BEGIN
	SET NOCOUNT ON;
	DECLARE @vouchercategory CHAR(1)=null
	DECLARE @groupid int 	= (SELECT GROUPID FROM db_accounts.accountHeads  WHERE id=@cashbankid)
	IF (@vouchertypeid=1)
	BEGIN
	SET @vouchercategory='R'
	end 
	IF (@vouchertypeid=2)
	BEGIN
	SET @vouchercategory='P'
	end 
	--cash groupid  =35
	-- bank groupid = 36
	IF (@groupid=35)
	BEGIN
	select ISNULL(max(voucherno),0) + 1 id  from [db_accounts].[voucher] 
	where trntype=@vouchertypeid and coid=@coid AND boid=@boid AND fyid=@fyid AND vouchertype='C' AND vouchercategory=@vouchercategory	 
END
else IF (@groupid=36)
	BEGIN
	select ISNULL(max(voucherno),0) + 1 id  from [db_accounts].[voucher] 
	where trntype=@vouchertypeid and coid=@coid AND boid=@boid AND fyid=@fyid AND vouchertype='B' AND vouchercategory=@vouchercategory	 
END
else
	BEGIN
	select ISNULL(max(voucherno),0) + 1 id  from [db_accounts].[voucher] 
	where trntype=@vouchertypeid and coid=@coid AND boid=@boid AND fyid=@fyid 	 
END

--select id,accounthead name from [db_accounts].[accountHeads] where groupid in (35,36) 
--	if (@vouchertypeid>0)
--	begin
--	select id,name,categcode  from [db_masters].[voucher_categories] where parentid=@vouchertypeid 
--	end
--	else 
--	begin 
--	select id,name,categcode  from [db_masters].[voucher_categories] where  isactive=1  and parentid=0 

	--end
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getPartyWiseChequeIssuedList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Er. Ravinder Pal>
-- Create date: <Create Date,03-01-2020>
-- Description:	<Description,Get supplier data>
--[db_accounts].[pr_getPartyWiseChequeIssuedList]  1,1,1801,1,'dprnumber','asc'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getPartyWiseChequeIssuedList] 
	@coid int = 1,
	@boid int = 1,
    @accountid int = 1,
	@accesstoken char(30)=null
AS
BEGIN
	SET NOCOUNT ON;
	
	Select d.reqid,tranamt, transdate,chequeno
	From  	[db_accounts].[hdr_paymentrequirement] h
	join [db_accounts].[chequeissueddetail] d on d.reqid=h.id
	where h.accountid=@accountid
	and   h.coid=@coid
	and   h.boid=@boid
	
	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getPaymentRequirementDetail]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,30-12-2019>
-- Description:	<Description,Get payment Detail>
--[db_accounts].[pr_getPaymentRequirementDetail]   1,1,1
CREATE PROCEDURE [db_accounts].[pr_getPaymentRequirementDetail] 
@id int=1,
@coid int,
@boid int,
@accesstoken char(30)=null
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;
SET NOCOUNT ON;

declare @supplierid int;
set @supplierid = (SELECT S.id from [db_accounts].[hdr_paymentrequirement] P Join [db_masters].[supplier] S on P.accountid=S.accountid  where P.id=@id) 

SELECT ISNULL(MAX(reqno), 0) as reqno from [db_accounts].[hdr_paymentrequirement] 
where coid=@coid 
and boid=@boid

SELECT su.name as headname, su.address1, su.address2, c.[cityname] as city, s.[statename] as state, co.[countryname] as country, p.isconfirmed	,
	   p.reqno, p.reqdate, p.accountid,  p.currentbalance, CONVERT(varchar(15),abs(p.currentbalance))+ iif(p.currentbalance>0,'D','C') currentbalance1, p.amounttopay, p.bankacno, p.ifsc, p.bankid, p.[remarks], p.paymenttype, b.name AS banker, p.id 	
from [db_accounts].[hdr_paymentrequirement] p
Join [db_masters].[supplier] su on p.accountid=su.accountid  
join [db_masters].[country] co on su.country = co.id 
join [db_masters].[statemaster] s on su.state = s.id 
join [db_masters].[city] c on su.city = c.id 
LEFT JOIN db_masters.bankmaster b  ON p.bankid = b.id
where p.id=@id

select supplier.[bankid],b.name AS bankname,
supplier.[bankacno],supplier.[ifsc],supplier.[isactive], supplier.bankaddress branch 
FROM [db_masters].[supplier_banks] supplier
LEFT JOIN db_masters.bankmaster b  ON supplier.bankid = b.id
where supplier.suplid = @supplierid
union
Select 0,'N/A', '','',1,''

END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getpaymentrequirmentlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Er. Ravinder Pal>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_accounts].[pr_getpaymentrequirmentlist]  1,10,1,1,'dprnumber','asc'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getpaymentrequirmentlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='reqno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@flag char(1)='N',
	@accesstoken char(30)=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql='SELECT su.name as headname, su.address1, su.address2, c.[cityname] as city, s.[statename] as state, co.[countryname] as country,
		      p.reqno, p.reqdate, p.accountid,  p.currentbalance,  CONVERT(varchar(15),abs(p.currentbalance))+ iif(p.currentbalance>0,''D'',''C'') currentbalance1,
			  p.amounttopay, p.bankacno, p.ifsc, b.name AS bankname, p.[remarks], p.paymenttype, p.id, p.isconfirmed, p.passedamt-chequeissuedamt balanceamt, p.id as reqid	
			  from [db_accounts].[hdr_paymentrequirement] p
			  Join [db_masters].[supplier] su on p.accountid=su.accountid  
              join [db_masters].[country] co on su.country = co.id 
              join [db_masters].[statemaster] s on su.state = s.id 
              join [db_masters].[city] c on su.city = c.id
			  LEFT JOIN db_masters.bankmaster b  ON p.bankid = b.id'



	--set @sql = 'Select [dprid],[dprnumber],[dprdate],u.username,h.[departmentid],d.[deptname],[manualslipno] from [db_mm].[hdr_dpr] h
	--join [db_masters].[department] d on h.departmentid= d.id
	--join [db_masters].[users] u on h.createdby = u.userid '
		set @sql += ' where p.coid = ' + cast(@coid as varchar(5)) + ' and p.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and su.name like '+'''%'+cast(@search as varchar(50)) + '%'''
		end

		if(@flag='Y')
		begin
		 set @sql += ' and p.isconfirmed=''N'''
		end

		if(@flag='S')
		begin
		 set @sql += ' and p.isconfirmed=''Y'''
		end

		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL

	 select count(h.id)records from [db_accounts].[hdr_paymentrequirement] h
	 Join [db_masters].[supplier] su on h.accountid=su.accountid  
	 where h.coid=@coid
	 and   h.boid=@boid
	 
	 select id,accounthead name from [db_accounts].[accountHeads] where groupid in (36) 			
	
	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getPrintChequeList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Er. Ravinder Pal>
-- Create date: <Create Date,03-01-2020>
-- Description:	<Description,Get supplier data>
--[db_accounts].[pr_getPrintChequeList]  1,10,1801,1,'dprnumber','asc'
-- =============================================
CREATE  PROCEDURE [db_accounts].[pr_getPrintChequeList] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='name',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@flag char(1)='N',
	@accesstoken char(30)=null
AS
BEGIN
	SET NOCOUNT ON;
	
	declare @sql nvarchar(max);


	set @sql='select d.TRANSDATE, d.CHEQUENO, su.NAME, d.NAMEONCHEQUE, b.accounthead as BANKACNAME, d.TRANAMT, d.CHEQUENEFT CHEQUEORNEFT, h.BANKACNO,dbo.fnNumberToWords(tranamt) TRANAMTINWORD, h.IFSC, d.BANKACID
	From 	[db_accounts].[hdr_paymentrequirement] h
	join [db_accounts].[chequeissueddetail] d on d.reqid=h.id
	Join [db_masters].[supplier] su on h.accountid=su.accountid 
	left Join [db_accounts].[accountHeads] b on d.bankacid= b.id'
	


        set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and su.name like '+'''%'+cast(@search as varchar(50)) + '%'''
		end

		if(@flag='N')
		begin
		 set @sql += ' and  d.iscleared=''N'''
		end


		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL



    select count(h.id)records
	From 	[db_accounts].[hdr_paymentrequirement] h
	join [db_accounts].[chequeissueddetail] d on d.reqid=h.id
	Join [db_masters].[supplier] su on h.accountid=su.accountid 
	left Join [db_accounts].[accountHeads] b on d.bankacid= b.id
	where d.iscleared='N'
	and   h.coid=@coid
	and   h.boid=@boid


	
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_getSupplierBanker]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,30-12-2019>
-- Description:	<Description,Get Supplier Banker Detail>
--[db_accounts].[pr_getSupplierBanker] 180
CREATE PROCEDURE [db_accounts].[pr_getSupplierBanker] 
@accountid int=1
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;
SET NOCOUNT ON;

declare @supplierid int;
set @supplierid = (SELECT id as reqno from [db_masters].[supplier] where accountid=@accountid) 

select supplier.[bankid],b.name AS bankname,
supplier.[bankacno],supplier.[ifsc],supplier.[isactive], supplier.bankaddress branch 
FROM [db_masters].[supplier_banks] supplier
LEFT JOIN db_masters.bankmaster b  ON supplier.bankid = b.id
where supplier.suplid = @supplierid
union
Select 0,'N/A', '','',1,''


END
GO
/****** Object:  StoredProcedure [db_accounts].[pr_gettrial]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_accounts].[pr_gettrial] 1,1,2,'2019-01-01','2019-02-15',G
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_gettrial]
@COID INT,
@BOID INT,
@FYID INT,
@FROMDATE DATE=NULL ,
@TODATE DATE ,
@trntype varchar(1)   
AS
BEGIN	
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
IF OBJECT_ID('tempdb..#tempvoucher1') IS NOT NULL DROP TABLE #tempvoucher1
DECLARE @temptrial TABLE
(
ID		int,
Accid        bigint,
accounthead     varchar(100),
groupid     bigint,
baldebit       decimal(15,2),
credit       decimal(15,2)
);
DECLARE @temptrialsum TABLE
(
sumdebit       decimal(15,2),
sumcredit       decimal(15,2)
);
 create table #tempvoucher 
(

Accid        bigint,
accounthead     varchar(100),
GROUPID     bigint,
baldr        decimal(13,2),
balcr        decimal(13,2),
yropbal        decimal(13,2),
bal        decimal(13,2)
);
 create table #tempvoucher1 
(

accountid        bigint,
accounthead     varchar(100),
GROUPID     bigint,
baldr        decimal(13,2),
balcr        decimal(13,2),
yropbal        decimal(13,2),
bal        decimal(13,2)
);
DELETE FROM @temptrial
DECLARE  @sdebtorsid BIGINT,   @screditorsid BIGINT
SELECT @sdebtorsid=sdebtorsid FROM  db_general.company_control
SELECT @screditorsid=screditorsid FROM  db_general.company_control

insert #tempvoucher(accounthead,Accid,yropbal,balcr,baldr,GROUPID)(
SELECT accounthead,y.accountid,ISNULL(y.openingbalance,0),0,0,y.parentgroupid FROM db_accounts.yearopening Y INNER JOIN 
db_accounts.accountHeads h ON h.ID=Y.accountid WHERE   Y.fyid=@FYID and Y.BOID=@BOID
 )

UPDATE #tempvoucher SET balcr= (select ISNULL(SUM(voucheramount),0)   from db_accounts.voucher v
where drcr='C'AND  #tempvoucher.Accid=v.accountid
and  fyid=@FYID and BOID=@BOID and VOUCHERDATE<=@TODATE  
group by accountid)

UPDATE #tempvoucher SET balDr= (select ISNULL(SUM(voucheramount),0)  
from db_accounts.voucher v
where drcr='D'AND  #tempvoucher.Accid=v.accountid
and  fyid=@FYID and BOID=@BOID and  VOUCHERDATE<=@TODATE  
group by accountid)
--SELECT * FROM    #tempvoucher 

UPDATE #tempvoucher SET bal= ISNULL(baldr,0)-ISNULL(balcr,0)+ISNULL(yropbal,0)  

IF (@trntype='G') -- journal ledger
BEGIN  
  INSERT into #tempvoucher(accid,accounthead,balcr,baldr ,GROUPID)(
  SELECT 0,'ADVANCE FROM CUSTOMERS', sum(isNULL((bal),0)),0,groupid from #tempvoucher t 
  WHERE  t.groupid=@sdebtorsid AND isNULL((bal),0)<0 GROUP BY groupid
 union
  SELECT 0,'SUNDRY DEBTORS', 0,sum(isNULL((bal),0)),groupid from #tempvoucher t 
  WHERE  groupid=@sdebtorsid AND isNULL((bal),0)>0 GROUP BY groupid 
 union
  SELECT 0,'SUNDRY CREDITORS', sum(isNULL((bal),0)),0,groupid from #tempvoucher t 
  WHERE  groupid=@screditorsid AND isNULL((bal),0)<0 GROUP BY groupid
 union 
  SELECT 0,'ADVANCE PAID TO SUPPLIERS', 0,sum(isNULL((bal),0)),groupid from #tempvoucher t 
  WHERE  groupid=@screditorsid AND isNULL((bal),0)>0 GROUP BY groupid
 ) 
SELECT v.groupid,v.bal, v.accounthead,CASE WHEN  isNULL((v.bal),0)>0 THEN isNULL((v.bal),0) ELSE 0 END debit,CASE WHEN isNULL((v.bal),0)<0 THEN isNULL((v.bal*-1),0) ELSE 0 END credit   
FROM    #tempvoucher v WHERE isNULL((v.bal),0) !=0   
and groupid not in (@sdebtorsid,@screditorsid)
SELECT  isNULL(SUM(v.baldr),0) sumdebit, isNULL(SUM(v.balcr),0)  sumcredit  FROM    #tempvoucher v 
  WHERE v.bal !=0 
--  union 
SELECT * FROM #tempvoucher1
END
  
 IF (@trntype='C') -- customer trial
BEGIN
UPDATE #tempvoucher SET accounthead=(SELECT c.name+ ' '+c.address1 + ' '+c.address2  from db_masters.customer c  
where #tempvoucher.Accid=c.accountid)

 SELECT accounthead,CASE WHEN  isNULL((bal),0)>0 THEN isNULL((bal),0) ELSE 0 END debit,CASE WHEN  isNULL((bal*-1),0)<0 THEN (bal) ELSE 0 END credit   FROM    #tempvoucher WHERE bal !=0  AND GROUPID=27
SELECT  isNULL(SUM(baldr),0) sumdebit, isNULL(SUM(balcr),0)  sumcredit   
FROM    #tempvoucher WHERE bal !=0  AND GROUPID=@sdebtorsid
 END
  IF (@trntype='S') -- supplier trial
BEGIN
UPDATE #tempvoucher SET accounthead=(SELECT c.name+ ' '+c.address1 + ' '+c.address2  from db_masters.supplier  c  
where #tempvoucher.Accid=c.accountid)
 SELECT accounthead,CASE WHEN  isNULL((bal),0)>0 THEN isNULL((bal),0) ELSE 0 END debit,CASE WHEN  isNULL((bal),0)<0 THEN isNULL((bal),0) ELSE 0 END credit   FROM    #tempvoucher WHERE bal !=0 AND GROUPID=34 
SELECT  isNULL(SUM(baldr),0) sumdebit, isNULL(SUM(balcr),0)  sumcredit 
FROM    #tempvoucher WHERE bal !=0 AND GROUPID=@screditorsid
 END
 SELECT c.companyname,cb.unitname ,cb.address1,cb.address2 FROM db_general.company_branches cb,db_masters.company c WHERE c.coid=@COID AND boid=@boid


END;




GO
/****** Object:  StoredProcedure [db_accounts].[pr_getvoucherdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getvoucherdata] 1,10,1,1,2,'2019-01-01','','VOUCHERDATE','asc',0,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getvoucherdata]
	@PageNumber INT=1,
	@PageSize INT=20, 
	@coid INT,
	@boid INT,
	@fyid INT,
	@fromdate DATE =null,
	@todate DATE=null ,
	@sort nvarchar(100)='voucherno',
	@sortorder nvarchar(100)='acs',
	@accountid BIGINT=null,
	@trntypeid INT=null  
AS
BEGIN	
SET NOCOUNT ON;
IF @accountid=0
BEGIN 
set @accountid=NULL
END
IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
create table #tempvoucher 
(
voucherdate		varchar(20),
voucherno        bigint,
vouchertype		char(1),
vouchercategory char(1),
voucheramount     DECIMAL(15,2),
firstdrac     varchar(100),
firstcrac      varchar(100),
drcr	char(1),
id	bigint
);

insert into #tempvoucher (voucherno,voucherdate,vouchertype,vouchercategory,id)
select voucherno, voucherdate, vouchertype,vouchercategory, min(id) id 
from db_accounts.voucher 
where 
accountid = coalesce(@accountid,accountid) and trntype = coalesce(@trntypeid,trntype) 
group by voucherno, voucherdate, vouchertype,vouchercategory

--select * from #tempvoucher
update #tempvoucher set drcr = (select drcr from db_accounts.voucher 
where db_accounts.voucher.id = #tempvoucher.id)
--select * from #tempvoucher
update #tempvoucher set firstcrac = (select ahead.accounthead from db_accounts.accountheads ahead 
join db_accounts.voucher v 
on ahead.id = case when #tempvoucher.drcr = 'D' then v.oppositeacid else v.accountid end where v.id = #tempvoucher.id) 
--select * from #tempvoucher
update #tempvoucher set firstdrac = (select ahead.accounthead from db_accounts.accountheads ahead 
join db_accounts.voucher v 
on ahead.id = case when #tempvoucher.drcr = 'D' then v.accountid else v.oppositeacid end where v.id = #tempvoucher.id) 
--select * from #tempvoucher
update #tempvoucher set voucheramount = 
(select sum(voucheramount) from db_accounts.voucher 
where db_accounts.voucher.voucherno = #tempvoucher.voucherno and db_accounts.voucher.drcr='D' and 
db_accounts.voucher.vouchertype = #tempvoucher.vouchertype and db_accounts.voucher.vouchercategory = #tempvoucher.vouchercategory ) 

declare @sql nvarchar(max);
	
	set @sql= 'select voucherdate, voucherno,  voucheramount , firstdrac, firstcrac from #tempvoucher'

		
	if (len(@fromdate) >0 and len(@todate) >0 and @fromdate !='1900-01-01' and @todate !='1900-01-01')
		begin
			set @sql+=' where voucherdate between ''' + cast(@fromdate as varchar(10)) + ''' and ''' + cast(@todate as varchar(10))+''''
		end
	
	set @sql +=' order by ' + @sort + ' desc
	OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	print @sql
	EXEC sp_executesql @SQL
	print @sql
	select Count(voucherno) records from #tempvoucher
end

GO
/****** Object:  StoredProcedure [db_accounts].[pr_getVoucherList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getVoucherList] 1,10,'VOUCHERDATE',1,1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getVoucherList]
	@PageNumber INT,
	@PageSize INT,
	@sort nvarchar(100)='voucherdate',
	@coid int,
	@boid int,
	@accountid Int = NULL,
	@vouchertype nvarchar(1) = null,
	@vouchercategory nvarchar(1) = null,
	@fromdate date = null,
	@todate date = null,
	@searchon nvarchar(200) = null 
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql= 'SELECT voucher.[id],voucher.[COID],voucher.[BOID],voucher.[USERID],voucher.[VOUCHERNO]
	,voucher.[VOUCHERDATE],voucher.[VOUCHERAMOUNT],voucher.[VOUCHERTYPE],voucher.[VOUCHERCATEGORY]
	,voucher.[ACCOUNTID],voucher.[DRCR],voucher.[NARRATION],voucher.[ISCONFIRM]
	,accounthead.[ID],accounthead.[accounthead],accounthead.[CLBAL],accounthead.[OPBAL],accounthead.[YOB]
	FROM [db_accounts].[voucher] voucher
	join [db_accounts].[accountHeads] accounthead on voucher.accountid= accounthead.id where voucher.coid= 
	' + cast(@coid as varchar(2)) + ' and voucher.boid =' + cast(@boid as varchar(3)) + ' and 
	voucher.[AccountId] =  coalesce('+ cast(@accountid as varchar(3)) + ',voucher.[Accountid]) and
	voucher.[vouchertype] = coalesce(' + @vouchertype + ',voucher.[vouchertype]) and 
	voucher.[vouchercategory] = coalesce('+ @vouchercategory + ',voucher.[vouchercategory]) ' 
	if (@fromdate is not null and @todate is not null)
		begin
			set @sql+=' and voucher.[VOUCHERDATE] between ' + cast(@fromdate as varchar(10)) + ' and ' + cast(@todate as varchar(10))
		end

	
	set @sql +=' order by ' + @sort + ' desc
	OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'

	print @sql
	--EXEC sp_executesql @SQL
	
	set @sql = 'select count(voucher.[id]) records  FROM [db_accounts].[voucher] voucher
	join [db_accounts].[accountHeads] accounthead on voucher.accountid= accounthead.id where voucher.coid= 
	' + cast(@coid as varchar(2)) + ' and voucher.boid =' + cast(@boid as varchar(3)) + ' and 
	voucher.[AccountId] =  coalesce('+ cast(@accountid as varchar(3)) + ',voucher.[Accountid]) and
	voucher.[vouchertype] = coalesce(' + @vouchertype + ',voucher.[vouchertype]) and 
	voucher.[vouchercategory] = coalesce('+ @vouchercategory + ',voucher.[vouchercategory]) '
		
	print @sql
	--EXEC sp_executesql @SQL

END


GO
/****** Object:  StoredProcedure [db_accounts].[pr_getvouchersubcategory]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getvouchersubcategory]1,1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_getvouchersubcategory] 
   @coid INT,
   @boid INT ,
   @trntypeid int
AS
BEGIN
	SET NOCOUNT ON;

	select id,name from [db_masters].[voucher_categories] 
	where parentid>0 AND parentid=@trntypeid AND coid=@coid AND boid =@boid
	 -- where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_grouptrial]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--delete from db_masters.customer where id=21
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-03-2019>
-- Description:	<Description,Get group wise trial balance>
-- [db_accounts].[pr_grouptrial] 1,1,1,'2019-01-01','2020-04-15',S
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_grouptrial]
@coid INT,
@boid INT,
@fyid INT,
@fromdate DATE=NULL ,
@todate DATE = null,
@trntype varchar(1)  
AS
BEGIN	
	SET NOCOUNT ON
	IF OBJECT_ID('tempdb..#temptrial') IS NOT NULL DROP TABLE #temptrial
	create table #temptrial 
	(
		acctype			char(1),
		id				bigint,
		name			varchar(100),
		parentid		bigint,
		parentname		varchar(300),
		position		int,
		baldr			decimal(13,2),
		balcr			decimal(13,2),
		yropbal			decimal(13,2),
		bal				decimal(13,2)
	);
	IF OBJECT_ID('tempdb..#tempresult') IS NOT NULL DROP TABLE #tempresult
	create table #tempresult (
		acctype		char(1),
		chk			varchar(100),
		parentid	bigint,
		parentname	varchar(500),
		id			bigint,
		name		varchar(500),
		baldr			decimal(13,2),
		balcr			decimal(13,2),
		yropbal			decimal(13,2),
		bal				decimal(13,2),
		level		int
	)
	 
	DECLARE  @sdebtorsid BIGINT,   @screditorsid BIGINT
	SELECT @sdebtorsid=sdebtorsid FROM  db_general.company_control
	SELECT @screditorsid=screditorsid FROM  db_general.company_control
	
	insert into #temptrial (acctype,id,name,parentid,position,baldr,balcr,yropbal,bal)
	select 'G' type,id,name,parentgroupid parentid, position, 0 dramt, 0 cramt, 0 yropbal,0 bal from db_accounts.accountgroups 
	union
	select 'H' type,id,accounthead, groupid parentid, id , 0 dramt, 0 cramt, 0 yropbal,0 bal from db_accounts.accountheads 
	where id in (
	select distinct accountid from db_accounts.voucher
	union
	select distinct accountid from db_accounts.yearopening
	)
	order by type,parentid,position;

	-- update parentname from accountgroups
	update #temptrial set parentname = a.name
	from db_accounts.accountGroups a where a.id = #temptrial.parentid 

	-- update opening balance 
	update #temptrial set yropbal = isnull(a.openingbalance,0) , baldr = case when isnull(a.openingbalance,0)>0 then isnull(a.openingbalance,0) else 0 end,
	balcr = case when isnull(a.openingbalance,0)<0 then isnull(a.openingbalance,0) else 0 end 
	from db_accounts.yearopening a where a.accountid = #temptrial.id and #temptrial.acctype = 'H'
	and coid = @coid and boid = @boid and fyid = @fyid;

	--update opening in #temptrial , add dr amount from voucher table and voucherdate < @fromdate
	update #temptrial set yropbal = yropbal + isnull(a.voucheramount,0)
	from (select accountid, sum(voucheramount) voucheramount from db_accounts.voucher
	where drcr='D' and fyid = @fyid and coid=@coid and boid = @boid 
	and voucherdate < @fromdate 
	group by accountid) a 
	where a.accountid = #temptrial.id and #temptrial.acctype='H'; 

	--update opening in #temptrial, add cr amount from voucher table and voucherdate < @fromdate
	update #temptrial set yropbal = yropbal - isnull(a.voucheramount,0)
	from (select accountid, sum(voucheramount) voucheramount from db_accounts.voucher
	where drcr='C' and fyid = @fyid and coid=@coid and boid = @boid 
	and voucherdate < @fromdate 
	group by accountid) a 
	where a.accountid = #temptrial.id and #temptrial.acctype='H'; 


	--update bal in #temptrial
	update #temptrial set bal = isnull(yropbal,0); 

	update #temptrial set bal = isnull(a.voucheramount,0)
	from (select accountid, sum(voucheramount) voucheramount from db_accounts.voucher
	where drcr='D' and fyid = @fyid and coid=@coid and boid = @boid 
	and voucherdate between @fromdate and @todate 
	group by accountid) a 
	where a.accountid = #temptrial.id and #temptrial.acctype='H'; 


	--update bal in #temptrial
	update #temptrial set bal = bal - isnull(a.voucheramount,0) 
	from (select accountid, sum(voucheramount) voucheramount from db_accounts.voucher
	where drcr='c' and fyid = @fyid and coid=@coid and boid = @boid 
	and voucherdate between @fromdate and @todate 
	group by accountid) a 
	where a.accountid = #temptrial.id and #temptrial.acctype='H'; 


	--update baldr, balcr in #temptrial
	update #temptrial set balcr = case when bal < 0 then bal else 0 end, 
	baldr = case when bal > 0 then bal else 0 end;


	--select * from #temptrial;

	declare @minlvl int, @maxlvl int;

	WITH x AS
	(
		-- anchor:
		SELECT acctype, cast(cast(id as varchar(20)) +acctype as varchar(100)) chk, id, cast(name as varchar(200)) name, parentid, parentname, position, baldr,balcr,yropbal,bal,		
		[level] = 0 
		FROM #temptrial WHERE isnull(parentid,0)=0 --and id = 2
		UNION ALL
		-- recursive:
		SELECT t.acctype, cast(x.chk + cast(t.id as varchar(20)) as varchar(100)) chk,  t.id, cast(space(5*(x.level+1)) + t.name as varchar(200)) as name, t.parentid,t.parentname,t.position,t.baldr,t.balcr,t.yropbal,t.bal,
		[level] = x.[level] + 1 
		FROM x INNER JOIN #temptrial AS t
		ON  t.parentid = x.id and x.acctype = 'G'
	)
	insert into #tempresult (acctype,chk,parentid,parentname,id,name,baldr,balcr,yropbal,bal,level)
	select acctype,x.chk, x.parentid,parentname,id,name,x.baldr,balcr,yropbal,bal, level 
	from x
	ORDER BY [level]
	OPTION (MAXRECURSION 1000);
	--drop temptrial table
	DROP TABLE #temptrial;

	select @maxlvl = max([level]),@minlvl=min(level) from #tempresult;
	-- update opening of group in #temptrial
	WAY: -- loop to update balance in result table
		update #tempresult set yropbal = a.yropbal, baldr = a.baldr, balcr=a.balcr,bal = a.bal
		from (select parentid, sum(yropbal) yropbal, sum(baldr) baldr, sum(balcr) balcr, sum(bal) bal from #tempresult 
		where level=@maxlvl group by parentid) a where #tempresult.id = a.parentid and #tempresult.level = @maxlvl-1;
		set @maxlvl -=1;
	IF NOT(@minlvl = @maxlvl) GOTO WAY;

	

  IF (@trntype='S') -- supplier trial
BEGIN
UPDATE #tempresult SET name=(SELECT isnull(c.name,'')+ ' '+isnull(c.address1,'') + ' '+isnull(c.address2,'')  from db_masters.supplier  c  
where #tempresult.id=c.accountid)

select acctype,parentid,parentname,id,replace(name,'  ','-') name ,baldr,balcr,yropbal,bal,level from #tempresult where parentid=@screditorsid and bal<>0 order by chk,acctype,  level,id;
select case when Sum(baldr)>sum(balcr) then sum(balcr) else Sum(baldr) end total ,Sum(baldr)  sumdebit, sum(balcr*-1) sumcredit from #tempresult where parentid=@screditorsid
 END
   IF (@trntype='C') -- CUSTOMER trial
BEGIN

UPDATE #tempresult SET name=(SELECT isnull(c.name,'')+ ' '+isnull(c.address1,'') + ' '+isnull(c.address2,'')  from db_masters.customer  c  
where #tempresult.id=c.accountid)
select acctype,parentid,parentname,id,replace(name,'  ','-') name ,baldr,balcr,yropbal,bal,level from #tempresult where parentid=@sdebtorsid and bal<>0 order by chk,acctype,  level,id;
select case when Sum(baldr)>sum(balcr) then sum(balcr) else Sum(baldr) end total ,Sum(baldr)  sumdebit, sum(balcr*-1) sumcredit, sum(balcr*-1) sumcredit from #tempresult where parentid=@sdebtorsid
 END
 IF (@trntype='G') -- journal ledger
BEGIN 
	select acctype,parentid,parentname,id,replace(name,'  ','-') name ,baldr,balcr,yropbal,bal,level from #tempresult where bal<>0 order by chk,acctype,  level,id;
	select case when Sum(baldr)>sum(balcr) then sum(balcr) else Sum(baldr) end total ,Sum(baldr)  sumdebit, sum(balcr*-1) sumcredit , sum(balcr*-1) sumcredit from #tempresult where parentid=0
	end
	
	drop table #tempresult;

END;




GO
/****** Object:  StoredProcedure [db_accounts].[pr_manageGLAccountGroup]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_manageGLAccountGroup] 'GENERAL', 10,1,1,1,1,10,'Insert'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_manageGLAccountGroup] 
	@name varchar(150),
	@groupid INT= null,
	@subleadger bit=1,
	@coid int =null,
	@boid int =null,
	@userid int =null,
	@position int =null,
	@statementtype varchar(10),
	@idtoUpdate int=0

AS
BEGIN
	SET NOCOUNT ON;
	declare @currentid int=0;
	declare @dubname int=(select count(id) from db_accounts.accountGroups where name=@name)
	
IF (@statementtype='Insert')
	Begin
	
if (@dubname>0)
BEGIN
declare @message VARCHAR(30)='duplicate'
select top(1) @message error from db_accounts.accountGroups
end
ELSE
BEGIN
	Insert into [db_accounts].[accountGroups](name, parentgroupid, belongto, grouptype, subledger,  position, 
		coid, boid, userid) values (@name,@groupid,0,0,@subleadger,@position,@coid,@boid,@userid)
	set @currentid=scope_identity()
		select top(1) 'success' error from db_accounts.accountGroups
	end
end
Else
	Begin
	declare @Count int=(select count(id) from db_accounts.accountGroups where name=@name and id<>@idtoUpdate)
	if (@Count>0)
BEGIN
declare @message1 VARCHAR(30)='duplicate'
select top(1) @message1 error from db_accounts.accountGroups
end
ELSE
	update [db_accounts].[accountGroups]set name=@name, parentgroupid=@groupid, belongto=0, grouptype=0, subledger=@subleadger,  position=@position, 
		coid=@coid, boid=@boid, userid=@userid 
		where id=@idtoUpdate
		select top(1) 'success' error from db_accounts.accountGroups
	end

END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_manageGLAccountHeads]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_manageGLAccountHeads] 'testxcz',1,1,1,1,10,0,1,'','Insert'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_manageGLAccountHeads] 
	@name varchar(250)=null,
	@groupid int= null,	
	@coid int =null,
	@boid int =null,
	@userid int =null,
	@yob decimal(18,2) =null,
	@id int =null,
	@fyid int =null,
	@dated  DATE=null,
	@statementtype varchar(250) =null
AS
BEGIN
	SET NOCOUNT ON;
	set @dated=GETDATE()
IF (@statementtype='Insert')
begin
declare @dubname int=(select count(id) from db_accounts.accountHeads where accounthead=@name)
if (@dubname>0)
BEGIN
declare @message VARCHAR(30)='duplicate'
select top(1) @message error from db_accounts.accountHeads
end
ELSE
BEGIN
Insert into [db_accounts].[accountHeads](coid, boid, groupid, accounthead, clbal, opbal, yob,createdby, createdon) 
values( @coid, @boid, @groupid,@name,0,0,  @yob,@userid,@dated)
--DECLARE @identy INT =@@IDENTITY
INSERT INTO  db_accounts.yearopening (coid, boid, fyid,  accountid, openingbalance, closingbalance, parentgroupid, createdby, createdon
 )   values( @coid, @boid,@fyid,@@IDENTITY,  @yob,0, @groupid,@userid,@dated) 
 select top(1) 'Success' error from db_accounts.accountHeads     
END
END
IF (@statementtype='Update')
BEGIN
declare @dub int=(select count(id) from db_accounts.accountHeads where accounthead=@name and id<>@id)
if (@dub>0)
BEGIN
select top(1) 'duplicate' error from db_accounts.accountHeads
end
ELSE

UPDATE [db_accounts].[accountHeads] SET groupid=@groupid, accounthead=@name,yob=@yob ,modifiedby=@userid,modifiedon=@dated WHERE id=@id

UPDATE [db_accounts].yearopening SET parentgroupid=@groupid, accountid=@id,openingbalance=@yob ,modifiedby=@userid,modifiedon=@dated WHERE accountid=@id
 select top(1) 'Success' error from db_accounts.accountHeads   
 
end
END




GO
/****** Object:  StoredProcedure [db_accounts].[pr_ministatementofaccount]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAccountStatement] 1,10,'VOUCHERDATE',1,1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_ministatementofaccount]
	@PageNumber INT,
@PageSize INT, 
@coid INT,
@boid INT,
@fyid INT,
@fromdate DATE,
@todate DATE ,
@sort nvarchar(100)='narration',
@sortorder nvarchar(100)='asc',
@accountid bigint   
AS
BEGIN	
SET NOCOUNT ON

DECLARE @tempopbal TABLE
(
accid        bigint,
yropbal        decimal(15,2),
opbaldr        decimal(15,2),
opbalcr        decimal(15,2),
clbaldr        decimal(15,2),
clbalcr        decimal(15,2)
);
DECLARE @tempvoucher TABLE
(
accid        bigint,
voucherdate    date,
voucherno bigint,
narration     varchar(100),
voucheramount       decimal(15,2), 
drcr char(1),
trntype      CHAR(1)
);

declare @sql nvarchar(max);
 insert @tempopbal(accid,yropbal)(
 select ACCOUNTID, OPENINGBALANCE  from [db_accounts].[yearopening] where FYID=@FYID and coid=@coid and boid=@boid and accountid=@accountid
)
insert @tempopbal(accid,opbaldr)(
 select ACCOUNTID, sum(voucheramount) voucheramount  from [db_accounts].[voucher] 
 where drcr='D' and FYID=@FYID and coid=@coid and boid=@boid
 and accountid=@accountid and voucherdate<@fromdate
 group by accountid
)
insert @tempopbal(accid,opbalcr)(
 select ACCOUNTID, sum(voucheramount) voucheramount  from [db_accounts].[voucher] where drcr='C' and FYID=@FYID and coid=@coid and boid=@boid
  and accountid=@accountid and voucherdate>=@fromdate and voucherdate<=@todate
  group by accountid
)
insert @tempopbal(accid,clbaldr)(
 select ACCOUNTID, sum(voucheramount) voucheramount  from [db_accounts].[voucher] where drcr='D' and FYID=@FYID and coid=@coid and boid=@boid
 and accountid=@accountid and voucherdate<=@todate
 group by accountid
)
insert @tempopbal(accid,clbalcr)(
 select ACCOUNTID, sum(voucheramount)  from [db_accounts].[voucher] where drcr='C' and FYID=@FYID and coid=@coid and boid=@boid
  and accountid=@accountid and voucherdate<=@todate
  group by accountid
)

insert @tempvoucher(accid,voucherdate,voucherno,narration,voucheramount,drcr,trntype)(
  select ACCOUNTID, voucherdate, voucherno, narration, voucheramount,drcr,trntype  from [db_accounts].[voucher] where  FYID=@FYID and coid=@coid and boid=@boid
  and accountid=@accountid and voucherdate>=@fromdate and voucherdate<=@todate)

 


  SELECT accid,CASE WHEN sum(isnull(yropbal,0))>0 THEN RTRIM(sum(isnull(yropbal,0)))+'D'  ELSE RTRIM(ABS(sum(isnull(yropbal,0))))+'C' END yropbal,
  CASE WHEN ((sum(isnull(yropbal,0))+sum(isnull(clbaldr,0)))- sum(Isnull(clbalcr,0)))>0 THEN RTRIM(((sum(isnull(yropbal,0))+sum(isnull(clbaldr,0)))- sum(Isnull(clbalcr,0))))+'D'  ELSE RTRIM(ABS((sum(isnull(yropbal,0))+sum(isnull(clbaldr,0)))- sum(Isnull(clbalcr,0))))+'C' END clbal
    from @tempopbal 
 group by accid

 --set @sql ='select ACCOUNTID, voucherdate, voucherno, narration, CASE WHEN drcr="D" then  ltrim(voucheramount)+"D" else ltrim(voucheramount)+"C" end voucheramount ,drcr,trntype  from [db_accounts].[voucher] where  FYID=' + cast(@FYID as varchar(20)) + ' and coid=' + cast(@coid as varchar(20)) + ' and boid=' + cast(@boid as varchar(20)) + '
 -- and accountid=' + cast(@accountid as varchar(20)) + ' order by ' + cast(@sort as varchar(10)) +' '+ cast(@sortorder as varchar(10)) + '
	--OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
 --   FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
 set @sql ='select ACCOUNTID, voucherdate, (voucherno), narration, voucheramount,drcr,trntype  from [db_accounts].[voucher] where  FYID=' + cast(@FYID as varchar(20)) + ' and coid=' + cast(@coid as varchar(20)) + ' and boid=' + cast(@boid as varchar(20)) + '
  and accountid=' + cast(@accountid as varchar(20)) + ' order by ' + cast(@sort as varchar(10)) +' '+ cast(@sortorder as varchar(10)) + '
	OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	EXEC sp_executesql @sql
END;


GO
/****** Object:  StoredProcedure [db_accounts].[pr_PrintCashJournal]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_PrintCashJournal]  2,1,1,'2019-01-21','2019-03-25'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_PrintCashJournal] 
	@fyid int,
	@coid int,
	@boid int,
	@fromdate DATE,
	@todate DATE
AS
BEGIN
	SET NOCOUNT ON;
	
	declare @cashaccountid int, @mindate date, @maxdate date;

	select @cashaccountid = cashaccountid from db_general.company_control where coid = @coid and boid=@boid;

	IF OBJECT_ID('tempdb..#tempcashsummary') IS NOT NULL DROP TABLE #tempcashsummary
	create table #tempcashsummary 
	(
		cdate			varchar(10),
		openingbalance	decimal(15,2),
		rowtotal		decimal(15,2),
		cramount		decimal(15,2),
		dramount		decimal(15,2),
		cramountJV		decimal(15,2),
		dramountJV		decimal(15,2)
	);
	IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
	create table #tempvoucher 
	(
		ID				bigint,
		vno				VARCHAR(20),
		vdate			date,
		accountid		bigint,
		accounthead		varchar(200),
		narration		varchar(500),
		dramount		decimal(13,2),
		cramount		decimal(13,2),
		rowtotal		decimal(13,2),
		cramountJV		decimal(13,2),
		dramountJV		decimal(13,2),
		rowno			int
	);
	IF OBJECT_ID('tempdb..#tempcashvouchers') IS NOT NULL DROP TABLE #tempcashvouchers
	create table #tempcashvouchers
	(
		id				bigint,
		vno				varchar(20),
		voucherno		varchar(20),
		vdate			date
	) 

--adding row into temporary cash summary table	
insert into #tempcashsummary (cdate,openingbalance,rowtotal,cramount,dramount,cramountJV,dramountJV) 
SELECT  TOP (DATEDIFF(DAY, @fromdate, @todate) + 1)
        Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @fromdate),0,0,0,0,0,0 
FROM    sys.all_objects a
        CROSS JOIN sys.all_objects b;

select @mindate = min(cdate), @maxdate = max(cdate) from #tempcashsummary

--adding row into temporary cash voucher table	
insert into #tempcashvouchers (id,vno,voucherno,vdate) 
select id, (vouchertype+vouchercategory+ltrim(voucherno)) voucher,voucherno,voucherdate
from db_accounts.voucher where (voucherdate between @fromdate and @todate)
and vouchertype = 'C' and accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid

--adding cash voucher's row into temporary voucher table	
insert into #tempvoucher (id,vno,vdate,accountid,narration,dramount,cramount,rowno,dramountJV,cramountJV)
select v.id,(v.vouchertype+v.vouchercategory+ltrim(v.voucherno)) voucher,v.voucherdate,v.accountid,rtrim(v.narration),
(case when v.drcr = 'D' then v.voucheramount else 0 end) dramount, 
(case when v.drcr = 'C' then v.voucheramount else 0 end) cramount, 
ROW_NUMBER() OVER(ORDER BY v.voucherdate,v.voucherno) rownum,
0,0  
from db_accounts.voucher v
join #tempcashvouchers  t on  v.vouchertype+v.vouchercategory+ltrim(v.voucherno) = t.vno 
where v.accountid <> @cashaccountid and v.coid = @coid and v.boid = @boid and v.fyid=@fyid

--adding journal vouchers row into temporary voucher table	
insert into #tempvoucher (id,vno,vdate,accountid,narration,dramount,cramount,rowno,dramountJV,cramountJV)
select v.id,(v.vouchertype+v.vouchercategory+ltrim(v.voucherno)) voucher,v.voucherdate,v.accountid,rtrim(v.narration),
0,0,
ROW_NUMBER() OVER(ORDER BY v.voucherdate,v.voucherno) rownum,
(case when v.drcr = 'D' then v.voucheramount else 0 end) dramountJV, 
(case when v.drcr = 'C' then v.voucheramount else 0 end) cramountJV  
from db_accounts.voucher v
where v.vouchertype+v.vouchercategory+ltrim(v.voucherno) not in (select vno from #tempcashvouchers)  
and v.coid = @coid and v.boid = @boid and v.fyid=@fyid

-- update rowtotal 
update #tempvoucher set rowtotal = cramount -dramount 

-- update accounthead from accoutheads table in temp voucher table
update #tempvoucher set accounthead = a.accounthead 
from db_accounts.accountheads a where a.id = #tempvoucher.accountid


-- update opening balance from yearopening table 
update #tempcashsummary set openingbalance = a.openingbalance
from (select openingbalance from db_accounts.yearopening where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid) a

-- update opening balance of row 1 from yearopening table 
update #tempcashsummary set openingbalance += a.vamount
from (select isnull(sum(voucheramount),0) vamount from db_accounts.voucher where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid and drcr='D' and voucherdate < @fromdate) a 

update #tempcashsummary set openingbalance -= a.vamount
from (select isnull(sum(voucheramount),0)  vamount from db_accounts.voucher where accountid = @cashaccountid 
and coid = @coid and boid = @boid and fyid=@fyid and drcr='C' and voucherdate < @fromdate) a 


-- update row total in temp cash summary
update #tempcashsummary set rowtotal = a.rowtotal,
dramount = a.dramount, cramount= a.cramount ,  dramountJV = a.dramountJV, cramountJV= a.cramountJV    
from (select vdate, sum(rowtotal) rowtotal,sum(dramount) dramount,sum(cramount) cramount ,
sum(dramountJV) dramountJV,sum(cramountJV) cramountJV  
 from #tempvoucher group by vdate) a 
where a.vdate = #tempcashsummary.cdate

select cdate, openingbalance + (select isnull(sum(rowtotal),0)  from #tempcashsummary c2 where c2.cdate <c1.cdate) openingbalance, 
cramount,dramount, cramountJV,dramountJV, 
openingbalance + (select sum(rowtotal) from #tempcashsummary c2 where c2.cdate <=c1.cdate) closingbalance
from #tempcashsummary c1


select * from #tempvoucher

--drop temp tables
DROP TABLE #tempvoucher;
drop table #tempcashsummary
	
	
END

GO
/****** Object:  StoredProcedure [db_accounts].[pr_PrintJournal]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_accounts].[pr_PrintJournal]  2,1,1,'2019-01-01','2019-03-28'
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_PrintJournal] 
	@fyid int,
	@coid int,
	@boid int,
	@fromdate DATE,
	@todate DATE
AS
BEGIN
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#tempcashsummary') IS NOT NULL DROP TABLE #tempcashsummary
	create table #tempcashsummary 
	(
		cdate			date,
		openingbalance	decimal(15,2),
		rowtotal		decimal(15,2),
		cramountJV		decimal(15,2),
		dramountJV		decimal(15,2)		
	);
	IF OBJECT_ID('tempdb..#tempvoucher') IS NOT NULL DROP TABLE #tempvoucher
	create table #tempvoucher 
	(
		ID				bigint,
		vno				VARCHAR(20),
		vcateg			varchar(20),
		vdate			date,
		accountid		bigint,
		accounthead		varchar(500),
		narration		varchar(500),
		dramount		decimal(15,2),
		cramount		decimal(15,2),
		drcr			varchar(1),
		rowno			bigint
	);

--adding row into temporary cash summary table	
insert into #tempcashsummary (cdate,openingbalance,rowtotal,cramountJV,dramountJV) 
SELECT  distinct voucherdate, 0,0,0,0 from db_accounts.voucher
where (voucherdate between @fromdate and @todate)
and vouchertype <> 'C' and coid = @coid and boid = @boid and fyid=@fyid
order by voucherdate

--adding row into temporary voucher table	
insert into #tempvoucher (id,vcateg,vno,vdate,accountid,narration,dramount,cramount,rowno,drcr)
select id,vouchercategory,(ltrim(vouchertype)+ltrim(vouchercategory)+ltrim(voucherno)) voucher,voucherdate,accountid,rtrim(narration),
(case when drcr = 'D' then voucheramount else 0 end) dramount, 
(case when drcr = 'C' then voucheramount else 0 end) cramount, 
rowno, drcr 
from db_accounts.voucher where (voucherdate between @fromdate and @todate)
and vouchertype <> 'C' and coid = @coid and boid = @boid and fyid=@fyid
order by voucherdate,vouchercategory desc,voucherno,drcr desc, rowno

-- update cramount and dramount in summary table
update #tempcashsummary set cramountJV = a.cramount, dramountJV = a.dramount 
from (select vdate, sum(cramount) cramount,sum(dramount) dramount from #tempvoucher group by vdate) a 
where #tempcashsummary.cdate = a.vdate

-- update accounthead from accoutheads table in temp voucher table
update #tempvoucher set accounthead = a.accounthead 
from db_accounts.accountheads a where a.id = #tempvoucher.accountid

select cdate, 0 openingbalance, cramountJV as cramount,dramountJV as dramount,0  closingbalance
from #tempcashsummary c1

select id,vno,vdate,accountid,accounthead,narration,
case when dramount=0 then 0 else dramount end dramount,cramount,0,rowno 
from #tempvoucher 
order by vdate, vcateg desc, vno,drcr desc,rowno

--drop temp tables
DROP TABLE #tempvoucher;
		
END

GO
/****** Object:  StoredProcedure [db_accounts].[pr_savechequeissueddetail]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,30-12-2019>
-- Description:	<Description,Save Payment advice>
CREATE PROCEDURE [db_accounts].[pr_savechequeissueddetail] 
@action VARCHAR(20),
@payment [db_accounts].[chequeissueddetail_tvp] readonly,
@userid int=1,
@coid int,
@boid int,
@fyid int,
@accesstoken char(30)=null
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;   
SET NOCOUNT ON;
declare @id int, @reqno int, @rowcnt int,  @error VARCHAR(100), @amt decimal
 

BEGIN TRANSACTION 
If (@action='Insert')
	Begin
		insert into [db_accounts].[chequeissueddetail](reqid, chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc, boid, [coid],[fyid],userid,[createdon])
		SELECT  reqid, chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc,  @boid, @coid,@fyid,@userid, getdate() from @payment
		IF @@ERROR <> 0
		BEGIN
		-- Rollback the transaction
		ROLLBACK
		-- Raise an error and return
		RAISERROR ('Error while adding cheque Data.', 16, 1)
		RETURN
		END
		

	end
else
	Begin

	select top 1 @id =id from @payment

	SELECT   chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc, userid from [db_accounts].[chequeissueddetail] Where id=@id
	EXCEPT 
	SELECT   chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc, @userid from @payment
	SELECT @rowcnt = @@ROWCOUNT
	IF @rowcnt > 0
		BEGIN
		
		insert into CloudERPbklog.[db_accounts].[chequeissueddetail](id, reqid, chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc, userid,[createdon], modifiedby, modifiedon)
		SELECT id, reqid, chequeneft, tranamt,  transdate, bankacid, chequeno, nameoncheque, bankacno, ifsc, userid,[createdon],modifiedby, modifiedon  from [db_accounts].[chequeissueddetail] where id=@id
		UPDATE [db_accounts].[chequeissueddetail]
			       set
		           chequeneft=a.chequeneft,
                   tranamt=a.tranamt,
                   transdate=a.transdate,
				   bankacid=a.bankacid,
                   bankacno=a.bankacno,
                   ifsc=a.ifsc,
                   chequeno=a.chequeno,
                   nameoncheque=a.nameoncheque,
                   [modifiedby]=@userid,
                   [modifiedon]=getdate()
                   FROM   @payment a
  				   WHERE [db_accounts].[chequeissueddetail].id= a.id 

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing payment detail record.', 16, 1)
							RETURN
					END
	end   
end

		select top 1 @id =reqid from @payment
		set @amt=(select sum(tranamt) as tranamt from [db_accounts].[chequeissueddetail] where reqid=@id);
		update [db_accounts].[hdr_paymentrequirement] set chequeissuedamt=@amt
		where id=@id

       IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK     
			-- Raise an error and return
			RAISERROR ('Error while adding  payment data.', 16, 1)
			SET @error = 'Error while adding  payment data.  error no: ' + CAST(@@error AS VARCHAR(3))
			RETURN @error 
		END

COMMIT
END
GO
/****** Object:  StoredProcedure [db_accounts].[pr_savepaymentrequirment]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,30-12-2019>
-- Description:	<Description,Save Payment advice>
CREATE PROCEDURE [db_accounts].[pr_savepaymentrequirment] 
@action VARCHAR(20),
@payment [db_accounts].[paymentrequirement_tvp] readonly,
@userid int=1,
@coid int,
@boid int,
@fyid int,
@accesstoken char(30)=null
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;   
SET NOCOUNT ON;
declare @reqid int, @reqno int, @rowcnt int,  @error VARCHAR(100)
set @reqno = (SELECT ISNULL(MAX(reqno), 0) + 1 as reqno from [db_accounts].[hdr_paymentrequirement] where coid=@coid and boid=@boid) 

BEGIN TRANSACTION 
If (@action='Insert')
	Begin
		insert into [db_accounts].[hdr_paymentrequirement](reqno, reqdate, accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype,boid, [coid],[fyid],userid,[createdon])
		SELECT  @reqno, reqdate, accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype, boid, [coid],[fyid],userid, getdate() from @payment
		IF @@ERROR <> 0
		BEGIN
		-- Rollback the transaction
		ROLLBACK
		-- Raise an error and return
		RAISERROR ('Error while adding Payment Data.', 16, 1)
		RETURN
		END
		SELECT @reqid= SCOPE_IDENTITY()
		IF @@ERROR <> 0
		BEGIN
		-- Rollback the transaction
		ROLLBACK
		-- Raise an error and return
		RAISERROR ('Error while getting req id.', 16, 1)
		RETURN
		END
	end
else
	Begin

	select top 1 @reqid =id from @payment

	SELECT  accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype, [coid],[fyid],userid from [db_accounts].[hdr_paymentrequirement] where id=@reqid
	EXCEPT 
	SELECT  accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype, [coid],[fyid],userid from @payment
	SELECT @rowcnt = @@ROWCOUNT
	IF @rowcnt > 0
		BEGIN
		insert into CloudERPbklog.[db_accounts].[hdr_paymentrequirement](id, reqno, reqdate, accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype, [coid],[fyid],userid,[createdon], modifiedby, modifiedon)
		SELECT id, reqno, reqdate, accountid,  currentbalance, amounttopay, bankacno, ifsc, bankid, [remarks], paymenttype, [coid],[fyid],userid,[createdon],modifiedby, modifiedon  from [db_accounts].[hdr_paymentrequirement] where id=@reqid
		UPDATE [db_accounts].[hdr_paymentrequirement] 
			       set
		           accountid=a.accountid,
                   currentbalance=a.currentbalance,
                   amounttopay=a.amounttopay,
                   bankacno=a.bankacno,
                   ifsc=a.ifsc,
                   bankid=a.bankid,
                   [remarks]=a.[remarks],
                   paymenttype=a.paymenttype,
                   [modifiedby]=@userid,
                   [modifiedon]=getdate()
                   FROM   @payment a
  				   WHERE [db_accounts].[hdr_paymentrequirement].id= a.id 

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing payment record.', 16, 1)
							RETURN
					END
	end   
end
       IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK     
			-- Raise an error and return
			RAISERROR ('Error while adding  payment data.', 16, 1)
			SET @error = 'Error while adding  payment data.  error no: ' + CAST(@@error AS VARCHAR(3))
			RETURN @error 
		END

COMMIT
END
GO
/****** Object:  StoredProcedure [db_accounts].[pr_savevoucher]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,mohit>
-- Create date: <Create Date,19-11-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_accounts].[pr_savevoucher1] 

CREATE PROCEDURE [db_accounts].[pr_savevoucher] 
@voucher_tvp [db_accounts].[voucher_tvp] readonly,
@statementtype VARCHAR(20)
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
	-- declare varilable for voucher no and voucher category
	declare @voucher_no int, @voucher_categ char, @voucher_type CHAR,@trntype int,@subtrntypeid int,@sratrvono bit ;
	--- select cash, bank group, cencel-voucher id from control table
	declare @cashbankid int , @drcr char, @cashbank_id int ,  @cashgroupid BIGINT,   @bankgroupid BIGINT
SELECT @cashgroupid=cashgroupid,@bankgroupid=bankgroupid FROM  db_general.company_control

	-- STEP 1: Start the transaction
	BEGIN TRANSACTION
		select top 1 @voucher_categ= vouchercategory,@voucher_type = vouchertype, @voucher_no = voucherno,@cashbankid=cashbankid, @trntype=trntype from @voucher_tvp
	DECLARE @vouchercategory CHAR(1)=null

	DECLARE @groupid BIGINT 	= 0
	if (@cashbankid>0)
	begin
	SELECT @groupid=GROUPID FROM db_accounts.accountHeads  WHERE id=@cashbankid
	end
	--if (@bankgroupid>0)
	--begin
	--SELECT @groupid=GROUPID FROM db_accounts.accountHeads  WHERE id=@bankgroupid
	--end
	SET @voucher_type=''
	IF (@groupid=@cashgroupid)
	BEGIN	
	SET @voucher_type='C'
	end
	else IF (@groupid=@bankgroupid)
	BEGIN
	SET @voucher_type='B'
	END
	else 
	BEGIN
	SET @voucher_type='J'
	END
	
	--select top 1  @voucher_no = voucherno, @trntype=trntype from @voucher_tvp
	select top 1 @voucher_categ= vouchercategory, @voucher_no = voucherno, @trntype=trntype , @subtrntypeid=subtrntypeid  from @voucher_tvp
	IF (@statementtype='Insert')
		BEGIN	
		--check voucher start series.
		if (@subtrntypeid>0)
		begin
		select @sratrvono=separateseries from db_masters.voucher_categories where id=@subtrntypeid
		end
		else
		begin
		select @sratrvono=separateseries from db_masters.voucher_categories where id=@trntype
		end
	IF (@sratrvono=1)
	begin
		select @voucher_no = ISNULL(max(voucherno),0) + 1 from voucher 
			where vouchercategory = @voucher_categ and vouchertype = @voucher_type AND  trntype=@trntype 
			
			end
			IF (@sratrvono=0)
	begin			
			select @voucher_no = ISNULL(max(voucherno),0) + 1 from voucher 
			where  trntype=@trntype			
			end
			-- Rollback the transaction if there were any errors
			IF @@ERROR <> 0
			 BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error in updating voucher no for this category.', 16, 1)
				RETURN
			 END
		END
	else 
		Begin
			select top 1 @voucher_no= voucherno from @voucher_tvp
			-- insert records in bkup and checking @@ERROR 
			insert into CloudERPbklog.db_accounts.voucher  (id, coid, boid, userid, voucherno, rowno, voucherdate, voucheramount, vouchertype,
			vouchercategory, accountid, drcr, narration, refid, isconfirm,trntype)
			Select  id,coid, boid, userid, @voucher_no, rowno, voucherdate, voucheramount, @voucher_type,
			vouchercategory, accountid, drcr, narration, refid, isconfirm,trntype from db_accounts.voucher 
			where vouchercategory = @voucher_categ and voucherno = @voucher_no
			
			-- Rollback the transaction if there were any errors
			IF @@ERROR <> 0
			 BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			 END
			-- delete existing records from voucher table and checking @@ERROR 
			delete from db_accounts.voucher where trntype = @trntype and voucherno = @voucher_no
			-- Rollback the transaction if there were any errors
			IF @@ERROR <> 0
			 BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while deleting existing voucher enteries.', 16, 1)
				RETURN
			 END
		End

		
	
	
	declare @oppositeacidDR bigint=(	Select top 1 accountid from @voucher_tvp where drcr='D' )
			declare @oppositeacidCR bigint=(Select top 1 accountid from @voucher_tvp where drcr='C' )
		 select top 1 @cashbankid= cashbankid, @drcr=drcr from  @voucher_tvp
		 if (@cashbankid!=0)
		 begin 
	   
		if (@drcr='C') begin set @drcr='D' end else begin set @drcr='C' end
		 Select top 1  @oppositeacidDR =  accountid from @voucher_tvp

		  --Select top 1  @oppositeacidDR =  CASHBANKID from @voucher_tvp where drcr='C' 
		  --Select top 1  @oppositeacidCR =  CASHBANKID from @voucher_tvp where drcr='D' 

		 	insert into db_accounts.voucher ( coid, boid, userid, voucherno, rowno, voucherdate, voucheramount, vouchertype,
			vouchercategory, accountid, drcr, narration, refid, isconfirm,trntype,oppositeacid,fyid,subtrntypeid)
		Select top 1 coid, boid, userid, @voucher_no, 0, voucherdate, TOTALAMOUNT, @voucher_type,
			vouchercategory, CASHBANKID, @drcr, narration, refid, isconfirm,trntype,
			 --case when drcr='D' then @oppositeacidCR  else @oppositeacidDR END,
			@oppositeacidDR, fyid ,subtrntypeid from @voucher_tvp

			set @oppositeacidDR =  @cashbankid 
			
			end
		
		-- insert data in voucher table and checking @@ERROR 
		insert into db_accounts.voucher ( coid, boid, userid, voucherno, rowno, voucherdate, voucheramount, vouchertype,
			vouchercategory, accountid, drcr, narration, refid, isconfirm,trntype,oppositeacid,fyid,subtrntypeid)
		Select coid, boid, userid, @voucher_no, rowno, voucherdate, voucheramount, @voucher_type,
			vouchercategory, accountid, drcr, narration, refid, isconfirm,trntype, 
		case when @cashbankid>0 then @cashbankid else	case when drcr='D' then @oppositeacidCR  else @oppositeacidDR END end,fyid,subtrntypeid  from @voucher_tvp
		
		-- Rollback the transaction if there were any errors
		IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding voucher enteries.', 16, 1)
			RETURN
			END

		-- If we reach this point, the commands completed successfully
		--Commit the transaction....
		COMMIT
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_saveyearopening]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_saveyearopening] 1,1,1,10,1,2
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_saveyearopening] 
	
		
	@coid int,
	@boid int ,
	@userid int ,
	@yob decimal(18,2) ,
	@id int,
	@fyid int 

	
AS
BEGIN
	SET NOCOUNT ON;
UPDATE [db_accounts].yearopening SET  openingbalance=@yob,modifiedby=@userid,modifiedon=GETDATE()
 WHERE accountid=@id  AND fyid=@fyid
END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_vouchercategory]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_vouchercategory]1,1
-- =============================================
CREATE PROCEDURE [db_accounts].[pr_vouchercategory] 
   
AS
BEGIN
	SET NOCOUNT ON;

	select id,name,categcode  from [db_masters].[voucher_categories] where isactive=1 -- where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	END



GO
/****** Object:  StoredProcedure [db_accounts].[pr_voucherdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_getAccountStatement] 1,10,'VOUCHERDATE',1,1,1
-- =============================================
create PROCEDURE [db_accounts].[pr_voucherdata]
	@PageNumber INT,
@PageSize INT, 
@coid INT,
@boid INT,
@fyid INT,
@fromdate DATE,
@todate DATE ,
@sort nvarchar(100),
@sortorder nvarchar(100),
@accountid bigint   
AS
BEGIN	
SET NOCOUNT ON

DECLARE @tempvoucher TABLE
(
accid        bigint,
voucherdate    date,
voucherno bigint,
narration     varchar(100),
voucheramount       decimal(15,2), 
drcr char(1),
trntype      CHAR(1)
);

declare @sql nvarchar(max);
 
 set @sql ='select ACCOUNTID, voucherdate, voucherno, narration, voucheramount,drcr,trntype  from [db_accounts].[voucher] where  FYID=' + cast(@FYID as varchar(20)) + ' and coid=' + cast(@coid as varchar(20)) + ' and boid=' + cast(@boid as varchar(20)) + '
  and accountid=' + cast(@accountid as varchar(20)) + ' order by ' + cast(@sort as varchar(10)) +' '+ cast(@sortorder as varchar(10)) + '
	OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	EXEC sp_executesql @sql
END;


GO
/****** Object:  StoredProcedure [db_fcr].[pr_commonapifcr]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,navneet>
-- Create date: <Create Date,23-09-2019>
-- =============================================

CREATE PROCEDURE [db_fcr].[pr_commonapifcr]	
     @coid int,
	 @boid int,	
	 @fyid int,
	 @userid int
	AS

BEGIN
	
 SET NOCOUNT ON;


	
    select * from [db_fcr].[mst_product]
    
    select * from [db_fcr].[mst_complainttype]
    
    select * from [db_fcr].[mst_complaintdescription]
    
    select * from [db_fcr].[mst_possiblecauses]

	select isnull(max(callno),0) + 1 as callno from [db_fcr].[fcr_hdr] 

	select userid,firstname from [db_masters].[users]

	select id,name from [db_fcr].[fcr_action]

	select id,status from [db_fcr].[fcr_status]

	select id,name from [db_fcr].[fcr_actiontaken]
END

GO
/****** Object:  StoredProcedure [db_fcr].[pr_getFcrComplaintlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

 -- exec [db_fcr].[pr_getFcrComplaintlist] 1,100,1,1,'','hdr.id','desc'

   CREATE PROCEDURE [db_fcr].[pr_getFcrComplaintlist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='hdr.id',
	@sortorder nvarchar(100)='desc',
	@status varchar(20)=''

AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);

	begin
	set @sql='select hdr.id, hdr.callno,hdr.calldate,
	          case when hdr.calltypeid = 1 then ''Complaint'' when hdr.calltypeid = 2 then ''Service Call'' else '''' end as type,
              cust.name, prd.name as product,hdr.contactperson,hdr.phone,hdr.remarks,st.status
              from [db_fcr].[fcr_hdr] hdr
              left join [db_fcr].[fcr_dtl] dtl on hdr.id = dtl.hdrid
              left join [db_masters].customer cust on hdr.custid = cust.id
              left join [db_fcr].[mst_product] prd on dtl.productgroup = prd.id
			  left join [db_fcr].fcr_status st on hdr.[status] = st.id'
	set @sql += ' where hdr.coid = '+ cast(@coid as varchar(5)) +' and hdr.boid='+ cast(@boid as varchar(5))+''

	--if(@resumestatus!='' and @search='')
	--begin 
	--set @sql +='a.statusid='+''''+cast(@resumestatus as VARCHAR(10))+''''
	--end
 --   if(@search!='' and @resumestatus='')
	--begin 
	--set @sql +='a.name like ''%' + cast(@search as varchar(100)) + '%'' or a.currentlocation like ''%' + cast(@search as varchar(100)) + '%''or a.contact like ''%' + cast(@search as varchar(100)) + '%'' or a.category like ''%' + cast(@search as varchar(100)) + '%'' or a.qualification like ''%' + cast(@search as varchar(100)) + '%'''
	--end

	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''

	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
     FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End
	
	print @SQL
	 
	EXEC sp_executesql @SQL

	set @totalcount = 'select count(hdr.id) records
        from [db_fcr].[fcr_hdr] hdr
        left join [db_fcr].[fcr_dtl] dtl on hdr.id = dtl.hdrid
        left join [db_masters].customer cust on hdr.custid = cust.id
        left join [db_fcr].[mst_product] prd on dtl.productgroup = prd.id'

    -- if(@resumestatus!='')
	-- begin 
	-- set @totalcount +=' where hdr.statusid='+''''+cast(@resumestatus as VARCHAR(10))+''''
	-- end

	end

	print @totalcount

	EXEC sp_executesql @totalcount

END


GO
/****** Object:  StoredProcedure [db_fcr].[pr_getfcrdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
-- [db_mktg].[pr_getenquirydata] 1,1,21
-- =============================================

CREATE PROCEDURE [db_fcr].[pr_getfcrdata] 
	@coid int,
	@boid int,
	@fcrid bigint
AS
BEGIN
SET NOCOUNT ON;   

	 select hdr.id,hdr.callno,hdr.calltypeid,hdr.calldate,hdr.calltime,hdr.custid ,cust.name,hdr.contactperson,
	 hdr.phone,hdr.remarks,hdr.ActiontakenId,hdr.fwdto,hdr.fwdfor,hdr.fwdby,hdr.attime,hdr.atdate,hdr.status,hdr.coid,hdr.boid
	 from db_fcr.fcr_hdr hdr
	 left join db_masters.customer cust on  hdr.custid=cust.id  
	 where hdr.id=@fcrid 

	 select * from db_fcr.fcr_dtl where hdrid=@fcrid

	 select * from [db_fcr].[mst_product]
    
     select * from [db_fcr].[mst_complainttype]
    
     select * from [db_fcr].[mst_complaintdescription]
    
     select * from [db_fcr].[mst_possiblecauses]

	 select userid,firstname from [db_masters].[users]

	 select id,name from [db_fcr].[fcr_action]

	 select id,status from [db_fcr].[fcr_status]

	 select id,name from [db_fcr].[fcr_actiontaken]
	
end

GO
/****** Object:  StoredProcedure [db_fcr].[pr_savefcr]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_fcr].[pr_savefcr]
    @statementtype nvarchar(50),
	@hdrcomplaint [db_fcr].[hdr_complaint] readonly,
	@dtlcomplaint [db_fcr].[dtl_complaint] readonly,
	@userid bigint=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100) 
	declare @hdrid bigint;

	if (@statementtype='Insert')
	    BEGIN        
		insert into [db_fcr].[fcr_hdr]
	    (callno,calltypeid,calldate,calltime,custid,contactperson,phone,remarks,ActiontakenId,fwdto,fwdfor,fwdby,attime,atdate,[status],isactive,createdby,createdon,modifiedby,modifiedon,coid,boid,fyid)	    
		select callno,calltypeid,calldate,calltime,custid,contactperson,phone,remarks,ActiontakenId,fwdto,fwdfor,fwdby,attime,atdate,[status],isactive,createdby,createdon,modifiedby,modifiedon,coid,boid,fyid
		from  @hdrcomplaint	  
		 
		set @hdrid= SCOPE_IDENTITY()	 
		 
		insert into [db_fcr].[fcr_dtl]
		(hdrid,productgroup,typeofcomplaint,complaint,possiblecauses,isactive,createdby,createdon,modifiedby,modifiedon) 
		select @hdrid,productgroup,typeofcomplaint,complaint,possiblecauses,isactive,createdby,createdon,modifiedby,modifiedon 
		from @dtlcomplaint
		
	End


     if (@statementtype='Update')

	 select @hdrid = [id]  from @hdrcomplaint
	   
	    BEGIN
			 UPDATE [db_fcr].[fcr_hdr]  set 
                          callno=a.callno,
                          calltypeid=a.calltypeid,
                          calldate=a.calldate,
                          calltime=a.calltime,
                          custid=a.custid,
                          contactperson=a.contactperson,
                          phone = a.phone,
                          remarks = a.remarks,
                          ActiontakenId = a.ActiontakenId,
                          fwdto = a.fwdto,
                          fwdfor = a.fwdfor,
                          fwdby = a.fwdby,
                          attime = a.attime,
                          atdate = a.atdate,
                          [status] = a.[status],
                          isactive = a.isactive,
                          modifiedby = @userid,
                          modifiedon = getdate(),
                          coid = a.coid,
                          boid = a.boid,
                          fyid = a.fyid			   				   				
					FROM  @hdrcomplaint a	where [db_fcr].[fcr_hdr].id = a.id

				-- delete records for missing skills in tvp 
				delete from [db_fcr].[fcr_dtl] where hdrid = @hdrid

		insert into [db_fcr].[fcr_dtl](hdrid,productgroup,typeofcomplaint,complaint,possiblecauses,isactive,createdby,createdon,modifiedby,modifiedon) 
		select @hdrid,productgroup,typeofcomplaint,complaint,possiblecauses,isactive,createdby,createdon,modifiedby,modifiedon from @dtlcomplaint
				
       End
  END

GO
/****** Object:  StoredProcedure [db_general].[Find_Text_In_SP]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---exec [db_general].[Find_Text_In_SP] '[mst_item_tvp]'

 CREATE PROCEDURE [db_general].[Find_Text_In_SP]
@StringToSearch varchar(100) 
AS 
   SET @StringToSearch = '%' +@StringToSearch + '%'
   SELECT Distinct SO.Name
   FROM sysobjects SO (NOLOCK)
   INNER JOIN syscomments SC (NOLOCK) on SO.Id = SC.ID
   AND SO.Type = 'P'
   AND SC.Text LIKE @stringtosearch
   ORDER BY SO.Name
  
  --pass sp name get schema name
-- SELECT * 
--FROM 
--    INFORMATION_SCHEMA.ROUTINES 
--WHERE 
--    ROUTINE_NAME LIKE '%batchwisegrossrequirement%'
GO
/****** Object:  StoredProcedure [db_general].[pr_changeLoginpassword]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_changeLoginpassword]'ADMIN','1233456','1'
-- =============================================
CREATE PROCEDURE [db_general].[pr_changeLoginpassword] 
	@UserName varchar(200),
	@Password varchar(100),
	@userid int
AS
BEGIN
	SET NOCOUNT ON;

	
	update   [db_masters].[users] set  usrpwd = @password where userid=@userid and username=@UserName
	
END



GO
/****** Object:  StoredProcedure [db_general].[pr_commonapimgmtplanner]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [db_general].[pr_commonapimgmtplanner] 1,1,1,1

Create PROCEDURE [db_general].[pr_commonapimgmtplanner]
	@coid int=1,
	@boid int=1,
	@fyid int = null,
	@userid int=1,
	@groupid int = null
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;

	select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

    select id,status from [db_general].[mst_mgmtplanner_status]

	
end	



GO
/****** Object:  StoredProcedure [db_general].[pr_companybranches]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [db_general].[pr_companybranches] 	
AS
BEGIN
	SET NOCOUNT ON;
		Begin
			select boid,unitname  from [db_general].[company_branches] where [isActive] = 1
		End	
END

GO
/****** Object:  StoredProcedure [db_general].[pr_generateaccesstoken]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_generateaccesstoken] 1,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_generateaccesstoken]
(
	@userid int
	--,@tokenVal varchar(8) OUTPUT
)
AS
Begin
	declare @AlLChars varchar(100) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',
	@token varchar(10) 
	select @token = RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) + 
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) +
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) + 
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) + 
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1)+
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) + 
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1) + 
	RIGHT( LEFT(@AlLChars,ABS(BINARY_CHECKSUM(NEWID())%35) + 1 ),1)

	IF NOT EXISTS (SELECT isnull(userid,0) id from db_masters.users where useraccesstoken =  @token)
		begin
			--select @tokenVal = db_masters.getHash(@token)
			update db_masters.users set useraccesstoken = @token, lastlogindate=GETDATE() where userid = @userid
			--select @tokenVal as token
		end
	else
		begin
			EXEC [db_general].[pr_generateaccesstoken] @userid
		end

end


GO
/****** Object:  StoredProcedure [db_general].[pr_getallstatusList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
-- exec [db_general].[pr_getallstatusList] 1,200,1,1,'resume',''

CREATE PROCEDURE [db_general].[pr_getallstatusList]
    @coid int,
	@boid int,
	@type varchar(20),
	@search varchar(100)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);


	if @type='resume'
	begin
	set @sql= 'select id,name as [status],colorcode from db_hr.mst_resumestatus'
	end

	if @type='enquiry'
	begin
	set @sql= 'select id,status,colorcode from db_mktg.mst_enqstatus'	
	End

	if @type='quote'
	begin
	set @sql= 'select id,status,colorcode from db_mktg.mst_quotestatus'	
	End


	if(@search!='')
	   begin
		 set @sql += 'where status like '+'''%'+cast(@search as varchar(50)) + '%'''
	   end 
	
	print @SQL
	 
	EXEC sp_executesql @SQL
END

GO
/****** Object:  StoredProcedure [db_general].[pr_getCustomerSpAll]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,26-04-2019>
-- Description:	<Description,Get list of data from master tables >
-- [db_general].[pr_getCustomerSpAll] 1,1,1,100,'boid',''
-- =============================================
CREATE PROCEDURE [db_general].[pr_getCustomerSpAll]
    @coid int,
	@boid int,
	@PageNumber INT =NULL,
	@PageSize int = NULL,
	@sort nvarchar(100)= 'boid',
	@sortorder nvarchar(100)= 'asc',
	@id INT=0,
	@type varchar(50)=NULL,
	@fyid INT=NULL,
	@userid int
	AS
BEGIN
	SET NOCOUNT ON;	
	--Exec  [db_masters].pr_getAllCity 1,1 @coid,@boid
	Exec  [db_masters].pr_getAllBank @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].pr_getAllCountry @coid,@boid,@PageNumber,@PageSize,@sort,@sortorder
	Exec  [db_masters].pr_getAllCurrencies @coid,@boid
	Exec  [db_masters].[pr_getZoneList]  @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].[pr_getAllCustomerCategoryList]  @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].[pr_getbusinesssegment] @coid,@boid
	--Exec  [db_masters].pr_getsinglecolumnmastersList @coid,@boid,@PageNumber,@PageSize,@sort,@sortorder,@type,@id
END

GO
/****** Object:  StoredProcedure [db_general].[pr_getdoublecolumndatalist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
-- [db_general].[pr_getsinglecolumnmastersList] 'dept',1,1,1,100,'2019-01-01',''


-- =============================================
CREATE PROCEDURE [db_general].[pr_getdoublecolumndatalist]
	@type varchar(50),
    @coid int,
	@boid int,
	@PageNumber INT =NULL,
	@PageSize int = NULL,
	@sort nvarchar(100)= 'boid',
	@sortorder nvarchar(100)= 'asc',
	@id INT=0
AS
BEGIN
	declare @tablename varchar(100)
	declare @columnname1 varchar(100)
	declare @columnname2 varchar(100)
	select @tablename=tablename from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname1=columnname1 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname2=columnname2 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
declare @sql nvarchar(500)

	IF (@id>0)
	BEGIN
	set @sql='SELECT    $IDENTITY as id, '+ @columnname1 +' as name,'+ @columnname2 +' as code,coid, boid, isactive, createdby, createdon
        FROM          '+ @tablename +'   WHERE $IDENTITY='+ cast(@id as varchar(3))+'
        order by ' + cast(@columnname1 as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''


   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	
   END 
   EXEC sp_executesql @sql
   print @sql
   end
   ELSE
   begin
   set @sql='SELECT    $IDENTITY as id, '+ @columnname1 +' as name,'+ @columnname2 +' as code,coid, boid, isactive, createdby, createdon
   FROM          ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + '
   order by ' + cast(@columnname1 as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''
   

   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	
   END 
   	EXEC sp_executesql @sql
   end
   print @sql
   set @sql='select Count('+@columnname1+') records
   FROM          ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + ''
       
   	EXEC sp_executesql @sql
   	
   	select * from [db_masters].[rcd_doublecolumn]where url=@type or type=@type
   END


GO
/****** Object:  StoredProcedure [db_general].[pr_getdoublecolumnmastersdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,15-07-2019>
-- Description:	<Description,Get list of data from master tables 
-- [db_general].[pr_getdoublecolumnmastersdata] 'resume',1,1,1
-- =============================================

CREATE PROCEDURE [db_general].[pr_getdoublecolumnmastersdata]
	@type varchar(50),
    @coid int,
	@boid int,
	@id INT=0
AS
BEGIN
	SET NOCOUNT ON;
	declare @tablename varchar(100)	
	set @tablename=(select CASE when lower(@type)='resume' then 'db_hr.mst_resumestatus'
	when lower(@type)='enquiry' then  'db_mktg.mst_enqstatus'
	when lower(@type)='quote' then  'db_mktg.mst_quotestatus'		
	ELSE 'Other'
END) 
declare @columnname varchar(100)
	set @columnname=(select CASE when lower(@type)='resume' then 'name'
	when lower(@type)='enquiry' then  'status'
	when lower(@type)='quote' then  'status'
	ELSE 'Other'
END)
declare @columnname1 varchar(100)
	set @columnname1 =(select CASE when lower(@type)='resume' then 'colorcode'
	when lower(@type)='enquiry' then  'colorcode'
	when lower(@type)='quote' then  'colorcode'

	ELSE 'Other'
END)


declare @sql nvarchar(500)

IF (@id>0)
BEGIN
set @sql='SELECT  '+ @columnname +' as [status], '+@columnname1+' as colorcode, coid, boid,createdby, createdon
FROM          '+ @tablename +' where id ='''+ cast(@id as varchar(20)) +'''
order by ' + cast(@columnname as varchar(20)) +''

END 

EXEC sp_executesql @sql

print @sql
	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_getdoublecolumnmastersList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,15-07-2019>
-- Description:	<Description,Get list of data from master tables >
-- [db_general].[pr_getdoublecolumnmastersList] 'resume',1,1,1,100,'boid','asc'
-- =============================================

CREATE PROCEDURE [db_general].[pr_getdoublecolumnmastersList]
	@type varchar(50),
    @coid int,
	@boid int,
	@PageNumber INT =NULL,
	@PageSize int = NULL,
	@sort nvarchar(100)= 'boid',
	@sortorder nvarchar(100)= 'asc',
	@id INT=0
AS
BEGIN
	SET NOCOUNT ON;
	declare @tablename varchar(100)	
	set @tablename=(select CASE when lower(@type)='resume' then 'db_hr.mst_resumestatus'
	when lower(@type)='enquiry' then  'db_mktg.mst_enqstatus'
	when lower(@type)='quote' then  'db_mktg.mst_quotestatus'		
	when lower(@type)='status' then  'db_hr.mst_status'		
	ELSE 'Other'
END) 
declare @columnname varchar(100)
	set @columnname=(select CASE when lower(@type)='resume' then 'name'
	when lower(@type)='enquiry' then  'status'
	when lower(@type)='quote' then  'status'
	when lower(@type)='status' then  'name'
	ELSE 'Other'
END)
declare @columnname1 varchar(100)
	set @columnname1 =(select CASE when lower(@type)='resume' then 'colorcode'
	when lower(@type)='enquiry' then  'colorcode'
	when lower(@type)='quote' then  'colorcode'
	when lower(@type)='status' then  'colorcode'

	ELSE 'Other'
END)


declare @sql nvarchar(500)

	IF (@id>0)
	BEGIN
	set @sql='SELECT  '+ @columnname +' as [status], '+@columnname1+' as colorcode,id, coid, boid,createdby, createdon
FROM          '+ @tablename +'
order by ' + cast(@columnname as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''


if (@PageSize>0)
begin

set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	
END 
EXEC sp_executesql @sql
print @sql
end
ELSE
begin
set @sql='SELECT  '+ @columnname +' as [status],'+@columnname1+' as colorcode,id, coid, boid,createdby, createdon
FROM          ' + @tablename + '
order by ' + cast(@columnname as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''


if (@PageSize>0)
begin

set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	
END 
	EXEC sp_executesql @sql
end
print @sql
set @sql='select Count('+@columnname+') records
FROM          ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + ''
    
	EXEC sp_executesql @sql
	
	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_getdoublecolumnmastersList1]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
-- [db_general].[pr_getdoublecolumnmastersList1] 'Currency',1,1,1,100,'2019-01-01',''


-- =============================================
CREATE PROCEDURE [db_general].[pr_getdoublecolumnmastersList1]
	@type varchar(50),
    @coid int,
	@boid int,
	@PageNumber INT =NULL,
	@PageSize int = NULL,
	@sort nvarchar(100)= 'boid',
	@sortorder nvarchar(100)= 'asc',
	@id INT=0
AS
BEGIN
	declare @tablename varchar(100)
	declare @columnname1 varchar(100)
	declare @columnname2 varchar(100)

	select @tablename=tablename from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname1=columnname1 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname2=columnname2 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)

declare @sql nvarchar(500)

	IF (@id>0)
	BEGIN
	set @sql='SELECT    $IDENTITY as id, '+ @columnname1 +' as code, '+ @columnname2 +' as name, coid, boid, isactive, createdby, createdon
        FROM '+ @tablename +'   WHERE $IDENTITY='+ cast(@id as varchar(3))+'
        order by ' + cast(@columnname2 as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''


   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	
   END 
   EXEC sp_executesql @sql
   print @sql
   end
   ELSE
   begin
   set @sql='SELECT    $IDENTITY as id, '+ @columnname1 +' as code, '+ @columnname2 +' as name, coid, boid, isactive, createdby, createdon
   FROM  ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + '
   order by ' + cast(@columnname2 as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''
   

   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	
   END 
   	EXEC sp_executesql @sql
   end
   print @sql
   set @sql='select Count('+@columnname1+') records
   FROM    ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + ''
       
   	EXEC sp_executesql @sql
   	
   	select * from [db_masters].[rcd_doublecolumn]where url=@type or type=@type

   END


GO
/****** Object:  StoredProcedure [db_general].[pr_getletterbankdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,NAVNEET>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get Data of DocumentLetters>
-- [db_general].[pr_getletterbankdata] 1,1,2
-- =============================================
CREATE PROCEDURE [db_general].[pr_getletterbankdata] 
    @coid int,
	@boid int,
	@id  int
AS
BEGIN
	SET NOCOUNT ON;

	 declare @sql nvarchar(max),@subjectid int,@deptid as int
	 
	 select id,documenttype,deptid,[subject] as subjectid,title as [titleid],documenttext,isactive,createdby,createdon,modifiedby,modifiedon,deactivatedby,deactivatedon
	 from db_general.document_bank where id=@id

	 set @deptid = (select deptid from db_general.document_bank where id=@id)

	 set @subjectid = (select subject  from db_general.document_bank where id=@id)

     select id,deptid,subject from [db_masters].[document_subjects] where deptid=@deptid

	 select id,subjectid,title from [db_masters].[document_titles] where subjectid=@subjectid

	END



GO
/****** Object:  StoredProcedure [db_general].[pr_getletterbanklist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_general].[pr_getletterbanklist] 1,200,1,1,1,'training','id',''

CREATE PROCEDURE [db_general].[pr_getletterbanklist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@userid int,
	@search varchar(100)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@dept  varchar(10)='',
	@subject varchar(10)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	begin
	set @sql= 'select * from ( select  db.id, dcat.category,dept.deptname,sub.subject,tit.title,db.createdon 
	 ,db.documenttext
	 from [db_general].document_bank  db
     left join db_masters.department dept on db.deptid= dept.id 
	 left join db_masters.document_titles tit on tit.id= db.title
	 left join db_masters.document_subjects sub on sub.id = db.subject
	 left join db_masters.document_category dcat on dcat.id=db.documenttype'
	set @sql += ' where db.isactive = '+ cast(@coid as varchar(5)) +''
	end
	if(@dept!='')
		begin
		 set @sql += ' and db.deptid ='+ cast(@dept as varchar(5)) +''
		end 
	if(@subject!='')
		begin
		 set @sql += ' and db.subject ='+ cast(@subject as varchar(5)) +''
		end 
		set @sql += ') as letterbank'
	if(@search!='')
		begin		 		 
		 set @sql += ' where letterbank.category like '+'''%'+cast(@search as varchar(50)) + '%'' or letterbank.title like '+'''%'+cast(@search as varchar(50)) + '%'' or letterbank.documenttext like '+'''%'+cast(@search as varchar(50)) + '%'''			   
		end 
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''

	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End
	print @SQL
	EXEC sp_executesql @SQL

	 select  count(db.[id])records 
     from [db_general].document_bank  db
     left join db_masters.department dept on db.deptid= dept.id 
	 left join db_masters.document_titles tit on tit.id= db.title
	 left join db_masters.document_subjects sub on sub.id = db.subject
	 left join db_masters.document_category dcat on dcat.id=db.documenttype
	 where db.isactive=1 and db.deptid= @dept and db.subject=@subject

END
GO
/****** Object:  StoredProcedure [db_general].[pr_getmanagementgroupactivities]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
--[db_general].[pr_getmanagementgroupactivities] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_general].[pr_getmanagementgroupactivities]
	@coid int,
	@boid int,
	@fyid int,
	@groupid int=null
AS
BEGIN
	SET NOCOUNT ON;
	select ga.id,groupid,activity,referenceno,duedate,reminderdate,assignedto,u.firstname +ISNULL(' ' + u.middlename ,'')+  ISNULL(' ' + u.lastname,'') AS assigneduser,
	taskstatus,TS.taskstatusname,actiontakenon,
	actiontakenby,esclatetouser,us.firstname +ISNULL(' ' + us.middlename ,'')+  ISNULL(' ' + us.lastname,'') AS esclateuser,afterdays,afterhrs,remarks
	from db_general.managementgroupactivities ga
	LEFT JOIN [db_masters].[mst_taskstatus] ts ON ga.taskstatus=ts.id
	LEFT JOIN db_masters.users u ON ga.assignedto=u.userid
	LEFT JOIN db_masters.users us ON ga.esclatetouser=us.userid
	where groupid = coalesce(@groupid,groupid) and ga.coid = @coid and ga.boid = @boid and fyid = @fyid

	SELECT id,taskstatusname FROM [db_masters].[mst_taskstatus] ms

	SELECT u.userid,u.firstname +ISNULL(' ' + u.middlename ,'')+  ISNULL(' ' + u.lastname,'') AS username FROM db_masters.users u
	

END

GO
/****** Object:  StoredProcedure [db_general].[pr_getmanagementgroups]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from management groups>
--[db_general].[pr_getmanagementgroups] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_general].[pr_getmanagementgroups]
	@isactive int
AS
BEGIN
	SET NOCOUNT ON;
	select id,groupname,groupcolor,parentid from db_general.managementplannergroups where isactive=@isactive
END

GO
/****** Object:  StoredProcedure [db_general].[pr_getmodulereports]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--exec [db_general].[pr_getmodulereports]  1,5,1,1
-- =============================================
CREATE PROCEDURE [db_general].[pr_getmodulereports] 
@userid int,
@moduleid int,
@coid int,
@boid int
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#usermenu') IS NOT NULL DROP TABLE #usermenu
	create table #usermenu 
	(
		id INT,
		moduleid int,
		menuname VARCHAR(100),
		menulabel varchar(100),
		routerLink varchar(200), 
		parentid	int,		
		menulevel	int,
		subparentid	int
	);

	insert into #usermenu (id,moduleid,menuname,menulabel,parentid,routerlink,subparentid) 	
	select id,0,functionality,menuname,moduleid,menulink,parentid 
	from db_general.erp_modules_functionalities where moduleid=@moduleid and parentid>0 and id in (
	select distinct(functionalityid) from db_general.user_rights where userid =@userid and coid=@coid and boid=@boid );

    SELECT id,moduleid, menuname,menulabel,routerlink,parentid,
	0 level,subparentid FROM #usermenu WHERE isnull(parentid,0)=0 
    UNION 
    SELECT t.id,t.moduleid, t.menuname , t.menulabel,t.routerlink, t.parentid,
	 1 level ,subparentid
    FROM #usermenu AS t where isnull(parentid,0)<>0 order by menuname
	
DROP TABLE #usermenu;


	
END













GO
/****** Object:  StoredProcedure [db_general].[pr_getmultilevelmastersList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
--[db_general].[pr_getmultilevelmastersList] '[db_mm].[mst_itemcategory]',1,1
-- =============================================
CREATE PROCEDURE [db_general].[pr_getmultilevelmastersList]
	@tablename varchar(50),
	@coid int,
	@boid int
AS
BEGIN

	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	CREATE TABLE dbo.tree
	(
		ID INT,
		name VARCHAR(100),
		parentid INT,
		code varchar(20), 
		parentname varchar(100)
	);

	set @sql= 'INSERT into dbo.tree (id,name,parentid,code,parentname) '
	if (@tablename='[db_mm].[mst_itemcategory]')
	begin
		set @sql+=' SELECT child.[id],child.[name],isnull(child.[parentid],0) parentid,child.[categorycode],parent.[name] 
		 from ' + @tablename + ' as child left join ' + @tablename + ' as parent on child.parentid = parent.id '
	end
	else
	begin
		set @sql+=' SELECT child.[id],child.[name],isnull(child.[parentgroupid],0) parentid,'''' code,parent.[name]  
		 from ' + @tablename + ' as child left join ' + @tablename + ' as parent on child.parentgroupid = parent.id '
	end
	
	set @sql+=' where child.coid='+ cast(@coid as varchar(2)) + ' and child.boid=' + cast(@boid as varchar(2))
	--print @sql
	EXEC sp_executesql @SQL;
	--select * from tree;
	WITH x AS
	(
		-- anchor:
		SELECT ID, name, parentid,code,parentname, [level] = 0 
		FROM dbo.tree WHERE isnull(parentid,0)=0 --and id=9 
		UNION ALL
		-- recursive:
		SELECT t.ID, t.name, t.parentid,t.code,t.parentname, [level] = x.[level] + 1
		FROM x INNER JOIN dbo.tree AS t
		ON t.parentid = x.ID 
	)
	SELECT ID, name, parentid, code,parentname, [level]
	FROM x
	ORDER BY [level]
	OPTION (MAXRECURSION 100);
	DROP TABLE dbo.tree;

	 
	
	

END


GO
/****** Object:  StoredProcedure [db_general].[pr_getnotificationdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- [db_general].[pr_getnotificationdata]  1,1,1,4

CREATE PROCEDURE [db_general].[pr_getnotificationdata] 
	@coid int,
	@boid int,
	@userid int,
	@notificationid bigint
AS
BEGIN
SET NOCOUNT ON;   
	
	update db_general.notifications set status='read' where id=@notificationid

	select * from db_general.notifications where id = @notificationid and receiverid = @userid 
	and coid = @coid and boid = @boid

End


GO
/****** Object:  StoredProcedure [db_general].[pr_getnotifications]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_general].[pr_getnotifications] 1,1,1

CREATE PROCEDURE [db_general].[pr_getnotifications] 
	@coid int,
	@boid int,
	@userid bigint,
	@PageNumber int =1,
	@Pagesize int=200,
	@sort nvarchar(100)='',
	@sortorder nvarchar(100)=''
AS
BEGIN
SET NOCOUNT ON; 
  
declare @sql nvarchar(max),@totalcount nvarchar(max);
	if exists (select id from db_general.notifications where escalateto = @userid and isnull(isescalated,0)=0 
	and status='Pending' and escalationtime <= getdate())
	begin
		insert into db_general.notifications (templateid,senderid,receiverid,notificationdate,notificationtext,status,
		parentid,isactive,coid,boid,createdon,createdby)
		select templateid,senderid,@userid,getdate(),notificationtext,'Pending',id,1,coid,boid,getdate(),receiverid 
		from db_general.notifications where escalateto = @userid and isnull(isescalated,0)=0 
		and status='Pending' and escalationtime <= getdate() 
		update db_general.notifications set isescalated = 1 where isnull(isescalated,0)=0 and id in (select parentid from db_general.notifications)
	end

	/*select * from db_general.notifications where escalateto = 1 and isnull(isescalated,0) = 0 and status='Pending'
	and escalationtime <= getdate()*/

	begin
	set @sql =' select id,isescalated, notificationdate,notificationtext +'' (''+format(notificationdate,''dd/MM/yyyy'')+'')'' as notificationtext,
                u.username from db_general.notifications  n
                left join db_masters.users u on u.userid=n.receiverid where [status] =''Pending'''
	set @sql += 'and receiverid = '+ cast(@userid as varchar(5)) +''
	print @SQL
	EXEC sp_executesql @SQL
	set @totalcount =' select count(id) records from db_general.notifications  where [status] =''Pending'''
	set @totalcount += ' and receiverid = '+ cast(@userid as varchar(5)) +''
	print @totalcount
	EXEC sp_executesql @totalcount
end
end

GO
/****** Object:  StoredProcedure [db_general].[pr_getrolesrights]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
-- Description:	<Description,Get role rights>
--[db_general].[pr_getrolesrights]  1,1,1,1
CREATE PROCEDURE [db_general].[pr_getrolesrights] 
@coid int,
@boid int,	
@roleid int,
@moduleid int=null,
@functionalityid int=null
AS
BEGIN
	SET NOCOUNT ON;
		Begin
		IF OBJECT_ID('tempdb..#temprolemodules') IS NOT NULL DROP TABLE #temprolemodules
		create table #temprolemodules
		(
			roleid int,
			moduleid int,
			module varchar(50),
			functionalityid int,
			functionality varchar(100),
			selected bit
		)

		IF OBJECT_ID('tempdb..#temprolerights') IS NOT NULL DROP TABLE #temprolerights
		create table #temprolerights
		(
			roleid int,
			moduleid int,
			module varchar(50),
			functionalityid int,
			functionality varchar(100),
			functionalityparentid int,
			functionalityorderno int,
			canview bit default 0,
			cancreate bit default 0,
			canedit bit default 0,
			candelete bit default 0,
			canprint bit default 0,
			canemail bit default 0,
			canimport bit default 0,
			canexport bit default 0
		)

		-- insert all module functionalities in #temprolemodules			
		insert into #temprolemodules (roleid,moduleid,functionalityid,functionality,selected)
		select @roleid,f.moduleid, f.id,f.functionality,0  
		from db_general.erp_modules_functionalities f 
		join db_general.branch_modules bmodules on f.moduleid = bmodules.moduleid and 
		bmodules.coid = @coid and bmodules.boid = @boid
		where f.moduleid =coalesce(@moduleid,f.moduleid) 
		
		--update modulename in #temprolemodules
		update #temprolemodules set module = m.modulename 
		from db_masters.erp_modules m where #temprolemodules.moduleid = m.id
		

		-- insert role rights in #temprolerights
		insert into #temprolerights (roleid,moduleid,functionalityid,canview,cancreate,canedit,candelete,
		canprint,canemail, canimport,canexport)
		select roleid,moduleid, functionalityid, 
			isnull(canview,0) canview,isnull(cancreate,0) cancreate,isnull(canedit,0) canedit,
			isnull(candelete,0) candelete,isnull(canprint,0) canprint,isnull(canemail,0) canemail,
			isnull(canimport,0) canimport,isnull(canexport,0) canexport 
		from [db_general].[role_rights] ur 
		where roleid = @roleid and moduleid = coalesce(@moduleid,moduleid) 
		and functionalityid = coalesce(@functionalityid,functionalityid)

		--update selected column in #temprolemodules
		update #temprolemodules set selected = 1 
		from #temprolerights ur where #temprolemodules.moduleid = ur.moduleid and 
		#temprolemodules.functionalityid = ur.functionalityid

		select * from #temprolemodules;
		drop table #temprolemodules;

		select * from #temprolerights;
		drop table #temprolerights;

		End	
END

GO
/****** Object:  StoredProcedure [db_general].[pr_getsinglecolumnmastersList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
--exce [db_general].[pr_getsinglecolumnmastersList] 'dept',1,1,1,100,'2019-01-01',''


-- =============================================
CREATE PROCEDURE [db_general].[pr_getsinglecolumnmastersList]
	@type varchar(50),
    @coid int,
	@boid int,
	@PageNumber INT =NULL,
	@PageSize int = NULL,
	@sort nvarchar(100)= 'boid',
	@sortorder nvarchar(100)= 'asc',
	@id INT=0
AS
BEGIN
	declare @tablename varchar(100)
	declare @columnname varchar(100)
	select @tablename=tablename from [db_masters].[rcd_singlecolumn]  where type=lower(@type)
	select @columnname=columnname from [db_masters].[rcd_singlecolumn]  where type=lower(@type)
declare @sql nvarchar(500)

	IF (@id>0)
	BEGIN
	set @sql='SELECT    $IDENTITY as id, '+ @columnname +' as name, coid, boid, isactive, createdby, createdon
        FROM          '+ @tablename +'   WHERE $IDENTITY='+ cast(@id as varchar(3))+'
        order by ' + cast(@columnname as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''


   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	 print @sql
   END 
   EXEC sp_executesql @sql
   print @sql
   end
   ELSE
   begin
   set @sql='SELECT    $IDENTITY as id, '+ @columnname +' as name, coid, boid, isactive, createdby, createdon
   FROM          ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + '
   order by ' + cast(@columnname as varchar(20)) +' '+ cast(@sortorder as varchar(10)) + ''
   
    print @sql
   if (@PageSize>0)
   begin
   
   set @sql+=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
       FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
   	
   END 
   	EXEC sp_executesql @sql
   end
   print @sql
   set @sql='select Count('+@columnname+') records
   FROM          ' + @tablename + ' where coid='+ cast(@coid as varchar(2)) +' and boid='+ cast(@boid as varchar(2)) + ''
       
   	EXEC sp_executesql @sql
   	
   	select * from [db_masters].[rcd_singlecolumn]where url=@type or type=@type
	

   END


GO
/****** Object:  StoredProcedure [db_general].[pr_getSupplierSpAll]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================

-- Author:		<Author,mohit>

-- Create date: <Create Date,26-04-2019>

-- Description:	<Description,Get list of data from master tables >

--[db_general].[pr_getCustomerSpAll] 1,1,1,100,'boid',''

-- =============================================

CREATE PROCEDURE [db_general].[pr_getSupplierSpAll]

	

    @coid int,

	@boid int

	

	AS

BEGIN

	SET NOCOUNT ON;	

	---get bank master

select ID, NAME, ADDRESS1, ADDRESS2, CITY, STATE, PHONE, EMAIL, ACCOUNTID, ISACTIVE, IFSCCODE, ACNO, ACNAME, ISDEFAULT

 from [db_masters].[bankmaster] where coid=@coid and boid=@boid

 ---get country

 select id,countryname, code,currency_preference from db_masters.country where coid=@coid and boid=@boid

 ---get Currency

  select id,name,code from db_masters.Currency where coid=@coid and boid=@boid

  ---get zone master

   select id,zonename from db_masters.zonemaster where coid=@coid and boid=@boid

   ---get supplier_category

    select id,categoryname from db_masters.supplier_category where coid=@coid and boid=@boid



	--Exec  [db_masters].pr_getAllBank @coid,@boid,@PageNumber,@PageSize,@sort

	--Exec  [db_masters].pr_getAllCountry @coid,@boid,@PageNumber,@PageSize,@sort,@sortorder

	--Exec  [db_masters].pr_getAllCurrencies @coid,@boid

	--Exec  [db_masters].[pr_getZoneList]  @coid,@boid,@PageNumber,@PageSize,@sort

	--Exec  [db_masters].[pr_getAllSupliersCategoryList]  @coid,@boid,@PageNumber,@PageSize,@sort

	

END



GO
/****** Object:  StoredProcedure [db_general].[pr_getusermenus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--exec [db_general].[pr_getusermenus]  1
-- =============================================
CREATE PROCEDURE [db_general].[pr_getusermenus] 
@userid int
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#usermenu') IS NOT NULL DROP TABLE #usermenu
	create table #usermenu 
	(
		id INT,
		moduleid int,
		menuname VARCHAR(100),
		menulabel varchar(100),
		routerLink varchar(200), 
		parentid	int,
		icon	varchar(200),
		menulevel	int,
		subparentid	int
	);

	insert into #usermenu (id,moduleid,menuname,menulabel,icon,parentid,routerlink,subparentid) 
	select 0,id,modulename, modulelabel,'pi pi-pw pi-file', 0 ,'',''
	from db_masters.erp_modules where id in (
	select distinct(moduleid) from db_general.erp_modules_functionalities where id in 
	(select distinct(functionalityid) from db_general.user_rights where userid= @userid))
	union
	select id,0,functionality,menuname,'pi pi-pw pi-file',moduleid,menulink,parentid 
	from db_general.erp_modules_functionalities where id in (
	select distinct(functionalityid) from db_general.user_rights where userid = @userid);

    SELECT id,moduleid, menuname,menulabel,routerlink,icon,parentid,
	0 level,subparentid FROM #usermenu WHERE isnull(parentid,0)=0 
    UNION 
    SELECT t.id,t.moduleid, t.menuname , t.menulabel,t.routerlink,t.icon, t.parentid,
	 1 level ,subparentid
    FROM #usermenu AS t where isnull(parentid,0)<>0 and subparentid=0 order by menuname
	
DROP TABLE #usermenu;


	
END













GO
/****** Object:  StoredProcedure [db_general].[pr_getuserrights]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
-- Description:	<Description,Get user rights>
--[db_general].[pr_getuserrights]  1,1,21,1
CREATE PROCEDURE [db_general].[pr_getuserrights] 
@coid int,
@boid int,	
@userid int,
@moduleid int=null,
@functionalityid int=null
AS
BEGIN
	SET NOCOUNT ON;
		Begin
		IF OBJECT_ID('tempdb..#tempuserrights') IS NOT NULL DROP TABLE #tempuserrights
		create table #tempuserrights
		(
			userid int,
			moduleid int,
			module varchar(50),
			functionalityid int,
			functionality varchar(100),
			functionalityparentid int,
			functionalityorderno int,
			selected bit,
			canview bit default 0,
			cancreate bit default 0,
			canedit bit default 0,
			candelete bit default 0,
			canprint bit default 0,
			canemail bit default 0,
			canimport bit default 0,
			canexport bit default 0
		)

		-- insert all module functionalities in #tempusermodules			
		insert into #tempuserrights (userid,moduleid,functionalityid,functionality,selected)
		select @userid,f.moduleid, f.id,f.functionality,0  
		from db_general.erp_modules_functionalities f 
		join db_general.branch_modules bmodules on f.moduleid = bmodules.moduleid and 
		bmodules.coid = @coid and bmodules.boid = @boid
		where f.moduleid =coalesce(@moduleid,f.moduleid) and f.id = coalesce(@functionalityid,f.id)
		
		--update modulename in #tempuserrights
		update #tempuserrights set module = m.modulename 
		from db_masters.erp_modules m where #tempuserrights.moduleid = m.id
		

		--update user rights
		update #tempuserrights set canview = isnull(ur.canview,0), cancreate = isnull(ur.cancreate,0),
		canedit = isnull(ur.canedit,0),candelete = isnull(ur.candelete,0),canprint = isnull(ur.canprint,0),
		canemail = isnull(ur.canemail,0), canimport = isnull(ur.canimport,0),canexport=isnull(ur.canexport,0),
		selected =1 
		from [db_general].[user_rights] ur 
		where ur.userid=@userid and ur.moduleid = coalesce(@moduleid,ur.moduleid)  
		and  #tempuserrights.functionalityid =  ur.functionalityid 

		select * from #tempuserrights;
		drop table #tempuserrights;


		--select * from [db_general].[user_rights] where userid = 2
		End	
END

GO
/****** Object:  StoredProcedure [db_general].[pr_PlanPoPopulate]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [db_general].[pr_PlanPoPopulate] 1,20,1,1,'C',1,'fa'
CREATE PROCEDURE [db_general].[pr_PlanPoPopulate] 
    @PageNumber INT=1,
	@PageSize INT=100,	
	@coid int,
	@boid int,
	@postatus varchar(50)='',
	@userid int=0,
	@search nvarchar(500)=null,
	@sort nvarchar(100)='cust.name',
	@sortorder nvarchar(100)=null
	
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	Begin
	--set @sql= 'select  itemord.id,itemord.orderid,itemord.orderdate,itemord.orderno,cust.name,cust.email,itemord.typeoforder,itemord.status,itemord.sectionid,
 --           sec.section,dept.deptname, itemord.sentforApproval,itemord.ARH, itemord.confirmation,itemord.Supplierorvendor,
 --           itemord.deptid,itemord.mailsentdate   
	--		from [db_masters].[items_ordermaster] itemord 
	--		join db_masters.customer cust on itemord.accountid = cust.id
	--		join db_masters.sectionmaster sec on itemord.sectionid= sec.sectionid
	--		join db_masters.department dept on itemord.deptid = dept.id where 1=1 '
	SET @SQL='select  itemord.orderid,itemord.orderdate,itemord.ordernumber,cust.name,isnull(dept.deptname,''-'') deptname,
              cust.email,itemord.ordertype typeoforder,itemord.postatus status,0 sectionid 
              from [db_mm].[hdr_purchaseorder] itemord 
              join db_masters.supplier cust on itemord.suplid = cust.id 
             left join [db_masters].[department] dept on itemord.deptid = dept.id
              where 1=1'
	if (@coid <>0 and @boid <>0)
		begin
		set @sql+=' and itemord.coid ='+  cast(@coid as varchar(5)) +'and  itemord.boid =  '+cast(@boid as varchar(5))+''
		--and itemord.IsPoCancelled =''N'' and cust.boid='+cast(@boid as varchar(5))+'and sec.boid= '+cast(@boid as varchar(5))+'
		--and dept.boid='+cast(@boid as varchar(5))+'' 
	end
	if(@postatus!='')
	begin
	set @sql+=' and postatus='''+ @postatus +''''
	end
	--if(@userid!=0) 
	--begin
	--set @sql+=' and empid='''+ cast(@userid as varchar(5)) +''''
	--end
	if (isnull(@search,'')<>'')
	begin
	set @sql+='and  cast(itemord.ordernumber as varchar)='''+  cast(@search as varchar(100)) +''' or upper(cust.name) like ''%'+cast(@search as varchar(100)) +'%'''
	end
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' asc
	OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End	
    print @sql
	EXEC sp_executesql @SQL

END


GO
/****** Object:  StoredProcedure [db_general].[pr_PoItemsPopulate]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--exec [db_general].[pr_PoItemsPopulate] 1,1,1,1,1,8
CREATE PROCEDURE [db_general].[pr_PoItemsPopulate] 
    @orderid int,
	@orderno int
	--@fyid INT,
	--@coid int = 1,
	--@boid int = 1,
	--@itemid bigint= null
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql='select hp.orderid,im.id,im.itemcode,im.id as itemid,im.itemname,dp.orderedquantity,dp.itemrate from  [db_mm].[hdr_purchaseorder] hp join [db_mm].[dtl_purchaseorder] dp on hp.orderid=dp.orderid
	left join [db_mm].[mst_item] im on dp.itemid=im.id where 1=1'
	if(@orderid<>0)
	begin
	set @sql +=' and hp.orderid='''+ cast(@orderid as varchar(10)) +''';'
	end
	set @sql +=' select * from [db_mm].[purchase_deliveryschedule]'
	if(@orderid<>0)
	begin
	set @sql +=' where orderid='''+ cast(@orderid as varchar(10)) +''';'
	end
	set @sql +=' select sim.itemid,sp.name,sim.suplitemrate,lastpurchaserate,hp.orderdate,dp.itemuom,''Rs.'' as currency  from [db_mm].[supplier_items] sim join db_masters.supplier sp on sim.suplid=sp.id'
	if(@orderid<>0)
	begin
	set @sql +=' join [db_mm].[dtl_purchaseorder] dp on sim.itemid=dp.itemid join  [db_mm].[hdr_purchaseorder] hp on hp.orderid=dp.orderid and  dp.orderid='''+ cast(@orderid as varchar(10)) +''';'
	end
	--set @sql +='; exec [db_mm].[pr_itemenquiry] '+ cast (@fyid as varchar) +','+cast(@coid as varchar)  +','+cast(@boid as varchar) +','+ cast(@itemid as varchar)
	exec(@sql)
END

--select * from [db_mm].[supplier_items]
-- select * from [db_mm].[dtl_purchaseorder]

GO
/****** Object:  StoredProcedure [db_general].[pr_POPreparedByUsers]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_general].[pr_POPreparedByUsers] 	
AS
BEGIN
	SET NOCOUNT ON;
		Begin    
			select userid ,username  FROM            db_masters.users
where userid in (select distinct  createdby  FROM            db_mm.hdr_purchaseorder)

select id ,(name+' '+isnull(address1,' ')+' '+isnull(address2,'')) as supplier  FROM            db_masters.supplier
where id in (select distinct  suplid  FROM            db_mm.hdr_purchaseorder)

	select id,deptname name from [db_masters].[department] 

	 select 1 as   id,'UN-CONFIRMED'  as STATUS 
	 union all select 2 as id,'confirmed' as status
	 union all select 3 as id,'partially settled' as status  
		End	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_poststus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

create PROCEDURE [db_general].[pr_poststus] 	
AS
BEGIN
	SET NOCOUNT ON;
		Begin
			select code,description  from [db_masters].[poStatusList] where [isActive] = 1
		End	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_reports]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_reports] 9,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_reports]
(
	@reportid INT=0,
    @reportparameters [db_general].[pr_report_parameters] readonly
)
AS
BEGIN
SET NOCOUNT ON;
	begin
	declare @spname varchar(300);
	declare @sql nvarchar(max);	

	select columnname,displayname,displaywidth,alignment 
   FROM db_mm.hdr_reportcolumn_definition h
   join db_mm.dtl_reportcolumn_definition d on h.id=d.headerid join
   db_general.mst_reportcolumns m  on d.fieldid=m.id
   where reportid=@reportid

set @spname= (select querylogic from db_mm.hdr_reportcolumn_definition where reportid=@reportid) 
exec @spname @reportid,@reportparameters
end
end

--insert into  db_mm.hdr_reportcolumn_definition (coid,	boid,	id,	reportid,	querylogic,			isactive)
--values(1,	1,	11,	1151,	'[db_mm].[reports_item-wise-minmaxlevel]'		,1)

GO
/****** Object:  StoredProcedure [db_general].[pr_reports_getreportsparameters]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_reports] 9,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_reports_getreportsparameters]
(
	@reportid INT=0,
	@coid int=0,
	@boid int=0,
	@userid int,
	@token varchar(500)
)
AS
BEGIN
SET NOCOUNT ON;
	begin
	
select id,paramname from [db_mm].[hdr_reportfilter_param] where reportid=@reportid and boid=@boid and coid=@coid 

end
end


GO
/****** Object:  StoredProcedure [db_general].[pr_savedoublecolumnmaster]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,15-07-2019>
-- Description:	<Description,Get list of data from master tables>
-- [db_general].[pr_Savedoublecolumnmasters]'resume',1,1,1,1,'2019-01-01','Under Consideration','#c58fe4','update'
-- =============================================

CREATE PROCEDURE [db_general].[pr_savedoublecolumnmaster]
	@type varchar(50),
	@coid int,
	@boid INT,
	@id INT=0,
	@userid INT,
	@dated DATE,
	@name varchar(50),
	@code varchar(50),
	@statementtype varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @tablename varchar(100)
    declare @columnname1 varchar(100)
	declare @columnname2 varchar(100)
	select @tablename=tablename from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname1=columnname1 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
	select @columnname2=columnname2 from [db_masters].[rcd_doublecolumn]  where type=lower(@type)
 


declare @sql nvarchar(500)
IF (@statementtype='insert')
begin
	set @sql='INSERT INTO '+ @tablename +'('+ @columnname1 +','+@columnname2 +',coid, boid, isactive, createdby,createdon)'
	set @sql +=' values	('''+ @name +''', '''+@code+''','+ cast(@coid as varchar(2)) +','+ cast(@boid as varchar(2))  +',1,'+ cast(@userid as varchar(3)) +','''+ cast(@dated as varchar(15)) +''')'
	print @sql
	EXECUTE sp_executesql @sql
	end
	else
	begin
	set @sql='	UPDATE  '+ @tablename +' SET '+ @columnname1 +'='''+ @name +''','+@columnname2 + '='''+@code+''' WHERE id='+ cast(@id as varchar(3)) +''
	
	EXECUTE sp_executesql @sql	
	end
	--print @sql
	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_Savedoublecolumnmasters]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,15-07-2019>
-- Description:	<Description,Get list of data from master tables>
-- [db_general].[pr_Savedoublecolumnmasters]'resume',1,1,1,1,'2019-01-01','Under Consideration','#c58fe4','update'

-- =============================================
CREATE PROCEDURE [db_general].[pr_Savedoublecolumnmasters]
	@type varchar(50),
	@coid int,
	@boid INT,
	@id INT=0,
	@userid INT,
	@dated DATE,
	@name varchar(50),
	@name2 varchar(50),
	@statementtype varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @tablename varchar(100)
	set @tablename=(select CASE when lower(@type)='resume' then 'db_hr.mst_resumestatus'
	 when lower(@type)='enquiry' then  'db_mktg.mst_enqstatus'
	 when lower(@type)='quote' then  'db_mktg.mst_quotestatus'
	ELSE 'Other'
END) 
declare @columnname varchar(100)
	set @columnname=(select CASE when lower(@type)='resume' then   'name'
	when lower(@type)='enquiry' then  'status'
	when lower(@type)='quote' then  'status'	
	ELSE 'Other'   
END)
declare @columnname1 varchar(100)
	set @columnname1=(select CASE when lower(@type)='resume' then   'colorcode'
	when lower(@type)='enquiry' then  'colorcode'
	when lower(@type)='quote' then  'colorcode'
	ELSE 'Other'  
END)

declare @sql nvarchar(500)
IF (@statementtype='insert')
begin
	set @sql='INSERT INTO '+ @tablename +'('+ @columnname +','+@columnname1 +',coid, boid, isactive, createdby,createdon)'
	set @sql +=' values	('''+ @name +''', '''+@name2+''','+ cast(@coid as varchar(2)) +','+ cast(@boid as varchar(2))  +',1,'+ cast(@userid as varchar(3)) +','''+ cast(@dated as varchar(15)) +''')'
	print @sql
	EXECUTE sp_executesql @sql
	end
	else
	begin
	set @sql='	UPDATE  '+ @tablename +' SET '+ @columnname +'='''+ @name +''','+@columnname1 + '='''+@name2+''' WHERE id='+ cast(@id as varchar(3)) +''

   -- set @sql='	UPDATE  '+ @tablename +' SET '+ @columnname +'='''+ @name +''','+@columnname1 + '='''+@name2+''', modifiedby='+ cast(@userid as varchar(3)) +''
	--set @sql +=' ,modifiedon='+ cast(@dated as varchar(3)) +' WHERE id='+ cast(@id as varchar(3)) +''	
	
	EXECUTE sp_executesql @sql	
	end
	--print @sql
	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_saveitemcategoryrights]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
-- Description:	<Description,Get user rights>
CREATE PROCEDURE [db_general].[pr_saveitemcategoryrights] 
@coid int,
@boid int,	
@userid int,
@categoryid int,
@rights_tvp [db_mm].[itemcategories_userrights_tvp] readonly 
AS
BEGIN
SET NOCOUNT ON;
	declare @user int;
	select top 1 @user = userid from @rights_tvp

	-- delete records for missing item categories in tvp 
	delete from db_mm.itemcategories_userrights where userid = @user and 
	itemcategoryid not in (select itemcategoryid from @rights_tvp) and itemcategoryid in (select * from dbo.fngetchilditemcategoryids(@categoryid))
	
	-- insert entry of parent category in itemcategories rights table
	if not exists(select itemcategoryid from db_mm.itemcategories_userrights where itemcategoryid = @categoryid and userid = @user)
	begin
		insert into db_mm.itemcategories_userrights (userid,itemcategoryid,isactive,coid,boid,createdby,createdon)
		values (@user,@categoryid,1,@coid,@boid,@userid,getdate())
	end

	-- insert new records
	insert into db_mm.itemcategories_userrights (userid,itemcategoryid,isactive,coid,boid,createdby,createdon)
	select userid,itemcategoryid,1,coid,boid,@userid,getdate() from @rights_tvp  
	where itemcategoryid not in (select itemcategoryid from db_mm.itemcategories_userrights where userid = @user) 

	select * from db_mm.itemcategories_userrights where userid = @user 

END



GO
/****** Object:  StoredProcedure [db_general].[pr_saveletter_banks]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
CREATE PROCEDURE [db_general].[pr_saveletter_banks] 
    @statementtype varchar(10),
	@coid int,
	@boid int,
	@userid bigint,
	@id int,
	@documenttype varchar(30),
	@deptid int,
	@subject varchar(300),
	@title varchar(300),
	@documenttext varchar(max)
As
BEGIN
SET NOCOUNT ON;
    If (@statementtype='Insert')
		BEGIN
		insert into [db_general].document_bank
		(documenttype,deptid,[subject],title,documenttext,isactive,createdby,createdon)
		values(@documenttype,@deptid,@subject,@title,@documenttext,1,@userid,getdate())
	End

	ELSE
	     Update [db_general].document_bank set 
	                     documenttype=@documenttype,
						 deptid=@deptid,
						 [subject]=@subject,
						 [title] = @title,
						 documenttext = @documenttext,
						 modifiedby=@userid,
						 modifiedon=getdate()
			 where id=@id
END

GO
/****** Object:  StoredProcedure [db_general].[pr_savemanagementgroupactivities]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
--[db_general].[pr_getmanagementgroupactivities] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_general].[pr_savemanagementgroupactivities]
	@coid int,
	@boid int,
	@fyid int,
	@userid int,
	@group_activity_tvp [db_general].[group_activity_tvp] readonly
AS
BEGIN
	SET NOCOUNT ON;
	declare @groupid int;
	select top 1 @groupid =  groupid from @group_activity_tvp
	IF OBJECT_ID('tempdb.. #tempactivity') IS NOT NULL DROP TABLE  #tempactivity
	create table #tempactivity (
		id int,
		groupid	int,
		activity	varchar(100),
		referenceno	varchar(10),
		duedate		date,
		reminderdate	date,
		assignedto	int,
		taskstatus	int,
		actiontakenon	datetime,
		actiontakenby	varchar(200),
		esclatetouser	int,
		afterdays	int,
		afterhrs	decimal(5,1),
		remarks	varchar(500)
	)

	-- delete records for activity missing in tvp 
	delete from [db_general].[managementgroupactivities] where groupid = @groupid and id not in (select id from @group_activity_tvp)
	
	select * from @group_activity_tvp 

	-- insert new and updated records in tmp table
	insert into #tempactivity ([id],[groupid],[activity],[referenceno],[duedate],[reminderdate],[assignedto],[taskstatus],[actiontakenon],[actiontakenby],[esclatetouser],
			 [afterdays],[afterhrs],[remarks])
	select [id],[groupid],[activity],[referenceno],[duedate],[reminderdate],[assignedto],[taskstatus],[actiontakenon],[actiontakenby],
	[esclatetouser],[afterdays],[afterhrs],[remarks] 
	from @group_activity_tvp
	EXCEPT
	select [id],[groupid],[activity],[referenceno],[duedate],[reminderdate],[assignedto],[taskstatus],[actiontakenon],[actiontakenby],
	[esclatetouser],[afterdays],[afterhrs],[remarks] 
	FROM [db_general].[managementgroupactivities] where groupid = @groupid


	select * from #tempactivity;
				 
	-- update existing enteries in 	[db_general].[managementgroupactivities] 	
	update [db_general].[managementgroupactivities]  
	set [activity] = a.activity, referenceno = a.referenceno, duedate = a.duedate, reminderdate = a.reminderdate,
	assignedto = a.assignedto, taskstatus = a.taskstatus, actiontakenon = a.actiontakenon, actiontakenby = a.actiontakenby, esclatetouser = a.esclatetouser, 
	afterdays=a.afterdays,afterhrs = a.afterhrs, remarks = a.remarks, modifiedby = @userid, modifiedon = getdate() 
	from #tempactivity a where [db_general].[managementgroupactivities].id = a.id 

	-- insert new records
	insert into [db_general].[managementgroupactivities] ([groupid],[activity],[referenceno],[duedate],[reminderdate],[assignedto],[taskstatus],[actiontakenon],[actiontakenby],[esclatetouser],
			[afterdays],[afterhrs],[remarks],[coid],[boid],[fyid],createdby,createdon)
	select [groupid],activity,[referenceno],[duedate],[reminderdate],[assignedto],[taskstatus],[actiontakenon],[actiontakenby],[esclatetouser],
			[afterdays],[afterhrs],[remarks],@coid,@boid,@fyid,@userid,getdate() from @group_activity_tvp 
			where id not in (select id from [db_general].[managementgroupactivities])

	
	select * from [db_general].[managementgroupactivities] where groupid = @groupid
	drop table #tempactivity;

END

GO
/****** Object:  StoredProcedure [db_general].[pr_savemultilevelmastersList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
--[db_general].[pr_savemultilevelmastersList] 
-- =============================================
CREATE PROCEDURE [db_general].[pr_savemultilevelmastersList]
	@statementtype varchar(10),
	@type varchar(50),
	@coid int,
	@boid int,
	@id bigint=0,
	@name varchar(100),
	@parentid bigint,
	@userid bigint,
	@isactive bit=true,
	@code varchar(10) = null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @tablename varchar(50);

	if (lower(@statementtype) = 'insert')
	begin
		if (lower(@type)='itemcategory')
		begin
			INSERT into [db_mm].[mst_itemcategory] (name,parentid,categorycode,isactive,coid,boid,createdby,createdon)
			values (@name,@parentid,@code,1,@coid,@boid,@userid,getdate())
		end
		else if (lower(@type)='accountgroups')
		begin
			Insert into [db_accounts].[accountGroups] (coid,boid,name,parentgroupid,userid,createdby,createdon,visible) 
			values (@coid,@boid,@name,@parentid,@userid,@userid,getdate(),1)
		end	

		else if (lower(@type)='employee')
		begin
			Insert into [db_general].[master_employee] (coid,boid,name,deptid,code,createdby,createdon,isactive) 
			values (@coid,@boid,@name,@parentid,@code,@userid,getdate(),1)
		end	
	end
	else
	begin
		if (lower(@type)='itemcategory')
		begin
			update [db_mm].[mst_itemcategory] set
				name = @name,
				parentid = @parentid,
				categorycode = @code,
				isactive = @isactive,
				coid = @coid,
				boid=@boid,
				modifiedby = @userid,
				modifiedon = getdate()
			where id = @id
			
		end
		else if (lower(@type)='accountgroups')
		begin
			update [db_accounts].[accountgroups] set
				name = @name,
				parentgroupid = @parentid,
				visible = @isactive,
				modifiedby = @userid,
				modifiedon = getdate()
			where id = @id
		end	

		else if (lower(@type)='employee')
		begin
			update [db_general].[master_employee] set
				name = @name,
				deptid = @parentid,
				code = @code,
				modifiedby = @userid,
				modifiedon = getdate()
			where empid = @id
		end	
	end


	 
	
	

END


GO
/****** Object:  StoredProcedure [db_general].[pr_Savesinglecolumnmasters]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of data from master tables >
-- [db_general].[pr_Savesinglecolumnmasters] 'bankmaster',1,1,8,1,'2019-09-17','SBI Branch','update'

 -- select * from db_masters.bankmaster

-- =============================================
CREATE PROCEDURE [db_general].[pr_Savesinglecolumnmasters]
	@type varchar(50),
	@coid int,
	@boid INT,
	@id INT=0,
	@userid INT,
	@dated DATE,
	@name varchar(50),
	@statementtype varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @tablename varchar(100)
	declare @columnname varchar(100)
	select @tablename=tablename from [db_masters].[rcd_singlecolumn]  where type=lower(@type)
	select @columnname=columnname from [db_masters].[rcd_singlecolumn]  where type=lower(@type)
--	set @tablename=(select CASE when lower(@type)='brand' then   'db_mm.mst_brand'
--	when lower(@type)='item' then  'db_mm.mst_itemtypes'
--	when lower(@type)='uom' then  'db_mm.mst_itemuom'
--	when lower(@type)='roles' then  'db_masters.roles'
--	when lower(@type)='costcentre' then  'db_masters.costcentre'
--	when lower(@type)='department' then  'db_masters.department'
--	when lower(@type)='popaymentterms' then  'db_mm.mst_paymentterms'
--    when lower(@type)='potermscondition' then  'db_mm.mst_termsandconditions'
--	when lower(@type)='businesssegment' then  'db_masters.businesssegement'
--	when lower(@type)='currencypreference' then  'db_masters.Currency'
--	when lower(@type)='copaymentterms' then  'db_sop.mst_termsandconditions'
--	when lower(@type)='cotermscondition' then  'db_sop.mst_termsandconditions'
--	when lower(@type)='suppliercategory' then  'db_masters.supplier_category'
--	when lower(@type)='countrymaster' then  '[db_masters].[Country]'
--	when lower(@type)='packinginstructions' then 'db_sop.mst_packinginstructions'
--	when lower(@type)='installationinfo' then 'db_sop.mst_installationinfo'
--	when lower(@type)='store' then 'db_mm.mst_store'
--	when lower(@type)='customercategory' then  'db_masters.customer_category'
--	when lower(@type)='transport' then  'db_masters.transport'
--	when lower(@type)='zonemaster' then  'db_masters.zonemaster'
--	when lower(@type)='bankmaster' then  'db_masters.bankmaster'
--	when lower(@type)='make' then '[db_masters].[Make]'
--	when lower(@type)='industrysegment' then '[db_hr].[lastindustrysegment]'

--	when lower(@type)='qccolours' then '[db_qc].[mst_qccolours]'
--	when lower(@type)='qclablocations' then '[db_qc].[mst_qclablocations]'
--	when lower(@type)='qcoperators' then '[db_qc].[mst_qcoperators]'
--	when lower(@type)='qcsmells' then '[db_qc].[mst_qcsmells]'
--	when lower(@type)='qctastes' then '[db_qc].[mst_qctastes]'
--	when lower(@type)='qctestgroups' then '[db_qc].[mst_qctestgroups]'
--	when lower(@type)='qctextures' then '[db_qc].[mst_qctextures]'
--	when lower(@type)='qctype' then '[db_qc].[mst_qctype]'
--	when lower(@type)='qcunitgroups' then '[db_qc].[mst_qcunitgroups]'
--	when lower(@type)='qcvaluetypes' then '[db_qc].[mst_qcvaluetypes]'
	

--	ELSE 'Other'
--END) 
--declare @columnname varchar(100)
--	set @columnname=(select CASE when lower(@type)='brand' then   'name'
--	when lower(@type)='item' then  'name'
--	when lower(@type)='uom' then  'uom'
--	when lower(@type)='roles' then  'rolename'
--	when lower(@type)='costcentre' then  'name'
--	when lower(@type)='department' then  'deptname'
--	when lower(@type)='popaymentterms' then  'name'
--	when lower(@type)='potermscondition' then  'name'
--	when lower(@type)='businesssegment' then 'businesssegement'
--	when lower(@type)='customercategory' then  'categoryname'
--	when lower(@type)='currencypreference' then  'name'
--	when lower(@type)='copaymentterms' then  'name'
--	when lower(@type)='cotermscondition' then  'name'
--	when lower(@type)='suppliercategory' then  'categoryname'
--	when lower(@type)='countrymaster' then  'countryname'
--	when lower(@type)='packinginstructions' then 'name'
--	when lower(@type)='installationinfo' then 'name'
--	when lower(@type)='store' then 'name'
--	when lower(@type)='customercategory' then  'name'
--	when lower(@type)='transport' then  'name'
--	when lower(@type)='zonemaster' then  'zonename'
--	when lower(@type)='bankmaster' then  'name'
--	when lower(@type)='make' then 'name'
--	when lower(@type)='qccolours' then 'colour'
--	when lower(@type)='qclablocations' then 'lablocations'
--	when lower(@type)='qcoperators' then 'operators'
--	when lower(@type)='qcsmells' then 'smells'
--	when lower(@type)='qctastes' then 'tastes'
--	when lower(@type)='qctestgroups' then 'qcgroup'
--	when lower(@type)='qctextures' then 'textures'
--	when lower(@type)='qctype' then 'type'
--	when lower(@type)='qcunitgroups' then 'unitgroup'
--	when lower(@type)='qcvaluetypes' then 'valuetype'
--	when lower(@type)='industrysegment' then 'name'
--	ELSE 'Other'  
--END)
declare @sql nvarchar(500)
IF (@statementtype='insert')
begin
	set @sql='INSERT INTO '+ @tablename +'( '+ @columnname +', coid, boid, isactive, createdby,createdon)'
	set @sql +=' values	('''+ @name +''','+ cast(@coid as varchar(2)) +','+ cast(@boid as varchar(2))  +',1,'+ cast(@userid as varchar(3)) +','''+ cast(@dated as varchar(15)) +''')'
	print @sql
	EXECUTE sp_executesql @sql
	end
	else
	begin
set @sql='	UPDATE  '+ @tablename +' SET '+ @columnname +'='''+ @name +''',modifiedby='+ cast(@userid as varchar(3)) +''
	set @sql +=' ,modifiedon='''+ cast(@dated as varchar(15)) +''' WHERE $IDENTITY='+ cast(@id as varchar(3)) +''	
	EXECUTE sp_executesql @sql	
	end
	print @sql
	
END


GO
/****** Object:  StoredProcedure [db_general].[pr_saveuserrights]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
--[db_general].[pr_saveuserrights] 1,1,1,10,[]
-- Description:	<Description,Get user rights>
CREATE PROCEDURE [db_general].[pr_saveuserrights] 
@coid int,
@boid int,	
@userid int,
@moduleid int,
@rights_tvp [db_general].[user_rights] readonly 
AS
BEGIN
SET NOCOUNT ON;
	declare @user int;
	
	select top 1 @user = userid from @rights_tvp
	
	-- delete records for missing functionalities in tvp 
	delete from [db_general].[user_rights] where userid = @user and moduleid = @moduleid
	
	-- insert new records
	insert into [db_general].[user_rights] (userid,moduleid,functionalityid,canview,cancreate,canedit,candelete,
	canprint,canemail,canimport,canexport,coid,boid,createdby,createdon)
	select userid,moduleid,functionalityid,canview,cancreate,canedit,candelete,
	canprint,canemail,canimport,canexport,coid,boid,@userid,getdate() from @rights_tvp  where functionalityid > 0

	select * from [db_general].[user_rights] where userid = @user and moduleid = @moduleid

	
	
END



GO
/****** Object:  StoredProcedure [db_general].[pr_script_forinsertalltablescolumn]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_generateaccesstoken] 1,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_script_forinsertalltablescolumn]

AS
BEGIN
truncate table  db_general.databasechanges
insert into db_general.databasechanges(tablename, fieldname, definition, defaultvalue, allownull,action,author)
SELECT ltrim(TABLE_SCHEMA+'.'+TABLE_NAME) tablename,	ltrim(COLUMN_NAME) fieldname ,case when character_maximum_length>0 then ltrim(DATA_TYPE)+'('+ltrim(isnull(CHARACTER_MAXIMUM_LENGTH,''))+')' else DATA_TYPE end	DATA_TYPE,
ltrim(COLUMN_DEFAULT) COLUMN_DEFAULT,case when IS_NULLABLE='NO' then 0 else 1 end IS_NULLABLE ,'ADD' action,1 author
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE not EXISTS (select tablename, fieldname  FROM db_general.databasechanges where INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA+'.'+TABLE_NAME=tablename and COLUMN_NAME=fieldname)


end


GO
/****** Object:  StoredProcedure [db_general].[pr_script_update_databasechanges]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_general].[pr_script_update_databasechanges]

AS
BEGIN
---first insert all tables with columns name in  databasechanges table


--for add default value 
--where (data_type='int' or data_type='bigint' or data_type='decimal') and column_default is  null
--add this when you want to add decimal vale  in data_type
--+'('+ ltrim(NUMERIC_PRECISION) + ',' + ltrim(numeric_scale)+')'

--insert into db_general.databasechanges(tablename, fieldname, definition, defaultvalue, allownull,action,author)
--SELECT ltrim(TABLE_SCHEMA+'.'+TABLE_NAME) tablename,	ltrim(COLUMN_NAME) fieldname ,
--case when character_maximum_length>0 then ltrim(DATA_TYPE)+'('+ltrim(isnull(CHARACTER_MAXIMUM_LENGTH,''))+')' else DATA_TYPE  end	DATA_TYPE,
--ltrim(COLUMN_DEFAULT) COLUMN_DEFAULT,case when IS_NULLABLE='NO' then 0 else 1 end IS_NULLABLE ,'ADD' action,1 author
--FROM INFORMATION_SCHEMA.COLUMNS  
--WHERE not EXISTS (select tablename, fieldname  FROM db_general.databasechanges where INFORMATION_SCHEMA.COLUMNS.TABLE_SCHEMA+'.'+TABLE_NAME=tablename and COLUMN_NAME=fieldname)

--second update all records action add to alter which column name exists but data type is diff
 update db_general.databasechanges set action='alter' 
 from db_general.databasechanges  a  WHERE definition not in  (select  case when character_maximum_length>0 then ltrim(DATA_TYPE)+'('+ltrim(isnull(CHARACTER_MAXIMUM_LENGTH,''))+')' else DATA_TYPE end	DATA_TYPE  FROM INFORMATION_SCHEMA.COLUMNS
  )
  
 --third delete all those records alerdy exists

-- delete  from db_general.databasechanges    WHERE  EXISTS  (select tablename, fieldname,definition  FROM db_general.databasechanges 
--WHERE  EXISTS (SELECT ltrim(TABLE_SCHEMA+'.'+TABLE_NAME) tablename,	ltrim(COLUMN_NAME) fieldname ,case when character_maximum_length>0 then ltrim(DATA_TYPE)+'('+ltrim(isnull(CHARACTER_MAXIMUM_LENGTH,''))+')' else DATA_TYPE end	DATA_TYPE
-- from INFORMATION_SCHEMA.COLUMNS )
--)
delete a from db_general.databasechanges a join  INFORMATION_SCHEMA.COLUMNS b on a.tablename=ltrim(TABLE_SCHEMA+'.'+TABLE_NAME) and fieldname=ltrim(COLUMN_NAME)
and action='add' 


 select * from db_general.databasechanges where action='alter' 


end


GO
/****** Object:  StoredProcedure [db_general].[pr_scriptupdate]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_generateaccesstoken] 1,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_scriptupdate]
(
	@userid INT=0
	--,@tokenVal varchar(8) OUTPUT
)
AS
BEGIN

DECLARE @myCursor cursor;
DECLARE @id int,
@sql char(5000)

BEGIN
  SET @myCursor = CURSOR FOR
        SELECT  id
        FROM db_general.databasechanges 

  OPEN @myCursor
  --print @myCursor
  --print @myCursor.tablename
  FETCH NEXT FROM @myCursor INTO @id
  --print @catgid 
  WHILE @@FETCH_STATUS = 0
        BEGIN
  DECLARE @tablename NVARCHAR(50)=( SELECT tablename FROM db_general.databasechanges WHERE ID =@id)
  DECLARE @fieldname NVARCHAR(50)=( SELECT fieldname FROM db_general.databasechanges WHERE ID =@id)
  DECLARE @definition NVARCHAR(50)=( SELECT [definition] FROM db_general.databasechanges WHERE ID =@id)
  DECLARE @action NVARCHAR(50)=( SELECT [action] FROM db_general.databasechanges WHERE ID =@id)

  IF (LOWER(@action)='add')
  BEGIN		
	          SET @sql = 'ALTER TABLE ' + @tablename + ' '+ @action + ' '+ @fieldname + ' '+ @definition + ''
			  END
IF (LOWER(@action)='alter' OR LOWER(@action)='drop')
  BEGIN		
	          SET @sql = 'ALTER TABLE ' + @tablename + ' '+ @action + ' column '+ @fieldname + ' '+ @definition + ''
			  END
IF (LOWER(@action)='default')
  BEGIN	
  SET @sql = 'ALTER TABLE ' + @tablename + ' add default 0 for '+ @fieldname
  end
			  --PRINT @sql
			  EXEC (@sql)
             FETCH NEXT FROM @myCursor INTO @id             
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END

end


GO
/****** Object:  StoredProcedure [db_general].[pr_scriptupdate_report]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_general].[pr_generateaccesstoken] 1,'token'
-- =============================================

CREATE PROCEDURE [db_general].[pr_scriptupdate_report]
AS
BEGIN

DECLARE @myCursor cursor;
DECLARE @id int,
@sql char(5000)

BEGIN
  SET @myCursor = CURSOR FOR
        SELECT  id
        FROM [db_mm].[hdr_reportfilter_param] where reportid=9
		--IF OBJECT_ID('tempdb..tempreport') IS NOT NULL 
		DROP TABLE tempreport
create table tempreport
( 
id int
)
  OPEN @myCursor 
  FETCH NEXT FROM @myCursor INTO @id 
  WHILE @@FETCH_STATUS = 0
        BEGIN
  DECLARE @fieldname NVARCHAR(50)=( SELECT paramname FROM [db_mm].[hdr_reportfilter_param] WHERE ID =@id)
  DECLARE @fieldvalue NVARCHAR(50)=( SELECT paravalue FROM [db_mm].[hdr_reportfilter_param] WHERE ID =@id)
  DECLARE @action NVARCHAR(50)='add'

  IF (LOWER(@action)='add')
  BEGIN		
	          SET @sql = 'ALTER TABLE tempreport '+ @action + ' '+ @fieldname + ' varchar(500)'
			  END	
			
			  EXEC (@sql)
             FETCH NEXT FROM @myCursor INTO @id             
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END

end


GO
/****** Object:  StoredProcedure [db_general].[pr_userlogs]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,06-05-2018>
-- Description:	<Description,For Insert user logs >
-- =============================================
CREATE PROCEDURE [db_general].[pr_userlogs] 
 @boid int,
 @coid int,
 @userid bigint,
 @deviceinfo varchar(200),
 @module varchar(200)
AS
BEGIN
	SET NOCOUNT ON;
	insert into db_general.Users_Logs (boid,coid,userid,Device_info,Module,Login_date)
	VALUES(@boid,@coid,@userid,@deviceinfo,@module,GETDATE())	
END



GO
/****** Object:  StoredProcedure [db_general].[pr_ValidateLogin]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- =============================================

-- exec [db_general].[pr_ValidateLogin] 'admin','123456'

CREATE PROCEDURE [db_general].[pr_ValidateLogin] 
	@UserName varchar(200),
	@Password varchar(100)
AS
BEGIN
	SET NOCOUNT ON;
	declare @userid bigint=0;
	SELECT @userid=isnull(userid,0)  FROM [db_masters].[users] WHERE username = @username AND usrpwd = @password
	IF (@userid>0)
		Begin
			-- generate access token for the user
			exec [db_general].[pr_generateaccesstoken] @userid
			-- select user data
			SELECT coid,boid, [userid],[U].[username] firstname,[middlename],[lastname],[aliasname],isnull([designationid],0) desginationid,[emailid],[useraccesstoken]
				,[lastlogindate],[U].[username] token1,[usrpwd] token2
			FROM [db_masters].[users] U
			where [isactive] = 1 and userid = @userid
			-- select companies in which user can work
		    select  c.coid,B.boid, B.unitname,c.companyname, (b.address1 + ', ' + b.address2) as unitaddress, b.[city],b.[state],b.[country],b.[countryid],
			b.pin, b.mobile_number, b.phone_number, b.fax, b.email,b.gstno,B.PAN,c.logo companylogo,b.logo branchlogo,c.cin,website,c.osservertype
			from [db_masters].[company] c 			
			join [db_general].[company_branches] B on c.coid = B.coid
			where B.boid in (select distinct(boid) from [db_general].[user_branches] where userid =@userid) and B.isactive = 1
			--select  A.coid,A.boid, B.unitname,c.companyname, (b.address1 + ', ' + b.address2) as unitaddress, b.[city],b.[state],b.[country],
			--b.pin, b.mobile_number, b.phone_number, b.fax, b.email,b.gstno,B.PAN,c.logo companylogo,b.logo branchlogo,c.cin,website
			--from [db_general].[user_branches] A 
			--join [db_general].[company_branches] B on A.boid = B.boid
			--join [db_masters].[company] c on c.coid = b.coid
			--where A.userid = @userid and B.isactive = 1
			-- select financial years
			select [id] fyid, [fyname],[fystartdate],[fyenddate] 
			from [db_masters].[financialyears] where [isActive] = 1 order by id desc

			select * from [db_masters].[gst_lut]
			--exec [db_general].[pr_getusermenus]  @userid
			/*IF OBJECT_ID('tempdb..#tempuserrights') IS NOT NULL DROP TABLE #tempuserrights
			create table #tempuserrights
			(
				userid int,
				moduleid int,
				module varchar(50),
				functionalityid int,
				functionality varchar(100),
				menuname varchar(100),
				menulink varchar(500),
				functionalityparentid int,
				functionalityorderno int,
				canview bit default 0,
				cancreate bit default 0,
				canedit bit default 0,
				candelete bit default 0,
				canprint bit default 0,
				canemail bit default 0,
				canimport bit default 0,
				canexport bit default 0
			)
			insert into #tempuserrights (userid,moduleid,functionalityid,canview,cancreate,canedit,candelete,
			canprint,canemail, canimport,canexport)
			select userid,moduleid, functionalityid, 
				isnull(canview,0) canview,isnull(cancreate,0) cancreate,isnull(canedit,0) canedit,
				isnull(candelete,0) candelete,isnull(canprint,0) canprint,isnull(canemail,0) canemail,
				isnull(canimport,0) canimport,isnull(canexport,0) canexport 
			from [db_general].[user_rights] ur 
			where  userid = @userid
			-- update module name 
			update #tempuserrights set module = a.modulename 
			from db_masters.erp_modules a where #tempuserrights.moduleid = a.id
			-- update functionality name 
			update #tempuserrights set functionality = a.functionality, menuname = a.menuname, menulink=a.menulink  
			from  db_general.erp_modules_functionalities  a where #tempuserrights.functionalityid = a.id
			-- select user rights
			select * from #tempuserrights;
		select moduleid,module from #tempuserrights group by moduleid,module;
			drop table #tempuserrights;*/
		End
	ELSE
		Begin
			SELECT 'false' AS userexists
		End
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_commonapihr]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,navneet>
-- Create date: <Create Date,26-04-2019>
-- Description:	<Description,Get list of data from master tables >
-- [db_hr].[pr_commonapihr] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_hr].[pr_commonapihr]	
    @coid int,
	@boid int,	
	@fyid int,
	@userid int
	AS
BEGIN
	SET NOCOUNT ON;	
	select id,name rcategory from [db_hr].[mst_resumecategory]
	select id,name rsource from [db_hr].[mst_resumesources]
	select id,name rskillset from [db_hr].[mst_skillsets]
	select id,qualification from [db_hr].[mst_qualification] 
	select id, name lastindustrysegment from [db_hr].[lastindustrysegment]
	select id,name from  db_hr.mst_resumestatus
	select id,name as deptid from db_hr.mstDept
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_commonapitraining]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,navneet>
-- Create date: <Create Date,26-04-2019>
-- Description:	<Description,Get list of data from master tables >
--[db_hr].[pr_commonapitraining]	 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_hr].[pr_commonapitraining]	
    @coid int,
	@boid int,	
	@fyid int,
	@userid int
	AS
BEGIN
	SET NOCOUNT ON;	
	select isnull(max(id),0) as LastTrainingId from [db_hr].[trg_hdr_calender]
	select id,coursearea FROM [db_hr].[trg_majorarea]
	select id,venuename from [db_hr].[trg_mst_venues]
	select id,name from [db_hr].[mst_status]
	select id,courseno,refno,coursedescription,coursevenue,coursedays,coursehours,coursecertreqd from [db_hr].[trg_mst_courses]
	select id,facultyname,facultyaddress,facultycontactno,facultycharges from [db_hr].[trg_mst_faculty]
	select id,name from db_hr.mstDept
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_getappraisallist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_hr].[pr_getappraisallist] 1,100,1,1

CREATE PROCEDURE [db_hr].[pr_getappraisallist]
	@PageNumber INT=1,
	@PageSize INT=100,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='empname',
	@sortorder nvarchar(100)='asc',
	@search varchar(50)='',
	@userid int=1,
	@dept int = 0
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql= 'Select emp.id as empid,emp.empno,emp.empname,des.designation,dept.name deptname
               from db_masters.employee emp
               left join db_masters.designations des on emp.designationid = des.id
               left join db_hr.mstDept dept on emp.deptid = dept.id'
    if(@dept>0)
    begin
    set @sql +=' where emp.deptid='+CAST(@dept as varchar(50))+''
    end
	if(@dept>0 and @search <>'')
    begin
    set @sql +=' and emp.empname like '+'''%'+cast(@search as varchar(50)) + '%'' or des.designation like '+'''%'+cast(@search as varchar(50)) + '%'' 
	             or dept.deptname like '+'''%'+cast(@search as varchar(50)) + '%'''
    end
    if(@dept=0 and @search <>'') 
	begin
	set @sql += 'where emp.empname like '+'''%'+cast(@search as varchar(50)) + '%'' or des.designation like '+'''%'+cast(@search as varchar(50)) + '%'' 
	             or dept.deptname like '+'''%'+cast(@search as varchar(50)) + '%'''	             
	end			 
	print @sql
	EXEC sp_executesql @sql
	set @sql='select count(id)records from db_masters.employee'
	print @sql
	EXEC sp_executesql @sql
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_getcommanapi_appraisal]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,23-12-2019>
-- Description:	<Description,Get CommonApi data>
-- =============================================
-- exec [db_hr].[pr_getcommanapi_appraisal] 1,1,1,1 

 CREATE PROCEDURE [db_hr].[pr_getcommanapi_appraisal] 
 @coid int,
 @boid int,
 @fyid int,
 @userid int
 AS
 BEGIN	
	select * from db_hr.mstDept
    select * from db_hr.mst_kra_catg
    select emp.id,emp.coid,emp.boid,emp.empno,emp.empname,emp.designationid,desg.designation, emp.current_address1,emp.current_address2,emp.current_state,emp.current_city,emp.current_country,
	emp.permanent_address1,emp.permanent_address2,emp.permanent_state,emp.permanent_city,emp.permanent_country,emp.religion,emp.deptid,emp.genderid,emp.aadharno,
	emp.nameinaadhar,emp.nameinbank,emp.mobile_no,emp.other_phone,emp.dob,emp.doj,emp.marital_statusid,emp.esiflag,emp.esino,emp.pfflag,emp.pfno,emp.pfrate,emp.fpfrate,emp.uan,
	emp.pfjoiningdate,emp.esijoiningdate,emp.domicile,emp.citizen_of,emp.esidispensaryid,emp.voterid,emp.passportno,emp.passportissuedat,emp.passportvalidupto,
	emp.divinglicense_no,emp.issuedat,emp.validupto,emp.bankid,emp.bankacno,emp.bankbranch,emp.bankifsc,emp.sports_ncc_info,emp.civildefenceinfo,emp.csrinfo,
	emp.biometric_code,emp.createdby,emp.createdon,emp.modifiedby,emp.modifiedon,emp.deactivatedby,emp.deactivatedon,emp.source,emp.referral_remarks,emp.email,
	emp.father_husbandname,emp.mothername , reportingto= stuff((select ',' + stid.splstatusname 
	from db_masters.emp_splstatus dtlid
	left  join db_masters.mst_empsplstatus stid on dtlid.splstatusid = stid.id
	where dtlid.empid=emp.id   FOR XML PATH ('')), 1, 1, '')	
	from db_masters.employee emp
	left join db_hr.mstDept dept on emp.deptid = dept.id
    left join db_masters.designations desg on emp.designationid =desg.id

	select mst.id,mst.coid,mst.boid,mst.apr_kra_catgid,mst.apr_kra_srno,mst.apr_kraname,mst.appr_kra_detail apr_kradetail,
	rting.apr_marks_from, rting.apr_marksupto apr_max_marks 
	from db_hr.mst_kras mst 
	left join db_hr.mst_apr_rating rting on mst.appr_marks_rating = rting.id

	select id,apr_rating rating from db_hr.mst_apr_rating

 END

GO
/****** Object:  StoredProcedure [db_hr].[pr_getGetAppraisaldata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,navneet>
-- Create date: <Create Date,25-12-2019>
-- Description:	<Description,Get list of data from master tables >
-- [db_hr].[pr_getGetAppraisaldata]	 1,1,1,1
-- =============================================

CREATE PROCEDURE [db_hr].[pr_getGetAppraisaldata]	
    @coid int,
	@boid int,	
	@fyid int,
	@userid int
	AS
BEGIN
	SET NOCOUNT ON;		
	 select id,name from db_hr.mstDept

	 -- select id,empname from db_masters.employee

	 select userid,firstname +' '+ lastname employee from db_masters.users

END

GO
/****** Object:  StoredProcedure [db_hr].[pr_getresumedata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_hr].[pr_getresumedata] 1,1,'jai'
CREATE PROCEDURE [db_hr].[pr_getresumedata] 
    @coid int,
	@boid int,	
	@search varchar(100)='',	
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);	
	begin  
	set @sql= 'select name,fathername ,phone,email,dob from [db_hr].[hdr_resume] h
	where h.createdby in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))'
	set @sql += ' and h.coid = '+ cast(@coid as varchar(5)) +' and h.boid='+ cast(@boid as varchar(5))	
	if(@search!='')
	begin
		 set @sql += ' and h.name like '+'''%'+cast(@search as varchar(50)) + '%''or h.fathername like '+'''%'+cast(@search as varchar(50)) + '%''
	or h.phone like '+'''%'+cast(@search as varchar(50)) + '%''or h.email like '+'''%'+cast(@search as varchar(50)) + '%'''
	end 	
	print @SQL
	EXEC sp_executesql @SQL
END
end
GO
/****** Object:  StoredProcedure [db_hr].[pr_getresumedetails]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- =============================================  
-- Author:  <Author,Amit>  
-- Create date: <Create Date,03-12-2018>  
-- Description: <Description,Get supplier data>  
-- [db_hr].[pr_getresumedetails]  1,1,10,32  
-- =============================================  
 
CREATE PROCEDURE [db_hr].[pr_getresumedetails]   
 @coid int,  
 @boid int,  
 @fyid int,  
 @resumeid int  
AS  
BEGIN  
SET NOCOUNT ON;  
  
   select * from [db_hr].[hdr_resume] where id=@resumeid  
  
   select dt.id,dt.resumeid,dt.organization,dt.totexpyy,dt.totexpmm,dt.relevantexpyy,dt.relevantexpmm,  
   dt.positionheld,dt.reportingto,dt.remarks,dt.expfrom,dt.expto,dt.deptid,dept.name as deptname,dt.lastindustrysegment, indseg.name as lastindustrysegmentname 
   from [db_hr].[dtl_resumeexperience] dt  
   left join db_hr.mstDept dept on dt.deptid = dept.id 
   left join db_hr.lastindustrysegment indseg on dt.lastindustrysegment=indseg.id
   where resumeid=@resumeid  
  
   select dtl.*, mst.qualification from [db_hr].[dtl_resumequalification] dtl  
   join db_hr.mst_qualification mst on dtl.qualificationid = mst.id  
   where resumeid=@resumeid  
  
   select * from [db_hr].[dtl_resumeskills] where resumeid=@resumeid  
  
   select * from [db_hr].[dtl_resumecategory] where resumeid=@resumeid  
  
   select id,name rcategory from [db_hr].[mst_resumecategory]  
  
   select id,name rsource from [db_hr].[mst_resumesources]  
     
   select id,name rskillset from [db_hr].[mst_skillsets]  
     
   select id,qualification from [db_hr].[mst_qualification]   
  
   select id, name lastindustrysegment from [db_hr].[lastindustrysegment]  
  
   select id,name from  db_hr.mst_resumestatus  
  
   select id,name as deptid from db_hr.mstDept  
  
end  
GO
/****** Object:  StoredProcedure [db_hr].[pr_getresumelist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_hr].[pr_getresumelist] 1,200,1,1,'trainee','a.id','desc','','4'

 CREATE PROCEDURE [db_hr].[pr_getresumelist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='a.id',
	@sortorder nvarchar(100)='desc',
	@resumestatus varchar(20)='',
	@deptid varchar(20)='',
	@fromdate varchar(20)='',
	@todate  varchar(20)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);
	begin
	set @sql='select * from (select hdr.id, hdr.name,hdr.fathername,
	          qualification=stuff((select '','' + mt.qualification from [db_hr].[dtl_resumequalification] dtl 
              join [db_hr].[mst_qualification] mt on dtl.qualificationid = mt.id where dtl.resumeid = hdr.id 
              FOR XML PATH ('''')), 1, 1, ''''),hdr.phone as contact,
			  (select sum(totexpyy) from db_hr.dtl_resumeexperience where resumeid=hdr.id GROUP by resumeid )totexpyy,
	          hdr.currentdesignation,dept.name as deptname, 
			  (select top (1) organization from db_hr.dtl_resumeexperience where resumeid=hdr.id) as company,
			  (select top (1) ls.name from db_hr.dtl_resumeexperience dtl left join db_hr.lastindustrysegment 
               ls on dtl.lastindustrysegment=ls.id  where resumeid=hdr.id) as companytype,
               (select top (1) expfrom +''to''+expto  from db_hr.dtl_resumeexperience where resumeid=hdr.id) as duration,
			  hdr.currentsalary,hdr.hometown,hdr.remarks,
			  category = stuff((select '','' + cat.name from [db_hr].[dtl_resumecategory] dtl 
              join [db_hr].[mst_resumecategory] cat on dtl.categoryid = cat.id where dtl.resumeid = hdr.id 
              FOR XML PATH ('''')), 1, 1, ''''),hdr.currentlocation,			  
              st.name as status,st.colorcode,res.name as source,
			  hdr.statusid,hdr.dueon             
              from [db_hr].[hdr_resume] hdr
              left join [db_hr].[mst_resumesources] res on hdr.sourceid = res.id 
              left join [db_hr].[mst_skillsets] sks on hdr.skillsetid = sks.id
			  left join [db_hr].[mst_resumestatus] st on hdr.statusid = st.id
			  left join db_hr.mstDept dept on hdr.co_deptid=dept.id'
	set @sql += ' where hdr.coid = '+ cast(@coid as varchar(5)) +' and hdr.boid='+ cast(@boid as varchar(5))+' '
	if(@deptid!='')
	begin 
	set @sql +=' and hdr.co_deptid ='+''''+cast(@deptid as VARCHAR(10))+''''
	end   
	set @sql += ') a where '
	if(@resumestatus!='' and @search='')
	begin 
	set @sql +='a.statusid='+''''+cast(@resumestatus as VARCHAR(10))+''''
	end
    if(@search!='' and @resumestatus='')
	begin 
	set @sql +=' a.name like ''%' + cast(@search as varchar(100)) + '%'' or a.currentlocation like ''%' + cast(@search as varchar(100)) + '%''or a.contact like ''%' + cast(@search as varchar(100)) + '%'' or a.category like ''%' + cast(@search as varchar(100)
)
    + '%'' or a.qualification like ''%' + cast(@search as varchar(100)) + '%'''
	end
	if (@search!='' and @resumestatus!='')
	begin
	set @sql +='a.statusid='+''''+cast(@resumestatus as VARCHAR(10))+''' and a.name like ''%' + cast(@search as varchar(100)) + '%'' or a.currentlocation like ''%' + cast(@search as varchar(100)) + '%''or a.contact like ''%' + cast(@search as varchar(100)) +
    '%'' or a.category like ''%' + cast(@search as varchar(100)) + '%'''
	end
    if (@search ='' and @resumestatus ='')
	begin
	set @sql +='a.id>0'
	end
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
     FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End
	print @SQL
	EXEC sp_executesql @SQL
	set @totalcount = 'select count(hdr.id) records
        from [db_hr].[hdr_resume] hdr
        left join [db_hr].[mst_resumecategory] cat on hdr.postappliedfor = cat.id
        left join [db_hr].[mst_resumesources] res on hdr.sourceid = res.id 
        left join [db_hr].[mst_skillsets] sks on hdr.skillsetid = sks.id
		left join [db_hr].[mst_resumestatus] st on hdr.statusid = st.id'
    if(@resumestatus!='')
	begin 
	set @totalcount +=' where hdr.statusid='+''''+cast(@resumestatus as VARCHAR(10))+''''
	end
	--if(@search!='')
	--begin 
	--set @totalcount +=' and hdr.name like ''%' + cast(@search as varchar(100)) + '%'''
	--end
	end
	print @totalcount
	EXEC sp_executesql @totalcount
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_getresumestatus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_hr].[pr_getresumestatus]	
    @coid int,
	@boid int,	
	@fyid int
	AS
BEGIN
  SET NOCOUNT ON;
  	
    select id,name as resumestatus from db_hr.mst_resumestatus

	select id,name from db_hr.mstDept

END

GO
/****** Object:  StoredProcedure [db_hr].[pr_gettrainingData]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Deepika>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get Training data>
-- [db_hr].[pr_gettrainingData] 1,1,12
-- =============================================
CREATE PROCEDURE [db_hr].[pr_gettrainingData]
	@coid int = 1,
	@boid int = 1,
	@id Int
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE  @PageNumber INT =1,@PageSize INT =100,@sort nvarchar(100)= 'boid',@sortorder nvarchar(100)= 'asc'

	SELECT hdr.id,hdr.courserefno,hdr.courseid,hdr.coursedescription,
	case when coursedatefrom ='1900-01-01 00:00:00' then '' 
	else FORMAT (coursedatefrom,'yyyy-MM-dd') end coursedatefrom,
	case when coursedateto ='1900-01-01 00:00:00' then '' 
	else FORMAT (coursedateto,'yyyy-MM-dd') end coursedateto,
	hdr.coursedays,hdr.coursehours,
	case when [coursestarttime] ='00:00:00' then ''
	else FORMAT([coursestarttime],'hh:MM:SS') end [coursestarttime],
	case when [courseendtime] ='00:00:00' then ''
	else FORMAT([courseendtime],'hh:mm:SS') end [courseendtime],
    --hdr.coursestarttime,hdr.courseendtime,
	hdr.venuetype,hdr.venueid,ven.venuename,hdr.coursestatusid,hdr.coursefacilities,
	hdr.facultytype,hdr.facultyid,fac.facultyname as facultyname,hdr.coursemajorareaid,hdr.createdby,hdr.createdon,hdr.modifiedby,
	hdr.modifiedby,hdr.coid,hdr.boid,are.coursearea as coursearea,st.name as status,[trainingcost],[trainingbtchsize]
	from [db_hr].[trg_hdr_calender] hdr
	left join [db_hr].[mst_status] st on hdr.coursestatusid=st.id
	left join [db_hr].[trg_mst_faculty] fac on hdr.facultyid=fac.id
	left join [db_hr].[trg_mst_venues] ven on hdr.venueid=ven.id
	left join [db_hr].[trg_mst_courses] cour on hdr.courseid=cour.id
	left join [db_hr].[trg_majorarea] are on hdr.coursemajorareaid=are.id
	where hdr.id =  @id and hdr.coid= @coid and hdr.boid=@boid
	select id,coursearea FROM [db_hr].[trg_majorarea]
	select id,venuename from [db_hr].[trg_mst_venues]
	select id,courseno,refno,coursedescription,coursevenue,coursedays,coursehours,coursecertreqd from [db_hr].[trg_mst_courses]
	select id,facultyname,facultyaddress,facultycontactno,facultycharges from [db_hr].[trg_mst_faculty]

END

GO
/****** Object:  StoredProcedure [db_hr].[pr_gettraininglist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_hr].[pr_gettraininglist] 1,200,1,1,'','hdr.id','desc','','',''

   CREATE PROCEDURE [db_hr].[pr_gettraininglist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='hdr.id',
	@sortorder nvarchar(100)='desc',
	@fromdate varchar(20)='',
	@todate varchar(20)='',
	@status varchar(20)='',
	@id Int = NULL
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);
	begin
	set @sql='SELECT hdr.id,hdr.courserefno,hdr.courseid,hdr.coursedescription,
	 case when hdr.coursedatefrom =''1900-01-01 00:00:00'' then '''' 
	else FORMAT (hdr.coursedatefrom,''yyyy-MM-dd'') end coursedatefrom,
	 case when hdr.coursedateto =''1900-01-01 00:00:00'' then '''' 
	else FORMAT (hdr.coursedateto,''yyyy-MM-dd'') end coursedateto,	
	hdr.coursedays,hdr.coursehours,
	hdr.coursestarttime,hdr.courseendtime,hdr.venuetype,hdr.venueid,ven.venuename,hdr.coursestatusid,hdr.coursefacilities,
	hdr.facultytype,fac.facultyname as facultyname,hdr.facultyid,hdr.coursemajorareaid,are.coursearea as coursearea,hdr.createdby,hdr.createdon,hdr.modifiedby,
	hdr.modifiedby,hdr.coid,hdr.boid,st.name as status
	FROM [db_hr].[trg_hdr_calender] hdr
	left join [db_hr].[mst_status] st on hdr.coursestatusid=st.id
	left join [db_hr].[trg_mst_faculty] fac on hdr.facultyid=fac.id
	left join [db_hr].[trg_mst_venues] ven on hdr.venueid=ven.id
	left join [db_hr].[trg_mst_courses] cour on hdr.courseid=cour.id
	left join [db_hr].[trg_majorarea] are on hdr.coursemajorareaid=are.id'
	set @sql += ' where hdr.coid = ' + cast(@coid as varchar(5)) + ' and hdr.boid = ' + cast(@boid as varchar(5))
    if (@id <>0)
		begin
		set @sql+=' and hdr.id =  '+  cast(@id as varchar(5)) +'' 
		PRINT @sql
		END
		if(@search!='')
		begin
		 set @sql += ' and hdr.coursedescription like '+'''%'+cast(@search as varchar(50)) + '%'''
		end 
		if(@sort!='' and @sortorder!='')
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
     FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End
	print @SQL
	EXEC sp_executesql @SQL
	set @totalcount = 'select count(hdr.id) as records
        from [db_hr].[trg_hdr_calender] hdr
		left join [db_hr].[mst_status] st on hdr.coursestatusid=st.id
	left join [db_hr].[trg_mst_faculty] fac on hdr.facultyid=fac.id
	left join [db_hr].[trg_mst_venues] ven on hdr.venueid=ven.id
	left join [db_hr].[trg_mst_courses] cour on hdr.courseid=cour.id
	left join [db_hr].[trg_majorarea] are on hdr.coursemajorareaid=are.id'
    if(@status!='')
	begin 
	set @totalcount +=' where hdr.coursestatusid='+''''+cast(@status as VARCHAR(10))+''''
	END
		if(@search!='')
		begin
		 set @sql += ' and hdr.coursedescription like '+'''%'+cast(@search as varchar(50)) + '%'''
		end 
	end
	print @totalcount
	EXEC sp_executesql @totalcount
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_SaveApraisal]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Navneet>
-- Create date: <Create Date,23-12-2019>
-- Description:	<Description,Save Appraisal data>
-- =============================================
CREATE PROCEDURE [db_hr].[pr_SaveApraisal]
    @statementtype nvarchar(50),
	@hdr_Appr [db_hr].[hdr_appraisals_tvp] readonly,
	@dtl_Appr [db_hr].[dtl_appraisals_tvp] readonly,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100) 
	declare @apprid bigint;

	if (@statementtype='Insert')
	 BEGIN        
		insert into [db_hr].[hdr_appraisals]
	    (apr_kra_catgid,empid,current_designation,current_dept,deptid,fyid,apr_from,apr_upto,apr_stage,apr_byid,apr_completedon,apr_reviewbyid,review_completedon,apr_total_marks,apr_max_marks,apr_rating,review_total_marks,review_max_marks,review_rating,apr_final_remarks,review_final_remarks,apr_trg_needs,review_trg_needs,md_final_remarks,md_final_rating,md_completed_date,md_trg_needs)	    
		select apr_kra_catgid,empid,current_designation,current_dept,deptid,fyid,apr_from,apr_upto,apr_stage,apr_byid,apr_completedon,apr_reviewbyid,review_completedon,apr_total_marks,apr_max_marks,apr_rating,review_total_marks,review_max_marks,review_rating,apr_final_remarks,review_final_remarks,apr_trg_needs,review_trg_needs,md_final_remarks,md_final_rating,md_completed_date,md_trg_needs
		from  @hdr_Appr	
		set @apprid= SCOPE_IDENTITY()
		insert into db_hr.dtl_appraisals(apr_id,apr_kra_srno,apr_kraname,apr_kradetail,apr_marks_rating,apr_marksawarded,apr_max_marks,apr_remarks,apr_ratingid,apr_rating,review_ratingid,review_rating,review_marksawarded,review_max_remarks,review_remarks)
		select @apprid,apr_kra_srno,apr_kraname,apr_kradetail,apr_marks_rating,apr_marksawarded,apr_max_marks,apr_remarks,apr_ratingid,apr_rating,review_ratingid,review_rating,review_marksawarded,review_max_remarks,review_remarks
		from @dtl_Appr		 
	End

    if (@statementtype='Update')        
		select @apprid =id from @hdr_Appr
	    BEGIN
			 UPDATE  [db_hr].[hdr_appraisals]  set 
                     apr_kra_catgid=a.apr_kra_catgid,
                     empid=a.empid,
                     current_designation=a.current_designation,
                     current_dept=a.current_dept,
                     deptid=a.deptid,
                     fyid=a.fyid,
                     apr_from=a.apr_from,
                     apr_upto=a.apr_upto,
                     apr_stage=a.apr_stage,
                     apr_byid=a.apr_byid,
                     apr_completedon=a.apr_completedon,
                     apr_reviewbyid=a.apr_reviewbyid,
                     review_completedon=a.review_completedon,
                     apr_total_marks=a.apr_total_marks,
                     apr_max_marks=a.apr_max_marks,
                     apr_rating=a.apr_rating,
                     review_total_marks=a.review_total_marks,
                     review_max_marks=a.review_max_marks,
                     review_rating=a.review_rating,
                     apr_final_remarks=a.apr_final_remarks,
                     review_final_remarks=a.review_final_remarks,
                     apr_trg_needs=a.apr_trg_needs,
                     review_trg_needs=a.review_trg_needs,
                     md_final_remarks=a.md_final_remarks,
                     md_final_rating=a.md_final_rating,
                     md_completed_date=a.md_completed_date,
					 md_trg_needs=a.md_trg_needs                   	   				
					FROM  @hdr_Appr a	
					where [db_hr].[hdr_appraisals].id = @apprid

				-- delete records for missing skills in tvp 
				delete from db_hr.dtl_appraisals where apr_id=@apprid
				-- update existing enteries in 	[db_hr].[@resumeskills] 

		insert into db_hr.dtl_appraisals(apr_id,apr_kra_srno,apr_kraname,apr_kradetail,apr_marks_rating,apr_marksawarded,apr_max_marks,apr_remarks,apr_ratingid,apr_rating,review_ratingid,review_rating,review_marksawarded,review_max_remarks,review_remarks)
		select @apprid,apr_kra_srno,apr_kraname,apr_kradetail,apr_marks_rating,apr_marksawarded,apr_max_marks,apr_remarks,apr_ratingid,apr_rating,review_ratingid,review_rating,review_marksawarded,review_max_remarks,review_remarks
		from @dtl_Appr

     End
  END

GO
/****** Object:  StoredProcedure [db_hr].[pr_saveemp_uploadinfo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_hr].[pr_saveemp_uploadinfo]
    @statementtype nvarchar(50),
	@userid int=1,
	@filename VARCHAR(200),
    @imageinfo VARCHAR(MAX)=NULL,
	@coid int,
	@boid int,
	@fyid INT,
	@empid BIGINT,
	@remarks VARCHAR(MAX)=NULL
  AS
 BEGIN 
 SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	DECLARE @error VARCHAR(100)   
		If (@statementtype='Insert')
		BEGIN			
			 --INSERT Images
		  insert into [db_masters].[empdocument_images]
		  ([empid],[doctype],[filename],[imageinfo],[isactive],[createdby],[createdon],remarks)
		  VALUES(@empid,0,@filename,@imageinfo,1,@userid,getdate(),@remarks)

		  IF @@ERROR <> 0
			 BEGIN
			 -- Rollback the transaction
			 ROLLBACK
			 -- Raise an error and return
			 	RAISERROR ('Error ', 16, 1)
			 SET @error = 'Error no : ' + CAST(@@error AS VARCHAR(3))
			 RETURN @error 
			 END
	    END

		If (@statementtype='Update')
		BEGIN			
		 Update db_masters.employee set emp_image=@imageinfo,[filename]=@filename WHERE id=@empid
		 IF @@ERROR <> 0
			 BEGIN
			 -- Rollback the transaction
			 ROLLBACK
			 -- Raise an error and return
			 	RAISERROR ('Error ', 16, 1)
			 SET @error = 'Error no : ' + CAST(@@error AS VARCHAR(3))
			 RETURN @error 
			 END
	    END

END

GO
/****** Object:  StoredProcedure [db_hr].[pr_savehdrresume]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_hr].[pr_savehdrresume]  
 @statementtype nvarchar(50),  
 @hdrresume [db_hr].[hdr_resume_tvp] readonly,  
 @resumeskills [db_hr].[dtl_resumeskills_tvp] readonly,  
 @resumecategory [db_hr].[dtl_resumecategory] readonly,  
 @userid int=1,  
 @coid int=1,  
 @boid int=1,  
 @fyid int=1   
AS  
BEGIN   
SET QUOTED_IDENTIFIER OFF;  
 SET ANSI_NULLS ON;     
 SET NOCOUNT ON;  
 declare @error VARCHAR(100)   
 declare @resumeid bigint;  
 if (@statementtype='Insert')  
     BEGIN          
  insert into [db_hr].[hdr_resume]  
  (sourceid,name,gender,dob,age,statusid,phone,email,totexpyy,totexpmm,currentsalary,ctc,fathername,mothername,husbandname,hometown,currentorg,currentdept,currentdesignation,currentlocation,[references],remarks,documents,isactive,coid,boid,createdby,createdon,colorcode,expectedsalary,lastindustrysegment,otherContactNo,commaddress,co_deptid)       
  select  sourceid,name,gender,dob,age,statusid,phone,email,totexpyy,totexpmm,currentsalary,ctc,fathername,mothername,husbandname,hometown,currentorg,currentdept,currentdesignation,currentlocation,[references],remarks,documents,isactive,coid,boid,createdby,getdate(),colorcode,expectedsalary,lastindustrysegment,otherContactno,[commaddress],co_deptid  
  from  @hdrresume  
  
  set @resumeid= SCOPE_IDENTITY() 
  
  insert into db_hr.dtl_resumeskills (resumeid,skillid) select @resumeid, skillid from @resumeskills  
  insert into db_hr.dtl_resumecategory (resumeid,categoryid) select @resumeid, categoryid from @resumecategory    
  
  --select @resumeid resumeid 

  select * from [db_hr].[hdr_resume] where id = @resumeid  

 End  
     if (@statementtype='Update')  
     BEGIN  
    UPDATE [db_hr].[hdr_resume]  set   
           [sourceid]   = a.sourceid,  
           name = a.name,  
           [gender]= a.gender,  
           [dob]= a.dob,  
           [age] = a.age,                        
           [statusid]=a.statusid,  
           [phone]= a.phone,  
           [email]=a.email,  
           [totexpyy]= a.totexpyy,  
           [totexpmm]=a.[totexpmm],  
           [currentsalary]=a.[currentsalary],  
           [ctc]=a.[ctc],  
           [fathername]=a.[fathername],  
           [mothername]=a.[mothername],  
           [husbandname]=a.[husbandname],  
           [hometown]= a.hometown,  
           [currentorg]= a.currentorg,  
           [currentdept]= a.currentdept,                        
           [currentdesignation]= a.currentdesignation,  
           [currentlocation]=a.currentlocation,  
           [references]= a.[references],  
           [remarks]=a.remarks,  
           [isactive]=a.isactive,  
           [coid]=a.coid,  
           [boid]=a.boid,  
           [colorcode]=a.colorcode,  
           [expectedsalary]=a.expectedsalary,  
           [lastindustrysegment]=a.lastindustrysegment,  
           [commaddress]= a.[commaddress],  
           [otherContactNo]= a.[otherContactNo],
		   [co_deptid]=a.[co_deptid]
     FROM  @hdrresume a where [db_hr].[hdr_resume].id = a.id  
    -- delete records for missing skills in tvp   
    delete from [db_hr].[dtl_resumeskills] where resumeid in (select distinct resumeid from @resumeskills) and   
    id not in (select id from @resumeskills)  
    -- update existing enteries in  [db_hr].[@resumeskills]   
    update [db_hr].[dtl_resumeskills] set skillid  = a.skillid   
    from @resumeskills a where [db_hr].[dtl_resumeskills].id = a.id and    
    [db_hr].[dtl_resumeskills].resumeid = a.resumeid  
    -- insert new records  
    insert into [db_hr].[dtl_resumeskills] (resumeid,skillid)  
    select resumeid,skillid from @resumeskills where id not in (select distinct id from [db_hr].[dtl_resumeskills])  
    -- delete records for missing categories in tvp   
    delete from [db_hr].[dtl_resumecategory] where resumeid in (select distinct resumeid from @resumecategory) and   
    id not in (select id from @resumecategory)  
    -- update existing enteries in  [db_hr].[dtl_resumeexperience]   
    update [db_hr].[dtl_resumecategory] set categoryid  = a.categoryid   
    from @resumecategory a where [db_hr].[dtl_resumecategory].id = a.id and    
    [db_hr].[dtl_resumecategory].resumeid = a.resumeid  
    -- insert new records  
    insert into [db_hr].[dtl_resumecategory] (resumeid,categoryid)  
    select resumeid,categoryid from @resumecategory where id not in (select distinct id from [db_hr].[dtl_resumecategory])  
       select @resumeid=id from @hdrresume  
    select * from [db_hr].[hdr_resume] where id = @resumeid  
       End  
  END  
GO
/****** Object:  StoredProcedure [db_hr].[pr_saveresumeexperience]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [db_hr].[pr_saveresumeexperience]
    @resumeexperience [db_hr].[dtl_resumeexperience_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100) 
	
	  declare @resumeid int;

	  select top 1 @resumeid = resumeid from @resumeexperience 

	  delete from [db_hr].[dtl_resumeexperience] where resumeid = @resumeid
	
	--delete from [db_hr].[dtl_resumeexperience] where resumeid = (select resumeid from @resumeexperience) and 
	--id not in (select id from @resumeexperience)

	-- update existing enteries in 	[db_hr].[dtl_resumeexperience]
	
	--update [db_hr].[dtl_resumeexperience] 
	--set organization = a.organization, totexpyy = a.totexpyy, totexpmm = a.totexpmm, relevantexpyy = a.relevantexpyy,
	--relevantexpmm = a.relevantexpmm, positionheld = a.positionheld, reportingto = a.reportingto, remarks = a.remarks,expfrom=a.expfrom,expto=a.expto
	--from @resumeexperience a where [db_hr].[dtl_resumeexperience].id = a.id and  
	--[db_hr].[dtl_resumeexperience].resumeid = a.resumeid

	-- insert new records

	insert into [db_hr].[dtl_resumeexperience]  
	(resumeid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,reportingto,remarks,expfrom,expto,deptid,lastindustrysegment)
	 select resumeid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,
	 reportingto,remarks,expfrom,expto,deptid,lastindustrysegment  from @resumeexperience
	 --where id not in (select id from [db_hr].[dtl_resumeexperience])

	
  END


GO
/****** Object:  StoredProcedure [db_hr].[pr_saveresumequalification]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_hr].[pr_saveresumequalification]
    @resumequalification [db_hr].[dtl_resumequalification_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100) 
	declare @resumeid int;
	select top 1 @resumeid = resumeid from @resumequalification 
	delete from [db_hr].[dtl_resumequalification] where resumeid = @resumeid
	-- delete records for missing functionalities in tvp 
	-- delete from [db_hr].[dtl_resumequalification] where resumeid = @resumeid and id not in (select id from @resumequalification)
	-- update existing enteries in 	[db_hr].[dtl_resumequalification] 
	--update [db_hr].[dtl_resumequalification] 
	--set qualificationid = a.qualificationid, institute = a.institute, passingyear = a.passingyear, grades = a.grades,
	--remarks = a.remarks	from @resumequalification a where [db_hr].[dtl_resumequalification].id = a.id and  
	--[db_hr].[dtl_resumequalification].resumeid = a.resumeid
	-- insert new records
	insert into [db_hr].[dtl_resumequalification]  (resumeid,qualificationid,institute,passingyear,grades,remarks)
	select resumeid,qualificationid,institute,passingyear,grades,remarks from @resumequalification 
	where id not in (select id from [db_hr].[dtl_resumequalification]) and resumeid = @resumeid
	select * from [db_hr].[dtl_resumequalification] where resumeid = @resumeid
  END

GO
/****** Object:  StoredProcedure [db_hr].[pr_saveresumeuploadinfo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_hr].[pr_saveresumeuploadinfo]
    @statementtype nvarchar(50),
	@userid int=1,
	@filename VARCHAR(200),
    @resumeimageinfo VARCHAR(MAX)=NULL,
	@coid int,
	@boid int,
	@fyid INT,
	@resumeid BIGINT,
	@remarks VARCHAR(MAX)=NULL
  AS
 BEGIN 
 SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	DECLARE @error VARCHAR(100)
		If (@statementtype='Insert')
		BEGIN			
			-- INSERT Images
		  insert into [db_hr].[resume_images]
		  ([resumeid],[filename],[imageinfo],[isactive],[createdby],[createdon],remarks)
		  VALUES(@resumeid,@filename,@resumeimageinfo,1,@userid,getdate(),@remarks)
		  IF @@ERROR <> 0
			 BEGIN
			 -- Rollback the transaction
			 ROLLBACK
			 -- Raise an error and return
			 	RAISERROR ('Error ', 16, 1)
			 SET @error = 'Error no : ' + CAST(@@error AS VARCHAR(3))
			 RETURN @error 
			 END
	 END
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_savetrainingcalender]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [db_hr].[pr_savetrainingcalender] 
    @statementtype nvarchar(50),
	@training_tvp [db_hr].[hdr_training_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @id int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		    insert into [db_hr].[trg_hdr_calender] ([courserefno],[courseid],[coursedescription],[coursedatefrom],[coursedateto],[coursedays],
			[coursehours],[coursestarttime],[courseendtime],venuetype,venueid,coursestatusid,coursefacilities,facultytype,facultyid,
			coursemajorareaid,[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[trainingcost],[trainingbtchsize])
			Select [courserefno],[courseid],[coursedescription],[coursedatefrom],[coursedateto],[coursedays],
			[coursehours],[coursestarttime],[courseendtime],venuetype,venueid,coursestatusid,coursefacilities,facultytype,
			facultyid,coursemajorareaid,[createdby],GETDATE(),[modifiedby],[modifiedon],
			[coid],[boid],[trainingcost],[trainingbtchsize] from @training_tvp
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding training data.', 16, 1)
				RETURN
				END
				SELECT @id= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				end 
	 else
		 Begin -- begin of update .
			select @id = id from @training_tvp
			select [courserefno],[courseid],[coursedescription],[coursedatefrom],[coursedateto],[coursedays],
			[coursehours],[coursestarttime],[courseendtime],venuetype,venueid,coursestatusid,coursefacilities,facultytype,facultyid,
			coursemajorareaid,[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[trainingcost],[trainingbtchsize]
				from [db_hr].[trg_hdr_calender] where id = @id
				 EXCEPT select [courserefno],[courseid],[coursedescription],[coursedatefrom],[coursedateto],[coursedays],
			[coursehours],[coursestarttime],[courseendtime],venuetype,venueid,coursestatusid,coursefacilities,facultytype,facultyid,
			coursemajorareaid,[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[trainingcost],[trainingbtchsize]
				 from @training_tvp
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- updating existing records from Training Calender table and checking @@ERROR 
					UPDATE [db_hr].[trg_hdr_calender] set 
					          [courserefno]= a.[courserefno],
                              [courseid]=a.[courseid],
                              [coursedescription]=a.[coursedescription],
                              [coursedatefrom]=a.[coursedatefrom],
							  [coursedateto]=a.[coursedateto],
							  [coursedays]=a.[coursedays],
							  [coursehours]=a.[coursehours],
							  [coursestarttime]=a.[coursestarttime],
							  [courseendtime]=a.[courseendtime],
							  venuetype=a.venuetype,
							  venueid=a.venueid,
                              coursestatusid=a.coursestatusid,
                              coursefacilities=a.coursefacilities,
                              facultytype=a.facultytype,
                              [facultyid]=a.[facultyid],
                              [coursemajorareaid]=a.[coursemajorareaid],
                              [createdby]=a.[createdby],
                              [createdon]=a.[createdon],
                              [modifiedby]=a.[modifiedby],
                              [modifiedon]=getdate(),
							  [coid]=a.[coid],
							  [boid]=a.[boid],
							  [trainingcost] =a.[trainingcost],
							  [trainingbtchsize] = a.[trainingbtchsize]
					FROM   @training_tvp a
					WHERE  [db_hr].[trg_hdr_calender].id =a.id 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing training record.', 16, 1)
							RETURN
					   END
				END -- end of row count
			end
	COMMIT
END

GO
/****** Object:  StoredProcedure [db_hr].[pr_updateresumestatus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_hr].[pr_updateresumestatus]
    @statementtype nvarchar(50),
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1	,
	@resumeid bigint,
	@statusId int ,
	@remarks varchar(200),
	@dueon date=null
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	if (@statementtype='Insert')
	 BEGIN        
	       UPDATE [db_hr].[hdr_resume] set [statusid] = @statusId ,remarks=@remarks,dueon=@dueon where id=@resumeid
	 End
  END




GO
/****** Object:  StoredProcedure [db_hr].[prgetresumelist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [db_mktg].[pr_getresumelist] 1,200,1,1,'','hdr.id'

CREATE PROCEDURE [db_hr].[prgetresumelist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='hdr.id',
	@sortorder nvarchar(100)='desc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);

	begin
	set @sql= 'select hdr.id,cat.name as category ,res.name as source ,hdr.name as name ,hdr.currentlocation as location,'''' as contact,
	           hdr.totexpyy,hdr.currentsalary ,'''' qualification
               from [db_hr].[hdr_resume] hdr
               left join [db_hr].[mst_resumecategory] cat on hdr.postappliedfor = cat.id
               left join [db_hr].[mst_resumesources] res on hdr.sourceid = res.id 
               left join [db_hr].[mst_skillsets] sks on hdr.skillsetid = sks.id'
	set @sql += ' where hdr.coid = '+ cast(@coid as varchar(5)) +' and hdr.boid='+ cast(@boid as varchar(5))+''
	end
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''

	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End
	
	print @SQL
	 
	EXEC sp_executesql @SQL

	set @totalcount ='select count(hdr.id) records
        from [db_hr].[hdr_resume] hdr
        left join [db_hr].[mst_resumecategory] cat on hdr.postappliedfor = cat.id
        left join [db_hr].[mst_resumesources] res on hdr.sourceid = res.id 
        left join [db_hr].[mst_skillsets] sks on hdr.skillsetid = sks.id'

	print @totalcount

	EXEC sp_executesql @totalcount

END
GO
/****** Object:  StoredProcedure [db_masters].[pr_commonapi_Usermst]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all users>
--[db_masters].[pr_commonapi_Usermst] 1,1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_commonapi_Usermst] 
	@coid int = 1,
	@boid int = 1,
	@userid Int = 0
AS
BEGIN
	SET NOCOUNT ON;
	
	SELECT [userid],[firstname],[middlename],[lastname],[aliasname],[emailid],[username],[lastlogindate]
      ,[isactive],[departmentid],[usrpwd],[mobileno] mobile,[designationid],[mobileuser]
	  ,[shifttimein],[shifttimeout]  FROM [db_masters].[users] 
  where coid = @coid and boid = @boid
  order by username
	
	select id,deptname from [db_masters].[department] where coid=@coid and boid=@boid

	select id,designation from [db_masters].[designations] where coid=@coid and boid=@boid

	select boid,unitname from db_general.company_branches where coid = @coid and isactive=1

	SELECT [userid],[firstname],[middlename],[lastname] FROM [db_masters].[users] 
    where coid = @coid and boid = @boid and userid not in (select * from dbo.fngetchilduserids(@userid))

	if (@userid>0)
	begin
		select a.id, a.userid, a.boid, a.coid,a.isactive, isnull(a.reportingto,0) reportingto, isnull(a.roleid,0) roleid,
		u.firstname, u.lastname,u.username, b.unitname  from db_general.user_branches a 
		left join [db_masters].[users] u on isnull(a.reportingto,0) = u.userid 
		join db_general.company_branches b on a.boid = b.boid
		where a.userid = @userid

	end
END







GO
/****** Object:  StoredProcedure [db_masters].[pr_commonapiemployee]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all users>
-- [db_masters].[pr_commonapiemployee] 1,1,1,1
-- =============================================

CREATE PROCEDURE [db_masters].[pr_commonapiemployee]
	@coid int,
	@boid int ,
	@userid int,
	@fyid int = 1
AS
BEGIN
	SET NOCOUNT ON;
	select id,name as deptname from db_hr.mstDept where coid=@coid and boid=@boid
	-- select id,name as designation from  db_hr.mst_designation where coid=@coid and boid=@boid
	select id,name as designation from  db_hr.mst_resumecategory where coid=@coid and boid=@boid
	select id,name from [db_masters].[gender] 
	select id,name from db_masters.mst_maritalstatus
	select id,groupname from db_masters.bloodgroup
	select id,rhname from db_masters.hlth_rh
	select id,name from db_masters.healthinsuranceco
	select id,name FROM db_masters.powerusingglasses 
	select id,qualification from [db_hr].[mst_qualification]
	select id,name from db_masters.esidispensary
	select id,name from db_masters.bankmaster
	select id,name from db_masters.relation
	select id,splstatusname from db_masters.mst_empsplstatus
	select id,religionname from db_masters.religion
	select id,statename from db_masters.statemaster
	select id,name from db_masters.documenttype
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_commonapiletters]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [db_masters].[pr_commonapiletters] 1,1,1

CREATE PROCEDURE [db_masters].[pr_commonapiletters]
	@coid int=null,
	@boid int=null,
	@fyid int = null
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;

	select id,category as doctype from [db_masters].[document_category]

     --get buisnesssegment
	select id,deptname from db_masters.department

	--get document
	select id,deptid,subject from [db_masters].[document_subjects]

	select id,subjectid,title from [db_masters].[document_titles]
	    	
end	

GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllBank]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getAllBank] 1,1,0,100,'name'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllBank] 
    @coid int,
	@boid int,
	@PageNumber int= null,
	@PageSize int = null,
	@sort nvarchar(100)	= 'NAME'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select ID, NAME, ADDRESS1, ADDRESS2, CITY, STATE, PHONE, EMAIL, ACCOUNTID, ISACTIVE, IFSCCODE, ACNO, ACNAME, ISDEFAULT
 from [db_masters].[bankmaster] '
  
	set @sql +=' where coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3)) +''
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' asc '
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
	FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end

	--print @sql
	EXEC sp_executesql @SQL
	
	select count(ID) records from [db_masters].[bankmaster] 
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllCity]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getAllCity] 1,10,'cityname',1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllCity] 
    @coid int,
	@boid int,
	@PageNumber INT = null,
	@PageSize int = null,
	@sort nvarchar(100)= null,
	@countryid	int =null,
	@stateid int =null
As
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id, cityname
				from [db_masters].[city]  where isactive=1 and Countryid =  '+ cast(@countryid as varchar(3)) +' and stateid='+cast(@stateid as varchar(3)) +' and coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3))
	
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
	FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end

	--print @sql
	EXEC sp_executesql @SQL
	
	set @sql= 'select count(id) records from [db_masters].[city]  where isactive=1 and 
	Countryid =  '+ cast(@countryid as varchar(3)) +' and stateid='+cast(@stateid as varchar(3))

	EXEC sp_executesql @SQL
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllCountry]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[db_masters].[pr_getAllCountry] 1,1,10,1,'countryname','asc'

CREATE PROCEDURE [db_masters].[pr_getAllCountry] 

	@coid int = 1,



	@boid int = 1,



	@PageNumber INT=NULL,



	@PageSize INT=NULL,



	@sort nvarchar(100)='countryname',



	@sortorder nvarchar(100)='asc'



AS



BEGIN



	SET NOCOUNT ON;



	declare @sql nvarchar(max);


	set @sql= 'select id,countryname,code,currency_preference from [db_masters].[Country]'



	set @sql +=' where coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3)) +''



	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '



	if(isnull(@PageNumber,0)>0)



	begin



	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS



	FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'



	end



    







	print @sql



	EXEC sp_executesql @SQL



	



	select count(id) records from [db_masters].[Country] 



END
GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllCurrencies]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getAllCurrencies] 1,1,1,100,'name'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllCurrencies] 
    @coid int,
	@boid int
As
BEGIN
	SET NOCOUNT ON;

	
	select id, code,name,conversionfactor 
				from [db_masters].[Currency] where coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllCustomerCategoryList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get list of all customer categories>
--[db_masters].[pr_getAllCustomerCategoryList] 1,1,1,10,'categoryname',1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllCustomerCategoryList] 
	@coid Int = NULL,
	@boid Int=NULL,
	@PageNumber INT=1,
	@PageSize INT=20,
	@sort nvarchar(100)='categoryname'
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	select id, categoryname from db_masters.customer_category where  coid =  @coid and
	  boid = @boid 
	

	
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllCustomerList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_masters].[pr_getAllCustomerList] 1,20,'name',1,1,'asc',0,'',1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllCustomerList] 
	@PageNumber INT,
	@PageSize INT ,
	@sort nvarchar(100) = 'id',
	@coid int= 1,
	@boid int =1,
	@sortorder nvarchar(100)='desc',
	@customerid int  = null,
	@search varchar(50)='',
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql= 'SELECT c.[id],c.name,cc.categoryname as categoryname,[gsTin],[pan],[address1],[address2],[cityname] city
      ,[statename] state,[countryname] country,[pin],[mobile_number] as mobile,[phone_number] as phone,[fax],[email],[website],[tds_applicable] tdsapplicable,[tds_rate] as tdsrate,
	  [tcs_applicable] tscapplicable,[tcs_rate] tscrate  ,c.state stateid ,cu.code currency 
	from [db_masters].[customer] c
	left join [db_masters].[customer_category] cc on c.categoryid=cc.id 
	left join [db_masters].[country] co on c.country = co.id 
	left join [db_masters].[statemaster] s on c.state = s.id 
	left join [db_masters].[city] ci on c.city = ci.id 
	left join [db_masters].[currency] cu on  c.currency_preference=cu.name '
	-- where c.createdby in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' )) '
	set @sql += ' where c.coid = ' + cast(@coid as varchar(5)) + ' and c.boid = ' + cast(@boid as varchar(5))
	if (@customerid <>0)
		begin
		set @sql+=' and c.id =  '+  cast(@customerid as varchar(5)) +'' 
		end
		if(@search!='')
		begin
		 set @sql += ' and c.name like '+'''%'+cast(@search as varchar(50)) + '%'' or c.mobile_number like '+'''%'+cast(@search as varchar(50)) + '%'' 
		 or ci.cityname like '+'''%'+cast(@search as varchar(50)) + '%'' or c.gsTin like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL
	set @sql='select count(c.[id])records from [db_masters].[customer] c
	join [db_masters].[customer_category] cc on c.categoryid=cc.id 
	join [db_masters].[country] co on c.country = co.id 
	join [db_masters].[statemaster] s on c.state = s.id 
	join [db_masters].[city] ci on c.city = ci.id 
	where c.coid = ' + cast(@coid as varchar(2)) +'  and c.boid ='+ cast(@boid as varchar(2)) +''
	if(@search!='')
		begin
		 set @sql += ' and c.name like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	EXEC sp_executesql @SQL
END


GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllmst_machineList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all machine master>
-- [db_masters].[pr_getAllmst_machineList] 1,100,1,1,0,'punjab'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllmst_machineList] 
	@PageNumber INT=1,
	@PageSize INT=100,
	@coid int = 1,
	@boid int = 1,
	
	@id Int = NULL,
	@search varchar(50)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	--(name +'' ''+ isnull(address1,'' '') +'' ''+  isnull(address2,'' '')+'' ''+ isnull(cityname,'' '') )

	set @sql= 'SELECT mc.[id],mc.MachineName as MachineName,[MCCatgId],mcc.[MCCatgName],[MCSRNo],[MCChassisNo],[MCModel],[MCCapacity],[MCSupplierId],[MCManufacturer],[MaintBy],[MainSupplierId],[UnderWty],[Wtyupto],[UnderAMC],[AMCFrom],[AMCUpto],[EmergencyContactNo],[LastMaint],[LMAfterOps],[LastBDownMaint],[BMAfterOps],[NextMaint],[NMAfterOps],[SplTools],[SplTeam],[ProjLifeYY],[ProjLifeMM],[ProjLifeOps],[ActualLifeYY],[ActualLifeMM],[ActualLifeOps],mc.[coid],mc.[boid],mc.[createdby],mc.[createdon],mc.[modifiedby],mc.[modifiedon]  
	from [db_masters].[mst_machine] mc 
	join [db_masters].[machinecategory] mcc on mc.MCCatgId=mcc.id  '
	set @sql += ' where mc.coid = ' + cast(@coid as varchar(5)) + ' and mc.boid = ' + cast(@boid as varchar(5))
	
	if (@id <>0)
		begin
		set @sql+=' and mc.id =  '+  cast(@id as varchar(5)) +'' 
		PRINT @sql
		end
	if(@search!='')
		begin
		 set @sql += ' and mc.MachineName like '+'''%'+cast(@search as varchar(50)) 
		end
		if(@sort!='' and @sortorder!='')
		begin
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		end
	
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql='select count(mc.[id])records from [db_masters].[mst_machine] mc
	where mc.coid = ' + cast(@coid as varchar(2)) +'  and mc.boid ='+ cast(@boid as varchar(2)) +''
		if(@search!='')
		begin
		
		 set @sql += ' and mc.MachineName like '+'''%'+cast(@search as varchar(50)) 
		 end
    EXEC sp_executesql @SQL
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllprospectList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_masters].[pr_getAllprospectList] 1,20,'name',1,1,'asc',0,'',3
-- =============================================

CREATE PROCEDURE [db_masters].[pr_getAllprospectList] 
	@PageNumber INT,
	@PageSize INT ,
	@sort nvarchar(100) = 'id',
	@coid int= 1,
	@boid int =1,
	@sortorder nvarchar(100)='desc',
	@customerid int  = null,
	@search varchar(50)='',
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql= 'SELECT c.[id],name,cc.categoryname as categoryname,[gsTin],[pan],[address1],[address2],[cityname] city
      ,[statename] state,[countryname] country,[pin],[mobile_number] as mobile,[phone_number] as phone,[fax],[email],[website],[tds_applicable] tdsapplicable,[tds_rate] as tdsrate,
	  [tcs_applicable] tscapplicable,[tcs_rate] tscrate  ,gstin 
     from [db_masters].prospectcustomers c
	LEFT join [db_masters].[customer_category] cc on c.categoryid=cc.id 
	left join [db_masters].[country] co on c.country = co.id 
	left join [db_masters].[statemaster] s on c.state = s.id 
	left join [db_masters].[city] ci on c.city = ci.id '
    -- where c.createdby in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))'
	set @sql += ' where c.custid is null and  c.coid = ' + cast(@coid as varchar(5)) + ' and c.boid = ' + cast(@boid as varchar(5))
	if (@customerid <>0)
		begin
		set @sql+=' and c.id =  '+  cast(@customerid as varchar(5)) +'' 
		end
		if(@search!='')
		begin
		 set @sql += ' and c.name like '+'''%'+cast(@search as varchar(50)) + '%''  or ci.cityname like '+'''%'+cast(@search as varchar(50)) + '%''
		  or c.mobile_number like '+'''%'+cast(@search as varchar(50)) + '%'' or c.gstin like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL
	--select ROWCOUNT_BIG() as records 
	set @sql='select count(c.[id])records from [db_masters].prospectcustomers c
	join [db_masters].[customer_category] cc on c.categoryid=cc.id 
	join [db_masters].[country] co on c.country = co.id 
	join [db_masters].[statemaster] s on c.state = s.id 
	join [db_masters].[city] ci on c.city = ci.id 
	where c.coid = ' + cast(@coid as varchar(2)) +'  and c.boid ='+ cast(@boid as varchar(2)) +'  and c.createdby ='+ cast(@userid as varchar(2)) +''
	if(@search!='')
		begin
		 set @sql += ' and c.name like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
	EXEC sp_executesql @SQL
END


GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllSupliersCategoryList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getAllSupliersCategoryList] 1,1,0,0,'categoryname',1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllSupliersCategoryList] 
	@coid INT,
	@boid INT,
	@PageNumber INT=1,
	@PageSize INT=10,
	@sort nvarchar(100) = 'categoryname'
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id, categoryname from db_masters.supplier_category 	where 
	coid =  '+  cast(@coid as varchar(5)) + ' and  boid =  '+  cast(@boid as varchar(5))  
	
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' asc'
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end 
	
	--print @sql
	EXEC sp_executesql @SQL
	
	select count(id)records from db_masters.supplier_category 	where coid = @coid and boid =@boid
END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllSupliersList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_masters].[pr_getAllSupliersList] 1,20,1,1,0,'pun','',''
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllSupliersList] 
	@PageNumber INT=1,
	@PageSize INT=100,
	@coid int = 1,
	@boid int = 1,	
	@supplierid Int = 0,
	@search varchar(50)='',
	@sort varchar(100)=null,
	@sortorder varchar(100)=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	--(name +'' ''+ isnull(address1,'' '') +'' ''+  isnull(address2,'' '')+'' ''+ isnull(cityname,'' '') )

	set @sql= 'SELECT sp.[id],name,spc.categoryname as categoryname,[gsTin],[pan],[address1],[address2],[cityname] city
      ,[statename] state,[countryname] country,[pin],[mobile_number] as mobile,[phone_number] as phone,[fax],[email],[website],[tds_applicable] tdsapplicable,[tds_rate] as tdsrate,
	  [tcs_applicable] tscapplicable,[tcs_rate] tscrate  
	from [db_masters].[supplier] sp 
	join [db_masters].[supplier_category] spc on sp.categoryid=spc.id 
	join [db_masters].[country] co on sp.country = co.id 
	join [db_masters].[statemaster] s on sp.state = s.id 
	join [db_masters].[city] c on sp.city = c.id '
	set @sql += ' where sp.coid = ' + cast(@coid as varchar(5)) + ' and sp.boid = ' + cast(@boid as varchar(5))
	
	if (@supplierid <>0)
		begin
		set @sql+=' and sp.id =  '+  cast(@supplierid as varchar(5)) +'' 
		PRINT @sql
		end
	if(@search!='')
		begin
		 set @sql += ' and sp.name like '+'''%'+cast(@search as varchar(50)) + '%'' 
		 or sp.address1 like '+'''%'+cast(@search as varchar(50)) + '%'' or sp.address2 like '+'''%'+cast(@search as varchar(50)) + '%'' 
		 or sp.mobile_number like '+'''%'+cast(@search as varchar(50)) + '%''  
		 or c.cityname like '+'''%'+cast(@search as varchar(50)) + '%'' or sp.gsTin like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
		if(@sort!='' and @sortorder!='' and @sort is not null and @sortorder is not null)
		begin
		set @sql +=' order by ' + cast(ltrim(@sort) as varchar(100)) + ' ' + @sortorder + ' '
		end
		else
	begin
		set @sql +=' order by name '
		end
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql='select count(sp.[id])records from [db_masters].[supplier] sp 
	join [db_masters].[supplier_category] spc on sp.categoryid=spc.id 
	join [db_masters].[country] co on sp.country = co.id 
	join [db_masters].[statemaster] s on sp.state = s.id 
	join [db_masters].[city] c on sp.city = c.id 
	where sp.coid = ' + cast(@coid as varchar(2)) +'  and sp.boid ='+ cast(@boid as varchar(2)) +''
		if(@search!='')
		begin
		
		 set @sql += ' and sp.name like '+'''%'+cast(@search as varchar(50)) + '%'' or sp.mobile_number like '+'''%'+cast(@search as varchar(50)) + '%'' 
		 or c.cityname like '+'''%'+cast(@search as varchar(50)) + '%'' or sp.gsTin like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
    EXEC sp_executesql @SQL
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getAllUsers]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all users>
--[db_masters].[pr_getAllUsers] 1,100,1,1,'firstname','asc',0,''
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAllUsers] 
	@PageNumber INT=1,
	@PageSize INT=100,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='firstname',
	@sortorder nvarchar(100)='asc',
	@userid Int = NULL,
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql= 'SELECT [userid]
      ,[firstname]
      ,[middlename]
      ,[lastname]
      ,[aliasname]
      ,[emailid]
      ,[username]
      ,[lastlogindate]
      ,[db_masters].[users].[isactive]
      ,[departmentid]
	,[usrpwd]
	,[mobileno] mobile
	  ,[designationid]
	  ,[db_masters].[designations].[designation]
	  ,[deptname]
	  ,[mobileuser]
	  ,[db_masters].[users].[coid]
	  ,[db_masters].[users].[boid]
	  ,[db_masters].[users].[shifttimein]
	,[db_masters].[users].[shifttimeout]
  FROM [db_masters].[users] 
  left join [db_masters].[department] on [db_masters].[users].departmentid = [db_masters].[department].id
 left  join [db_masters].[designations] on [db_masters].[users].designationid = [db_masters].[designations].id
  where [db_masters].[users].coid = ' + cast(@coid as varchar(5)) + ' and [db_masters].[users].boid = ' + cast(@boid as varchar(5))
  
	if (@userid <>0)
		begin
		set @sql+=' and [db_masters].[users].userid =  '+  cast(@userid as varchar(5)) +'' 
		end
	if(@search!='')
		begin
		 set @sql += ' and ([db_masters].[users].firstname like '+ '''%' + cast(@search as varchar(50)) + '%'' or  
							[db_masters].[users].lastname like '+ '''%' + cast(@search as varchar(50)) + '%'' or 
							[db_masters].[users].middlename like '+ '''%' + cast(@search as varchar(50)) + '%'' or 
							[db_masters].[users].username like '+ '''%' + cast(@search as varchar(50)) + '%'')'
		end
	
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	if(isnull(@PageNumber,0)>0)
		begin
			set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
			FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
		end
	print @sql
	EXEC sp_executesql @sql
	
	set @sql='select count(userid)records from [db_masters].[users] 
	where [db_masters].[users].coid = ' + cast(@coid as varchar(5)) + ' and [db_masters].[users].boid = ' + cast(@boid as varchar(5))
	if (@userid <>0)
		begin
		set @sql+=' and [db_masters].[users].userid =  '+  cast(@userid as varchar(5)) +'' 
		end
	if(@search!='')
		begin
		 set @sql += ' and ([db_masters].[users].firstname like '+ '''%' + cast(@search as varchar(50)) + '%'' or  
							[db_masters].[users].lastname like '+ '''%' + cast(@search as varchar(50)) + '%'' or 
							[db_masters].[users].middlename like '+ '''%' + cast(@search as varchar(50)) + '%'' or 
							[db_masters].[users].username like '+ '''%' + cast(@search as varchar(50)) + '%'')'
		end
	print @sql
	EXEC sp_executesql @sql


	select id,deptname from [db_masters].[department] where coid=@coid and boid=@boid
	select id,designation from [db_masters].[designations] where coid=@coid and boid=@boid
END







GO
/****** Object:  StoredProcedure [db_masters].[pr_getAreaList]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getAreaList]1,1,1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getAreaList] 
    @coid int,
	@boid int,
	@zoneid int =null,
	@regionid int =null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
  -- set @sql= 'select id,areaname from [db_masters].[areamaster] where  zoneid='+cast(@zoneid as varchar(3)) +' and regionid='+cast(@regionid as varchar(3))
	

	--set @sql +=' order by ' + cast(@sort as varchar(100)) + ' asc
	--OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    --FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	
	--EXEC sp_executesql @SQL
	select id, areaname  from db_masters.areamaster where zoneid = coalesce(@zoneid,zoneid) and regionid = coalesce(@regionid,regionid) and coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	
	END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getbomitems]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
-- [db_masters].[pr_getbomitems] 1,1,I
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getbomitems] 
	@coid int = 1,
	@boid int = 1,
	@itemtype varchar(1)='I',
	@search varchar(100)=null
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#itemcategories') IS NOT NULL DROP TABLE #itemcategories
	create table #itemcategories 
	(
		id int,
		parentid int,
		slevel int
	);

	declare @packingid varchar(50);
	-- select packing material categories

	select @packingid=packmatcategoryid from db_general.company_control where coid =@coid and boid=@boid;

	WITH x AS
	(
		-- anchor:
		SELECT ID, parentid, [level] = 0 
		FROM db_mm.mst_itemcategory WHERE id in (select * from dbo.fnSplitString(@packingid,','))
		UNION ALL
		-- recursive:
		SELECT t.ID, t.parentid ,[level] = x.[level] + 1 
		FROM x INNER JOIN db_mm.mst_itemcategory  AS t
		ON t.parentid = x.ID 
	
	)
	insert into #itemcategories (id,parentid,slevel) select id, parentid,level from x ORDER BY [level];
	

	IF OBJECT_ID('tempdb..#itemmaster') IS NOT NULL DROP TABLE #itemmaster

	create table #itemmaster(
		id				bigint,
		itemcategoryid	int,
		itemname		varchar(200),
		itemcategory	varchar(200),
		itemcode		varchar(25),
		oldcode			varchar(25),
		specialcode		varchar(25),
		receivingunitid	int,
		receivingunit	varchar(50),
		issuingunitid	int,
		issuingunit		varchar(50),
		eoq				decimal(15,3),
		gstid			int,
		hsncode			varchar(10),
		igst			decimal(5,2),
		sgst			decimal(5,2),
		cgst			decimal(5,2)
	) 

	
	-- insert items into temp table
	insert into #itemmaster (id,itemcategoryid,itemname,itemcode,oldcode,specialcode,receivingunitid,issuingunitid,eoq,
	gstid)
	select im.id,itemcategoryid,itemname,itemcode,oldcode,specialcode,receivingunitid,issuingunitid,eoq,im.gstid 
	from db_mm.mst_item im 
	where itemname like isnull(@search,itemname) + '%' and (itemcode like  isnull(@search,itemcode) + '%' or 
	oldcode like  isnull(@search,oldcode) + '%' or specialcode like  isnull(@search,specialcode) + '%') 
	and ((@itemtype = 'I' and im.itemcategoryid not in (select id from #itemcategories))  or 
	(@itemtype = 'P' and im.itemcategoryid in (select id from #itemcategories)) )

	-- update receiving unit 
	update #itemmaster set receivingunit = um.uom 
	from db_mm.mst_itemuom um where #itemmaster.receivingunitid = um.id 
	-- update issuing unit 
	update #itemmaster set issuingunit = um.uom 
	from db_mm.mst_itemuom um where #itemmaster.issuingunitid = um.id 

	-- update gst detail 
	update #itemmaster set hsncode = g.hsncode, igst = g.igst, sgst = g.sgst, cgst= g.cgst
	from [db_mm].[mst_gst] g where #itemmaster.gstid=g.gstid

	--update item category
	update #itemmaster set itemcategory = ic.name
	from [db_mm].[mst_itemcategory] ic where #itemmaster.itemcategoryid= ic.id

	select * from #itemmaster; 
	DROP TABLE #itemcategories;
	DROP TABLE #itemmaster;
END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getbusinesssegment]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getbusinesssegment] 1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getbusinesssegment] 
    @coid int,
	@boid int
As
BEGIN
	SET NOCOUNT ON;
	
	select id,businesssegementname name
				from [db_masters].[businesssegement] 
	where coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5)) and parentid=0
	
END


GO
/****** Object:  StoredProcedure [db_masters].[pr_getbusinesssegmentlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
-- [db_masters].[pr_getbusinesssegmentlist]  1,1,null,10032

CREATE PROCEDURE [db_masters].[pr_getbusinesssegmentlist] 
@coid int,
@userid int = null,
@segmentid int=null,
@enquiryid int= 0
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#tempbsegmentlist') IS NOT NULL DROP TABLE #tempbsegmentlist
create table #tempbsegmentlist (
id int,
name varchar(100),
parentid int,
level int,
value decimal(13,2),
parentname varchar(100),
selected bit default 0
);


WITH x AS
(
-- anchor:
SELECT ID, businesssegementname,parentid, [level] = 0  
FROM db_masters.businesssegement WHERE isnull(parentid,0)=0 and id=coalesce(@segmentid,id) 
UNION ALL
-- recursive:
SELECT t.ID, t.businesssegementname,t.parentid,[level] = x.[level] + 1 
FROM x INNER JOIN db_masters.businesssegement AS t ON t.parentid = x.ID
--left join db_masters.businesssegement t1 on t.parentid = x.id
)
insert into #tempbsegmentlist (id,name,parentid,level,value,parentname,selected)
SELECT x.id, x.businesssegementname name, x.parentid, [level], 0 as value,t.businesssegementname as parentname, 0
FROM x  
left join db_masters.businesssegement t on x.parentid =t.id
ORDER BY id,[level],name
OPTION (MAXRECURSION 100);

if (@enquiryid > 0)
begin
update #tempbsegmentlist set value = isnull(dt.qty,0) , selected = 1 
from  db_mktg.dtl_bsegmt_enq dt where #tempbsegmentlist.id = dt.bsegmtid and dt.enqid=@enquiryid
 declare @minlvl int, @maxlvl int;
select @maxlvl = max([level]),@minlvl=min(level) from #tempbsegmentlist;
WAY: -- loop to update balance in result table
		update #tempbsegmentlist set selected = 1 
		from (select parentid, selected from #tempbsegmentlist where level=@maxlvl and selected =1) a 
		where #tempbsegmentlist.id = a.parentid and #tempbsegmentlist.level = @maxlvl-1;
		set @maxlvl -=1;
	IF NOT(@minlvl = @maxlvl) GOTO WAY;

end


select id,name,parentid,level,value,parentname,case when selected =0 then 'false' else 'true' end selected from #tempbsegmentlist;
END





GO
/****** Object:  StoredProcedure [db_masters].[pr_Getcommonapiformachinemaster]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_masters].[pr_Getcommonapiformachinemaster]
	@coid int=1,
	@boid int=1,
	@userid Int = 0
AS
BEGIN 
   
   SET NOCOUNT ON;

   select isnull(max(id),0) as LastMcId from [db_masters].[mst_machine] 

    --get machine category information
	Select id,MCCatgName,isactive 
	from [db_masters].[machinecategory] where coid=@coid and boid=@boid

END

GO
/****** Object:  StoredProcedure [db_masters].[pr_Getcommonapiformachinemasterjobcard]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create PROCEDURE [db_masters].[pr_Getcommonapiformachinemasterjobcard]
	@coid int=1,
	@boid int=1,
	@userid Int = 0
AS
BEGIN 
   
   SET NOCOUNT ON;

    --get machine master information
	Select id,MachineName
	from [db_masters].[mst_machine] where coid=@coid and boid=@boid

END

GO
/****** Object:  StoredProcedure [db_masters].[pr_Getcommonapiformakeandmodel]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_masters].[pr_Getcommonapiformakeandmodel]
	@coid int=1,
	@boid int=1,
	@fyid int=1
AS
BEGIN 
   
   select * from [db_masters].[Make]

   select * from [db_masters].[Model]

END

GO
/****** Object:  StoredProcedure [db_masters].[pr_getcustomerData]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
-- [db_masters].[pr_getcustomerData] 1,1,6837
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getcustomerData] 
@coid int = 1,
@boid int = 1,
@custid bigint
AS
BEGIN
	SET NOCOUNT ON;
	DECLARE  @PageNumber INT =1,@PageSize INT =100,@sort nvarchar(100)= 'boid',@sortorder nvarchar(100)= 'asc'
	-- get supplier's general information
	SELECT c.[id],c.[coid],c.[boid],c.[name],c.[categoryid],c.[segmentid],[businesssegementname],c.[gsTin],c.[pan],c.[address1],c.[address2],c.[city],c.[state]
     ,c.[country],c.[pin],c.[mobile_number],c.[phone_number],c.[fax],c.[email],c.[website],c.[tds_applicable],c.[tds_rate],c.[tcs_applicable]
     ,c.[tcs_rate],c.[isactive],c.[createdby],c.[createdon],c.[modifiedby],c.[modifiedon],c.[deactivatedby],c.[deactivatedon],
      COALESCE(c.credit_days,0) as credit_days,COALESCE(c.credit_limit,0) as credit_limit,c.[currency_preference],p.[name] as currencyname,
	  COALESCE(c.zone,0) as zone,[zonename],c.[area],[areaname],c.[region],[regionname],c.[title],c.[vendorcode],
	  c.excise_commissionerate,c.excise_division,c.excise_range,c.vat_number,c.vat_date,c.excise_regn_number,c.iecno,c.eximcode,isnull(c.associateacid,0) associateacid,
	  case when c.associateacid>0 then (select name+' '+isnull(address1,'')+' '+isnull(address2,'') from [db_masters].[customer] where id=c.associateacid ) else '' end associateacname
	,case when c.associateacid>0 then 1 else 0 end isassociate
	from [db_masters].[customer] c 
	left join [db_masters].[regionmaster] r on c.region=r.id
	left join [db_masters].[zonemaster] z on c.zone=z.id
	left join [db_masters].[areamaster] a on c.area=a.id
	left join [db_masters].[businesssegement] b on c.segmentid=b.id
	left join [db_masters].[Currency] p on c.currency_preference = p.name
	where c.id = @custid and c.coid= @coid and c.boid=@boid  
	--- get supplier's bank account info
	--select [id],custid,[bankname],[bankacno],[ifsc],[isactive] 
	--FROM [db_general].[customer_banks]
	--where custid = @custid
	 select cust.[id],cust.custid,cust.bankid,b.name AS bankname,
	 cust.[bankacno],cust.[ifsc],cust.[isactive] 
	FROM [db_general].[customer_banks] cust
	LEFT JOIN db_masters.bankmaster b  ON cust.bankid = b.id
  	where cust.custid = @custid
	-- get supplier's contacts information
	SELECT [id],custid,[name],[mobile],[phone],[fax],[email],[website],[isactive],position
	FROM [db_general].[customer_contactpersons]
	where custid = @custid
	-- get supplier's license information
	SELECT [id],custid,[licensetype],[licenseno],[validtill],[authentication],[isactive]
    FROM [db_general].[customer_licenseinfo] where custid = @custid
	Exec  [db_masters].pr_getAllBank @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].pr_getAllCountry @coid,@boid,@PageNumber,@PageSize,@sort,@sortorder
	Exec  [db_masters].pr_getAllCurrencies @coid,@boid
	Exec  [db_masters].[pr_getZoneList]  @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].[pr_getAllCustomerCategoryList]  @coid,@boid,@PageNumber,@PageSize,@sort
	Exec  [db_masters].[pr_getbusinesssegment] @coid,@boid	
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_getDepartments]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all departments>
--[db_masters].[pr_getDepartments]  1,'adfafda',1,100,1,1,'deptname','asc'
-- =============================================
create PROCEDURE [db_masters].[pr_getDepartments] 
	@userid int,
	@accesstoken varchar(100),
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='deptname',
	@sortorder nvarchar(100)='asc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id,deptname from [db_masters].[department] '
	set @sql +=' where coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3)) +''
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
	FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
    

	print @sql
	EXEC sp_executesql @SQL
	
	select count(id)records from [db_masters].[department]
END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getDesignation]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,,mohit>
-- Create date: <Create Date,2/26/2019>
-- Description:	<Description,Get list of all Designation>
--[db_masters].[pr_getDesignation]  1,'adfafda',1,100,1,1,'designation','asc'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getDesignation] 
	@userid int,
	@accesstoken varchar(100),
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='designation',
	@sortorder nvarchar(100)='asc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id,designation from [db_masters].[designations] '
	set @sql +=' where coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3)) +''
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
	FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
    

	print @sql
	EXEC sp_executesql @SQL	
	select count(id)records from [db_masters].[designations]

END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getemployeedata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
-- exec [db_masters].[pr_getemployeedata]  1,1,1,1,9
-- ========================================

CREATE PROCEDURE [db_masters].[pr_getemployeedata] 
	@coid int,
	@boid int,
	@userid bigint,
	@fyid int,
	@empid bigint
AS
BEGIN
SET NOCOUNT ON;   

     -- select 'Mr.' title ,empname employeename,empno employeeno,'developer' designation,'NCCMS' companyName,'2019-01-01' joindate from db_masters.employee

     select * from db_masters.employee where id=@empid

	 select * from db_masters.emp_healthcard where empid=@empid

	 select dtlid.splstatusid as id,stid.splstatusname splstatusname 
	 from db_masters.emp_splstatus dtlid
	 left  join db_masters.mst_empsplstatus stid on dtlid.splstatusid = stid.id
	 where dtlid.empid=@empid 

	 select mstedu.id,mstedu.qualification,empedu.qualificationid,empedu.institute,empedu.passingyear,empedu.grades,empedu.remarks

	 from db_masters.empeducation empedu
	 left join [db_hr].[mst_qualification] mstedu on empedu.qualificationid = mstedu.id
	 where empid=@empid

	 select expr.id,dpt.name as deptname,expr.empid,expr.organization,expr.totexpyy,expr.totexpmm,expr.relevantexpyy,expr.relevantexpmm,
	 expr.positionheld,expr.reportingto,expr.remarks,expr.expfrom,expr.expto,expr.deptid
	 from db_masters.empexperience expr 
	 left join db_hr.mstDept dpt on expr.deptid=dpt.id 
	 where empid=@empid

	 select emprel.id, emprel.empid,emprel.name,gen.name as gender,emprel.genderid,emprel.dob as dependant_dob,
	 emprel.bloodgroup as dependant_bloodgroup,bg.groupname,
	 emprel.relationid,rel.name as relation
	 from db_masters.emp_relations emprel
	 left join db_masters.relation rel on emprel.relationid = rel.id
	 left join db_masters.gender gen on emprel.genderid = gen.id
	 left join db_masters.bloodgroup bg on emprel.bloodgroup=bg.id
	 where empid = @empid 
	  
	 select id,empid,name,organization,contactno,email from db_masters.emp_referals where empid = @empid

	 -----------commonapi----------
	 select id,name as deptname from db_hr.mstDept where coid=@coid and boid=@boid
	 -- select id,name as designation from db_hr.mst_designation where coid=@coid and boid=@boid
	 select id,name as designation from  db_hr.mst_resumecategory where coid=@coid and boid=@boid
	 select id,name from [db_masters].[gender] 
	 select id,name from db_masters.mst_maritalstatus
	 select id,groupname from db_masters.bloodgroup
	 select id,rhname from db_masters.hlth_rh
	 select id,name from db_masters.healthinsuranceco
	 select id,name FROM db_masters.powerusingglasses 
	 select id,qualification from [db_hr].[mst_qualification]
	 select id,name from db_masters.esidispensary
	 select id,name from db_masters.bankmaster
	 select id,name from db_masters.relation
	 select id,splstatusname from db_masters.mst_empsplstatus
	 select id,religionname from db_masters.religion
	 select id,statename from db_masters.statemaster
	 select id,name from db_masters.documenttype
 end

GO
/****** Object:  StoredProcedure [db_masters].[pr_getemployeelist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_masters].[pr_getemployeelist] 1,100,1,1,'emp.id','desc','',1

CREATE PROCEDURE [db_masters].[pr_getemployeelist]
	@PageNumber int=1,
	@PageSize int=100,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='emp.id',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql= 'Select emp.id as empid, emp.empname,des.name as designation,dept.deptname,emp.doj date_of_joining,emp.mobile_no
               from db_masters.employee emp
               left join db_hr.mst_resumecategory des on emp.designationid = des.id
               left join db_masters.department dept on emp.deptid = dept.id'
    if(@search <>'')
	begin
	set @sql += ' where emp.empname like '+'''%'+cast(@search as varchar(50)) + '%'' or des.designation like '+'''%'+cast(@search as varchar(50)) + '%'' 
	              or dept.deptname like '+'''%'+cast(@search as varchar(50)) + '%'' or emp.mobile_no like '+'''%'+cast(@search as varchar(50)) + '%'''	          
   
	end 
	set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''
	if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
     FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	End


	print @sql
	EXEC sp_executesql @sql
	set @sql='select count(id)records from db_masters.employee'
	print @sql
	EXEC sp_executesql @sql
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_geterpmodules]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
-- Description:	<Description,Get user rights>
--[db_masters].[pr_geterpmodules] 1,1
CREATE PROCEDURE [db_masters].[pr_geterpmodules] 
@coid int,
@boid int
AS
BEGIN
	SET NOCOUNT ON;
		Begin
		 select m.id,m.modulename from db_masters.erp_modules m join db_general.branch_modules bm on m.id = bm.moduleid where m.isactive=1 and bm.coid = @coid and bm.boid = @boid
		end
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_getgstlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
-- [db_masters].[pr_getgstlist] 1,10,1,1,'','asc'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getgstlist] 
	
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT,
	@PageSize INT,
	@sort nvarchar(100)='hsncode',
	@sortorder nvarchar(100)='asc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [description],[hsncode],[igst],[sgst],[cgst],h.[createdby],u.username,gstid,[concessionaligst],[concessionalcgst],[concessionalsgst] from [db_mm].[mst_gst] h
	join [db_masters].[users] u on h.createdby = u.userid '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL

	 select count(h.[gstid])records from [db_mm].[mst_gst] h
	join [db_masters].[users] u on h.createdby = u.userid 
				
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_gethsnlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_masters].[pr_gethsnlist] 1,1,1,100,'hsncode','asc',''
-- =============================================
CREATE PROCEDURE [db_masters].[pr_gethsnlist] 
	
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT,
	@PageSize INT,
	@sort nvarchar(100)='hsncode',
	@sortorder nvarchar(100)='asc',
	@search nvarchar(100)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select h.id, h.hsncode,  g.[igst],g.[sgst],g.[cgst],g.description
FROM         [db_mm].[mst_gst] g join     db_mm.mst_hsn h on g.gstid=h.gstid'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if (isnull(@search,'') != '')
		begin
			set @sql += ' and h.hsncode like ''%' + @search + '%'''
		end
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '

		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	 set @sql = 'select count(h.gstid) records from 
	 [db_mm].[mst_hsn] h join db_mm.mst_gst g on h.gstid = g.gstid where h.coid =' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
	 if (isnull(@search,'') !='')
		begin
			set @sql += ' and h.hsncode like ''%' + @search + '%'''
		end
	print @sql
	EXEC sp_executesql @sql			
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getitembrands]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getitembrands] 1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitembrands] 
@coid int,
@boid int
AS
BEGIN

	select id,name brandname  from [db_mm].[mst_brand] where coid  =  cast(@coid as varchar(5))   and boid =   cast(@boid as varchar(5)) 
	
	END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getitemcategorylist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:	<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getitemcategorylist] 1,1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitemcategorylist] 
@coid int,
@userid int = null,
@categoryid int=null
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
