create table #tree 
(
ID INT,
name VARCHAR(100),
parentgroupid INT,
code varchar(20), 
categcode varchar(20),
maxitemid bigint,
lastitemcode varchar(15)
);

INSERT into #tree (id,name,parentgroupid,code) 
SELECT a.id,a.name, a.parentid,a.categorycode
from db_mm.mst_itemcategory a where a.coid=@coid
-- and id in (select itemcategoryid from db_mm.[itemcategories_userrights] where userid = coalesce(@userid,userid))

-- update maxitemid for the category
update #tree set maxitemid = a.itemid 
from 
(select itemcategoryid, max(id) itemid from db_mm.mst_item group by itemcategoryid) a 
where #tree.ID = a.itemcategoryid;

-- update lastitemcode for the category
update #tree set lastitemcode = a.itemcode 
from 
db_mm.mst_item a 
where #tree.maxitemid = a.id;

WITH x AS
(
-- anchor:
SELECT ID, name, parentgroupid, code,
cast(left(isnull(code,'XX'),2) + 'XXXX' as varchar(6)) as categcode, cast(name as varchar(500)) as categname,
[level] = 0 , isnull(lastitemcode, cast(left(isnull(code,'XX'),2) + 'XXXX0000' as varchar(10))) lastitemcode 
FROM #tree WHERE isnull(parentgroupid,0)=0 and id=coalesce(@categoryid,id) 
UNION ALL
-- recursive:
SELECT t.ID, t.name , t.parentgroupid,t.code, 
cast(case when x.[level]=0 then left(x.categcode,2) + left(t.code,2) + 'XX' else left(x.categcode,4) + left(t.code,2) end 
as varchar(6)) as categcode, 
cast(x.name + ' :==> ' + t.name as varchar(500)) as categname,
[level] = x.[level] + 1, t.lastitemcode
FROM x INNER JOIN #tree AS t
ON t.parentgroupid = x.ID 

)
SELECT ID, name, isnull(lastitemcode,categcode + '0000') as code, 
x.parentgroupid, categcode, categname, [level], 
isnull(lastitemcode,categcode + '0000') lastitemcode ,
isnull(b.cnt,0) childcnt 
FROM x  left JOIN
(select parentgroupid,count(parentgroupid) cnt from x group by parentgroupid) b
on x.id=b.parentgroupid
ORDER BY [level],name
OPTION (MAXRECURSION 100);
DROP TABLE #tree;
--select id,name from db_mm.mst_dimension
END





GO
/****** Object:  StoredProcedure [db_masters].[pr_getitemdata]    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_getitemdata] 1,1,55119
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitemdata] 
	@coid int = 1,
	@boid int = 1,
	@itemid Int
AS
BEGIN
	SET NOCOUNT ON;
	
	-- get item's general information
	SELECT im.id, [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],im.[hsncode],[taxrate],[receivingunitid] ,[UOM],[issuingunitid] ,[UOM],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[lastissuancedate],[openingrate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],im.[coid],im.[boid],im.[isactive],im.[createdby],[im].[location],[im].[remarks],
				[im].[openingstock],[im].[itemclassABC],[itemalias],im.[gstid],h.id hsnid,case when [itemcode] like 'MC%' then 1 else 0 end rmtype
				from [db_mm].[mst_item]  im 
				left join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id
				left join db_mm.mst_hsn h on im.hsncode=h.hsncode
				where im.id=@itemid and im.coid = @coid and im.boid = @boid

				

	--- get item's supplier data
	select   [suplid],[itemid],[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface] 
	from [db_mm].[supplier_items]
	where itemid = @itemid

	-- get item's brand information
	SELECT [brandid],[name],[itemid],b.[coid],b.[boid] 
	FROM  [db_mm].[item_brands] b left join [db_mm]. [mst_brand] M on b.brandid=m.id
	where itemid = @itemid

	-- get item's type information
	SELECT [typeid],[itemid],t.[name],ty.[coid],ty.[boid]
       FROM [db_mm].[item_types] ty
	   join [db_mm].[mst_itemtypes] t on ty.typeid=t.id
	    where itemid = @itemid
		
    select * from [db_masters].[Make]

	select * from [db_masters].[Model]

	select * from db_mm.mst_item where id =@itemid  order by id desc

	--use in item_master from Wt Calc. added by Mohit (2019-11-08)
		select c.id,dimensionid,name,value,itemid from db_mm.dtl_itemwise_dimension c 
	join db_mm.mst_dimension m on c.dimensionid=m.id
	where itemid=(select id from db_mm.mst_item where id =@itemid  )

	--use in BOM from Wt Calc. added by Mohit (2019-11-08)
	--" m.id=7" hard-code for wt/mtr calc 
 declare @count int =(	select count(*) from [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
		where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =@itemid  ) and m.id=7)
		if @count=1
		begin 
	select top(1)  p.id,p.name from [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
	join  db_mm.dtl_wtparameter_mapping wp on m.id=wp.dimensionid join [db_mm].[mst_wtparameter] p on wp.wtparameterid =p.id
	where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =@itemid  ) 
	end 
	else 
	begin 
		select distinct p.id,p.name from [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
	join  db_mm.dtl_wtparameter_mapping wp on m.id=wp.dimensionid join [db_mm].[mst_wtparameter] p on wp.wtparameterid =p.id
	where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =@itemid  ) 
	end

	--SELECT p.id,p.name, COUNT(p.id) FROM [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
	--join  db_mm.dtl_wtparameter_mapping wp on m.id=wp.dimensionid join [db_mm].[mst_wtparameter] p on wp.wtparameterid =p.id
	--where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =56579  )	 GROUP BY p.name,p.id 

	--select id,max(noum) noum,a.name from (	SELECT p.id, COUNT(p.id) noum,p.name FROM [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
	--join  db_mm.dtl_wtparameter_mapping wp on m.id=wp.dimensionid join [db_mm].[mst_wtparameter] p on wp.wtparameterid =p.id
	--where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =56579  )
	-- GROUP BY p.name,p.id ) as a group by a.id,a.name  having max(noum)=
	-- (SELECT COUNT(p.id) noum FROM [db_mm].[dtl_categorywise_dimension_mapping] c join db_mm.mst_dimension m on c.dimensionid=m.id
	--join  db_mm.dtl_wtparameter_mapping wp on m.id=wp.dimensionid join [db_mm].[mst_wtparameter] p on wp.wtparameterid =p.id
	--where c.categoryid=(select itemcategoryid from db_mm.mst_item where id =56579  )
	-- GROUP BY p.name,p.id)
	-- select * from db_mm.mst_dimension
END


GO
/****** Object:  StoredProcedure [db_masters].[pr_getitemlist]    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_getitemlist] 200,101,1,1,'itemname','asc'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitemlist] 
	@PageNumber bigint,
	@PageSize bigint,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='ITEMNAME',
	@sortorder nvarchar(100)='asc'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	-- get item's general information
	set @sql = 'SELECT im.[id],[itemcategoryid],[name] as itemcategoryname,[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[taxrate],[receivingunitid] ,[UOM],[issuingunitid] ,[UOM],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel],  im.gstid, g.hsncode, g.igst, g.sgst, g.cgst
				,[rol],im.[coid],im.[boid],im.[isactive],im.[createdby]
				from [db_mm].[mst_item]  im 
				left join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id
				left   join [db_mm].[mst_gst] g on im.gstid=g.gstid
			  	left join  [db_mm].[mst_itemcategory] ic on im.itemcategoryid= ic.id'
				set @sql += ' where im.coid = ' + cast(@coid as varchar(5)) + ' and im.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(10))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL
					
 select count(im.[id])records from [db_mm].[mst_item]  im
 left join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id 
	
END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getitemtype]    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_getitemtype] 1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitemtype] 

	@coid Int ,
	@boid int=1

AS
BEGIN
	SET NOCOUNT ON;
	
	SELECT [id],[name] from [db_mm].[mst_itemtypes] where Coid = @coid and boid=@boid

	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getitemuom]    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_getitemuom] 1,2
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getitemuom] 

	@coid INT ,
	@boid Int 
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	 SELECT [id],[uom] as test1211 from [db_mm].[mst_itemuom] where coid =  @coid  and boid=@boid
	
	
	

END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getmake]    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_getModel]  1,1,1,100,''
-- =============================================

CREATE PROCEDURE [db_masters].[pr_getmake] 
    @coid Int,
	@boid Int,  
	@PageNumber INT = null,
	@PageSize INT= null,
	@sort nvarchar(100) = 'id'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql= 'select id,name from [db_masters].make'

	if(isnull(@PageNumber,0)>0)
	begin
	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_masters].[pr_getModel]    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_getModel] 1,1,1,100,''
-- =============================================

CREATE PROCEDURE [db_masters].[pr_getModel] 
    @coid Int,
	@boid Int,  
	@PageNumber INT = null,
	@PageSize INT= null,
	@sort nvarchar(100) = 'id'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql= 'select model.id,model.modelname,model.makeid , model.modelname
                  from [db_masters].[Model] model 
			   inner join [db_masters].[Make] make on model.makeid = make.id '

	if(isnull(@PageNumber,0)>0)
	begin
	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_masters].[pr_getmst_machineData]    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 Machine data>
-- [db_masters].[pr_getmst_machineData] 1,1,33
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getmst_machineData] 
	@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'
	-- get machine's general information
	SELECT mc.[id],mc.[coid],mc.[boid],[MachineName],[MCCatgId],mcc.MCCatgName,[MCSRNo],[MCChassisNo],[MCModel],[MCCapacity],[MCSupplierId],[MCManufacturer],
    [MaintBy],
	[MainSupplierId],[UnderWty],	
	case when [Wtyupto] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([Wtyupto],'yyyy-MM-dd') end [Wtyupto],
	[UnderAMC],
	case when [AMCFrom] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([AMCFrom],'yyyy-MM-dd') end [AMCFrom], 
	case when [AMCUpto] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([AMCUpto],'yyyy-MM-dd') end [AMCUpto], 
	[EmergencyContactNo],
	case when [LastMaint] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([LastMaint],'yyyy-MM-dd') end [LastMaint],
	[LMAfterOps],
	case when [LastBDownMaint] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([LastBDownMaint],'yyyy-MM-dd') end [LastBDownMaint]	
	,[BMAfterOps],
	case when [NextMaint] ='1900-01-01 00:00:00' then '' 
	else FORMAT ([NextMaint],'yyyy-MM-dd') end [NextMaint]		
	,[NMAfterOps],[SplTools],[SplTeam],[ProjLifeYY],[ProjLifeMM],[ProjLifeOps],[ActualLifeYY],[ActualLifeMM],[ActualLifeOps],mc.[createdby],mc.[createdon],mc.[modifiedby],mc.[modifiedon],s.name suplname,s1.name MainSuppliername
	from [db_masters].[mst_machine] mc
	join [db_masters].[machinecategory] mcc on mc.MCCatgId=mcc.id 
	left join [db_masters].[supplier] s on mc.MCSupplierId=s.id
	left join [db_masters].[supplier] s1 on mc.[MainSupplierId]=s1.id
	where mc.id =  @id and mc.coid= @coid and mc.boid=@boid
	--get machine category information
	Select id,MCCatgName from [db_masters].[machinecategory]
	--get Fixed Asset Information
	Select [id],[assetno],[currentloc],[procuredon],[installedon],[operationalon]
	from [db_masters].[fixedassetregister] where mcid=@id
END

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

--  exec [db_masters].[pr_getprospectcustomerData] 1,1,71
-- =============================================

    CREATE PROCEDURE [db_masters].[pr_getprospectcustomerData] 
  	@coid Int = 1,
  	@boid Int = 1,
  	@custid bigint =0
  AS
  BEGIN
  	SET NOCOUNT ON;
	DECLARE  @PageNumber INT =1,@PageSize INT =500,@sort nvarchar(100)= 'boid',@sortorder nvarchar(100)= 'asc'
  	-- get supplier's general information
  	  SELECT c.[id],c.[coid],c.[boid],c.[name],[categoryid],[segmentid],[businesssegementname],[gsTin],[pan],[address1],[address2],[city],[state]
      ,[country],[pin],[mobile_number],[phone_number],[fax],[email],[website],[tds_applicable],[tds_rate],[tcs_applicable]
      ,[tcs_rate],c.[isactive],c.[createdby],c.[createdon],c.[modifiedby],c.[modifiedon],c.[deactivatedby],c.[deactivatedon],
       COALESCE(credit_days,0) as credit_days,COALESCE(credit_limit,0) as credit_limit,p.[name] as currencyname,COALESCE(zone,0) as zone,
  	  [zonename],[area],[areaname],[region],[regionname],[title],[vendorcode],c.iecno,c.eximcode,c.currency_preference,c.excise_regn_number,
	  c.excise_commissionerate,c.excise_division,c.excise_range,c.vat_number,c.vat_date
  	  from [db_masters].prospectcustomers 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 prospect.[id],prospect.custid,prospect.[bankid],b.name AS bankname,
	prospect.[bankacno],prospect.[ifsc],prospect.[isactive] 
	FROM [db_masters].prospectcustomer_banks prospect
	LEFT JOIN db_masters.bankmaster b  ON prospect.bankid = b.id
  	where prospect.custid = @custid

  	-- get supplier's contacts information
  	SELECT [id],custid,[name],[mobile],[phone],[fax],[email],[website],[isactive],position
  	FROM [db_masters].prospectcustomer_contactpersons where custid = @custid
  	-- get supplier's license information
  	SELECT [id],custid,[licensetype],[licenseno],[validtill],[authentication],[isactive]

    FROM [db_masters].prospectcustomer_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_getquotebusinesssegmentlist]    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_getquotebusinesssegmentlist]   1,1,null,42

CREATE PROCEDURE [db_masters].[pr_getquotebusinesssegmentlist] 
@coid int,
@userid int = null,
@segmentid int=null,
@quoteid 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 (@quoteid > 0)
begin
update #tempbsegmentlist set value = isnull(dt.qty,0) , selected = 1 
from  db_mktg.dtl_bsegmt_quote dt where #tempbsegmentlist.id = dt.bsegmtid and dt.quoteid=@quoteid
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_getRegionList]    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_getRegionList] 1,1,1,100,'regionname',1,1
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getRegionList] 
    @coid int,
	@boid int,
	@PageNumber int = null,
	@PageSize int = null,
	@sort nvarchar(100)=NULL,
	@countryid int ,
	@zoneid int
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select r.id,regionname from [db_masters].[country] c inner join
	[db_masters].[Regionmaster] r on c.id=r.countryid inner join
	[db_masters].[zonemaster] z on r.zoneid=z.id
	 where Countryid =  '+ cast(@countryid as varchar(3)) +' and zoneid='+cast(@zoneid as varchar(3)) 
	+ ' and r.coid =  '+ cast(@coid as varchar(3)) +' and r.boid='+cast(@boid as varchar(3)) 

	--print @sql
	EXEC sp_executesql @SQL
	
	select count(r.id)records from [db_masters].[country] c inner join
	[db_masters].[Regionmaster] r on c.id=r.countryid inner join
	[db_masters].[zonemaster] z on r.zoneid=z.id where Countryid =  @countryid and zoneid=@zoneid and r.coid = @coid and r.boid = @boid
	 
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getStateList]    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_getAllCountry] 1,100,1,1,'countryname',1,100
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getStateList] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='Statename',
	@sortorder nvarchar(100)='',
	@Countryid int	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id,statename from [db_masters].[statemaster] '
	set @sql +=' where countryid =  '+ cast(@Countryid as varchar(3)) +' and 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].[statemaster] 
END




GO
/****** Object:  StoredProcedure [db_masters].[pr_getSuplierContactInfox]    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,10,'name',0
-- =============================================
create PROCEDURE [db_masters].[pr_getSuplierContactInfox] 
	@PageNumber INT,
	@PageSize INT,
	@sort nvarchar(100),
	@supplierid Int = NULL
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select  id, suplid, name, mobile, phone, fax, email, website

	from [db_masters].[supplier_contactpersons]  '

	if (@supplierid <>0)
		begin
		set @sql+=' where suplid =  '+  cast(@supplierid as varchar(5)) +'' 
		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)'

	--print @sql
	EXEC sp_executesql @SQL
	
END



GO
/****** Object:  StoredProcedure [db_masters].[pr_getSuplierData]    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_getSuplierData] 1,1,180
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getSuplierData] 
	@coid int = 1,
	@boid int = 1,
	@supplierid Int
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 sp.[id],sp.[coid],sp.[boid],[name],[categoryid],spc.categoryname as categoryname,[segmentid],[gsTin],[pan],[address1],[address2],[city],[cityname] 
      ,[state],[statename] 
      ,[country],[countryname],[pin],[mobile_number],[phone_number],[fax],[email],[website],[tds_applicable],[tds_rate],[tcs_applicable]
      ,[tcs_rate],sp.[isactive],sp.[createdby],sp.[createdon],sp.[modifiedby],sp.[modifiedon],sp.[deactivatedby],sp.[deactivatedon],[vat_number]
      ,[vat_date],[excise_regn_number],[excise_commissionerate],[excise_division],[excise_range],[credit_days],[credit_limit],
	  isnull(sp.associateacid,0) associateacid,
	  case when sp.associateacid>0 then (select name+' '+isnull(address1,'')+' '+isnull(address2,'') from [db_masters].[supplier] where id=sp.associateacid ) else '' end associateacname
	,case when sp.associateacid>0 then 1 else 0 end isassociate
	  -- ,[currency_preference]  
	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.id =  @supplierid and sp.coid= @coid and sp.boid=@boid
	--- get supplier's bank account info
	--select [id],[suplid],[bankid],[bankacno],[ifsc],[isactive] FROM [db_masters].[supplier_banks]
	--where suplid = @supplierid
	select supplier.[id],supplier.suplid,supplier.[bankid],b.name AS bankname,
	supplier.[bankacno],supplier.[ifsc],supplier.[isactive] 
	FROM [db_masters].[supplier_banks] supplier
	LEFT JOIN db_masters.bankmaster b  ON supplier.bankid = b.id
  	where supplier.suplid = @supplierid
	-- get supplier's contacts information
	SELECT [id],[suplid],[name],[mobile],[phone],[fax],[email],[website],[isactive],position
	FROM [db_masters].[supplier_contactpersons]
	where suplid = @supplierid

	-- get supplier's license information
	SELECT [id],[suplid],[licensetype],[licenseno],[validtill],[authentication],[isactive]
       FROM [db_masters].[supplier_licenseinfo] where suplid = @supplierid
	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_getVoucherCategories]    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_getVoucherCategories] 1,100,'name'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getVoucherCategories]
	@PageNumber INT,
	@PageSize INT,
	@sort nvarchar(100),
	@categid Int = NULL
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql= 'SELECT [ID]
      ,[NAME]
      ,[PARENTID]
      ,[VOUCHERNO]
      ,[CATEGCODE]
      ,[ISACTIVE]
      ,[createdby]
      ,[createdon]
      ,[modifiedby]
      ,[modifiedon]
  FROM [db_masters].[voucher_categories]'
	if (@categid is not null)
		begin
		set @sql+=' where parentid =  '+ cast(@categid as varchar(3))  
		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)'

	--print @sql
	EXEC sp_executesql @SQL

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

END


GO
/****** Object:  StoredProcedure [db_masters].[pr_getZoneList]    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_getZoneList] 1,1,1,100,'Zonename'
-- =============================================
CREATE PROCEDURE [db_masters].[pr_getZoneList] 
    @coid Int,
	@boid Int,  
	@PageNumber INT = null,
	@PageSize INT= null,
	@sort nvarchar(100) = null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql= 'select id,Zonename from [db_masters].[zonemaster] '
	set @sql +=' where coid='+cast(@coid as varchar(5)) +' and boid='+ cast(@boid as varchar(3)) 

	if(isnull(@PageNumber,0)>0)
	begin
	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
	
	select count(id)records from [db_masters].[zonemaster] 


END



GO
/****** Object:  StoredProcedure [db_masters].[pr_purchaseaccounts]    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_getsupplierpos]1,1,1
-- =============================================
create PROCEDURE [db_masters].[pr_purchaseaccounts] 
    @coid int,
	@boid int
	
AS
BEGIN
	SET NOCOUNT ON;

	select accounthead  from  [db_accounts].[accountHeads] where groupid=4;
	END




GO
/****** Object:  StoredProcedure [db_masters].[pr_savecountrymaster]    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,10,'name',0
-- =============================================
create PROCEDURE [db_masters].[pr_savecountrymaster]
    @statementtype nvarchar(50),
	@userid int=0,
	@coid int =0,
	@boid  int =0,
	@id int =0,
	@date datetime,
	@name varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	
IF (@statementtype='Insert')
Insert into [db_masters].[country](coid, boid, createdby, createdon, countryname, isactive) 
values( @coid, @boid, @userid,@date,@name,1 )

END




GO
/****** Object:  StoredProcedure [db_masters].[pr_savecustomer]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--drop procedure [db_masters].[pr_savesupplier] 
-- =============================================
-- Author:		<Author,,Amit>

-- Create date: <Create Date,19-11-2018>

-- Description:	<Description,save/update supplier data>

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

 CREATE PROCEDURE [db_masters].[pr_savecustomer] 

	@statementtype nvarchar(50),

	@userid int,	

	@fyid int=1,

	@party_tvp [db_masters].[partymaster_tvp] readonly,

	@party_contacts_tvp [db_masters].[party_contactpersons_tvp] readonly,

	@party_bank_tvp [db_masters].[party_bank_tvp] readonly,

	@party_license_tvp [db_masters].[party_licenseinfo_tvp] readonly

AS

BEGIN

SET QUOTED_IDENTIFIER OFF;

SET ANSI_NULLS ON;

SET NOCOUNT ON;

	------get customer group id from control table     mohit

DECLARE  @sdebtorsgroupid BIGINT





	-- declare varilable for voucher no and voucher category

	declare @customerid bigint, @rowcnt int, @countryid int, @stateid int,@cityid int,@coid int, @accountid bigint,@boid int,@partyid bigint;

	declare @colstring nvarchar(max), @sql nvarchar(max), @countryname varchar(50), @statename varchar(50), @cityname varchar(50);



-- STEP 1: Start the transaction

BEGIN TRANSACTION



SELECT
	@countryid = country

   ,@stateid = state

   ,@cityid = city

   ,@coid = coid

   ,@countryname = newCountry

   ,@boid = boid

   ,@statename = newState

   ,@cityname = newCity

FROM @party_tvp

SET @sdebtorsgroupid = (SELECT 	(sdebtorsid)	FROM db_general.company_control where coid=@coid and boid=@boid)

IF (@countryid = 0) -- if countryid is 0, insert new country

BEGIN

INSERT INTO db_masters.country (coid, boid, countryname, isactive, createdby, createdon)

	VALUES (@coid, @boid, @countryname, 1, @userid, GETDATE())

SELECT

	@countryid = SCOPE_IDENTITY()

END



IF (@stateid = 0) --  if stateid = 0, insert new state

BEGIN

INSERT INTO db_masters.statemaster (coid, boid, statename, countryid, isactive, createdby, createdon)

	VALUES (@coid, @boid, @statename, @countryid, 1, @userid, GETDATE())

SELECT

	@stateid = SCOPE_IDENTITY()

END



IF (@cityid = 0) --  if stateid = 0, insert new state

BEGIN

INSERT INTO db_masters.city (coid, boid, cityname, countryid, stateid, isactive, createdby, createdon)

	VALUES (@coid, @boid, @cityname, @countryid, @stateid, 1, @userid, GETDATE())

SELECT

	@cityid = SCOPE_IDENTITY()

END



IF (@statementtype = 'Insert')

BEGIN

-- insert data in accounthead table and checking @@ERROR 

INSERT INTO db_accounts.accountHeads (coid, boid, groupid, accounthead, clbal, opbal, yob)

	SELECT

		[coid]

	   ,[boid]

	   ,@sdebtorsgroupid

	   ,[name]

	   ,0

	   ,[openingbal]

	   ,0

	FROM @party_tvp



SELECT

	@accountid = SCOPE_IDENTITY()



-----insert data into yearopening

INSERT INTO db_accounts.yearopening (coid, boid, accountid, openingbalance, parentgroupid, fyid)

	SELECT		[coid],[boid],@accountid	   ,[openingbal]	   ,@sdebtorsgroupid	   ,@fyid

	FROM @party_tvp





-- insert data in customer table and checking @@ERROR 

INSERT INTO db_masters.customer ([coid], [boid], [name], [categoryid], [segmentid]

, [gstin], [pan], [address1], [address2], [city], [state], [country], [pin], [mobile_number], [phone_number], [fax]

, [email], [website], [tds_applicable], [tds_rate], [tcs_applicable], [tcs_rate], [isactive], [createdby]

, [createdon], [zone], [area], [region], [vendorcode], [title], [accountid], [credit_days], [credit_limit], [vat_number], [vat_date],

  [excise_regn_number], [excise_commissionerate], [excise_division], [excise_range], [currency_preference],[eximcode],[iecno],associateacid)



	SELECT [coid]	   ,[boid]	   ,[name]	   ,[categoryid]	   ,[segmentid]	   ,[gstin]	   ,[pan]	   ,[address1]	   ,[address2]

	   ,@cityid	   ,@stateid	   ,@countryid	   ,[pin]	   ,[mobile_number]	   ,[phone_number]	   ,[fax]	   ,[email]	   ,[website]

	   ,[tds_applicable]	   ,[tds_rate]	   ,[tcs_applicable]	   ,[tcs_rate]	   ,[isactive]	   ,@userid	   ,GETDATE()	   ,[zone]

	   ,[area]	   ,[region]	   ,[vendorcode]	   ,[title]	   ,@accountid	   ,[credit_days]	   ,[credit_limit]	   ,[vat_number]

	   ,[vat_date]	   ,[excise_regn_number]	   ,[excise_commissionerate]	   ,[excise_division]	   ,[excise_range]	   ,[currency_preference]

	   ,[eximcode]	   ,[iecno],associateacid	FROM @party_tvp



SELECT 	@customerid = SCOPE_IDENTITY()

		update db_accounts.accountHeads set partyid=@customerid where id=@accountid

-- insert data for supplier banks and checking @@ERROR 

INSERT INTO db_general.customer_banks ([custid], [bankid], [bankacno], [ifsc], [isactive], [createdby], [createdon])

	SELECT

		@customerid

	   ,[bankid]

	   ,[bankacno]

	   ,[ifsc]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	FROM @party_bank_tvp





-- insert data for supplier contacts and checking @@ERROR 

INSERT INTO db_general.customer_contactpersons ([custid], [name], [mobile], [phone], [fax], [email], [isactive]

, [createdby], [createdon],position)

	SELECT

		@customerid

	   ,[name]

	   ,[mobile]

	   ,[phone]

	   ,[fax]

	   ,[email]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	   ,position

	FROM @party_contacts_tvp



-- insert data for supplier licenses and checking @@ERROR 

INSERT INTO db_general.customer_licenseinfo ([custid], [licensetype], [licenseno], [validtill], [authentication],

[isactive], [createdby], [createdon])

	SELECT

		@customerid

	   ,[licensetype]

	   ,[licenseno]

	   ,[validtill]

	   ,[authentication]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	FROM @party_license_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 customer license data.', 16, 1)

RETURN

END



END

ELSE

BEGIN -- begin of update 



SELECT TOP 1

	@customerid = id

FROM @party_tvp

SELECT

	[coid]

   ,[boid]

   ,[name]

   ,[categoryid]

   ,[segmentid]

   ,[gstin]

   ,[pan]

   ,[address1]

   ,[address2]

   ,[city]

   ,[state]

   ,[country]

   ,[pin]

   ,[mobile_number]

   ,[phone_number]

   ,[fax]

   ,[email]

   ,[website]

   ,[tds_applicable]

   ,[tds_rate]

   ,[tcs_applicable]

   ,[tcs_rate]

   ,[isactive]

   ,[createdby]

   ,[createdon]

   ,[zone]

   ,[area]

   ,[region]

   ,[vendorcode]

   ,[title]

   ,[credit_days]

   ,[credit_limit]

   ,[title]

FROM db_masters.customer

WHERE id = @customerid

EXCEPT SELECT

	[coid]

   ,[boid]

   ,[name]

   ,[categoryid]

   ,[segmentid]

   ,[gstin]

   ,[pan]

   ,[address1]

   ,[address2]

   ,[city]

   ,[state]

   ,[country]

   ,[pin]

   ,[mobile_number]

   ,[phone_number]

   ,[fax]

   ,[email]

   ,[website]

   ,[tds_applicable]

   ,[tds_rate]

   ,[tcs_applicable]

   ,[tcs_rate]

   ,[isactive]

   ,[createdby]

   ,[createdon]

   ,[zone]

   ,[area]

   ,[region]

   ,[vendorcode]

   ,[title]

   ,[credit_days]

   ,[credit_limit]

   ,[title]

FROM @party_tvp





SELECT

	@rowcnt = @@rowcount

-- data needs to update if query returns a row  

IF @rowcnt > 0

BEGIN -- begin of row count

-- insert records in bkup and checking @@ERROR 

INSERT INTO CloudERPbklog.db_masters.customer (id, [coid], [boid], [customername], [categoryid], [segmentid]

, [gstin], [pan], [address1], [address2], [city], [state], [country], [pin], [mobile_number], [phone_number], [fax]

, [email], [website], [tds_applicable], [tds_rate], [tcs_applicable], [tcs_rate], [isactive], [createdby]

, [createdon], [zone], [area], [region], [vendorcode], [title], [modifiedby])

	SELECT

		id

	   ,[coid]

	   ,[boid]

	   ,[name]

	   ,[categoryid]

	   ,[segmentid]

	   ,[gstin]

	   ,[pan]

	   ,[address1]

	   ,[address2]

	   ,[city]

	   ,[state]

	   ,[country]

	   ,[pin]

	   ,[mobile_number]

	   ,[phone_number]

	   ,[fax]

	   ,[email]

	   ,[website]

	   ,[tds_applicable]

	   ,[tds_rate]

	   ,[tcs_applicable]

	   ,[tcs_rate]

	   ,[isactive]

	   ,[createdby]

	   ,[createdon]

	   ,[zone]

	   ,[area]

	   ,[region]

	   ,[vendorcode]

	   ,[title]

	   ,[modifiedby]

	FROM db_masters.customer

	WHERE id = @customerid







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

-- updating existing records from supplier table and checking @@ERROR 

UPDATE db_masters.customer

SET [coid] = a.[coid]

   ,[boid] = a.[boid]

   ,[name] = a.[name]

   ,[categoryid] = a.[categoryid]

   ,[segmentid] = a.[segmentid]

   ,[gstin] = a.[gstin]

   ,[pan] = a.[pan]

   ,[address1] = a.[address1]

   ,[address2] = a.[address2]

   ,[city] = @cityid

   ,[state] = @stateid

   ,[country] = @countryid

   ,[pin] = a.[pin]

   ,[mobile_number] = a.[mobile_number]

   ,[phone_number] = a.[phone_number]

   ,[fax] = a.[fax]

   ,[email] = a.[email]

   ,[website] = a.[website]

   ,[tds_applicable] = a.[tds_applicable]

   ,[tds_rate] = a.[tds_rate]

   ,[tcs_applicable] = a.[tcs_applicable]

   ,[tcs_rate] = a.[tcs_rate]

   ,[isactive] = a.[isactive]

   ,[createdby] = a.[createdby]

   ,[createdon] = a.[createdon]

   ,[modifiedby] = @userid

   ,[modifiedon] = GETDATE()

   ,[deactivatedby] = a.[deactivatedby]

   ,[deactivatedon] = a.[deactivatedon]

   ,[zone] = a.[zone]

   ,[area] = a.[area]

   ,[region] = a.[region]

   ,[vendorcode] = a.[vendorcode]

   ,[title] = a.[title]

   ,[credit_days] = a.[credit_days]

   ,[credit_limit] = a.[credit_limit]

   ,[vat_number] = a.[vat_number]

   ,[vat_date] = a.[vat_date]

   ,[currency_preference] = a.[currency_preference]

   ,[excise_regn_number] = a.[excise_regn_number]

   ,[excise_commissionerate] = a.[excise_commissionerate]

   ,[excise_division] = a.[excise_division]

   ,[excise_range] = a.[excise_range]

   ,[eximcode]=a.[eximcode]

   ,[iecno]=a.[iecno]

   ,associateacid=a.associateacid

FROM @party_tvp a

WHERE db_masters.customer.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 supplier record.', 16, 1)

RETURN

END

END -- end of row count

ELSE -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 

BEGIN

IF NOT EXISTS (SELECT

			id

		FROM CloudERPbklog.db_masters.customer

		WHERE id = @customerid)

BEGIN

-- insert data in supplier table and checking @@ERROR 

INSERT INTO CloudERPbklog.db_masters.customer ([id], [coid], [boid], [customername], [categoryid], [segmentid]

, [gstin], [pan], [address1], [address2], [city], [state], [country], [pin], [mobile_number], [phone_number], [fax]

, [email], [website], [tds_applicable], [tds_rate], [tcs_applicable], [tcs_rate], [isactive], [createdby]

, [createdon], [modifiedby], [modifiedon], [deactivatedby], [deactivatedon], [zone], [area], [region], [vendorcode], [title])

	SELECT

		[id]

	   ,[coid]

	   ,[boid]

	   ,[name]

	   ,[categoryid]

	   ,[segmentid]

	   ,[gstin]

	   ,[pan]

	   ,[address1]

	   ,[address2]

	   ,[city]

	   ,[state]

	   ,[country]

	   ,[pin]

	   ,[mobile_number]

	   ,[phone_number]

	   ,[fax]

	   ,[email]

	   ,[website]

	   ,[tds_applicable]

	   ,[tds_rate]

	   ,[tcs_applicable]

	   ,[tcs_rate]

	   ,[isactive]

	   ,[createdby]

	   ,[createdon]

	   ,@userid

	   ,GETDATE()

	   ,[deactivatedby]

	   ,[deactivatedon]

	   ,[zone]

	   ,[area]

	   ,[region]

	   ,[vendorcode]

	   ,[title]

	FROM db_masters.customer

	WHERE id = @customerid

----- 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 customer data.', 16, 1)

RETURN

END

END

END





-- check for changes in supplier bank details



-- defining column list of supplier bank table

SELECT

	[custid]

   ,[bankid]

   ,[bankacno]

   ,[ifsc]

   ,[isactive]

   ,[createdby]

   ,[createdon]

FROM [db_general].[customer_banks]

WHERE custid = @customerid

-- creating dynamic query to check for changes in row data 

EXCEPT SELECT

	@customerid

   ,[bankid]

   ,[bankacno]

   ,[ifsc]

   ,[isactive]

   ,@userid

   ,GETDATE()

FROM @party_bank_tvp







SELECT

	@rowcnt = @@rowcount



IF @rowcnt > 0

BEGIN

-- insert data needs to log table if query returns a row  

INSERT INTO CloudERPbklog.db_masters.customer_banks ([custid], [bankname], [bankacno], [ifsc], [isactive], [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby], [deactivatedon])

	SELECT

		@customerid

	   ,[bankid]

	   ,[bankacno]

	   ,[ifsc]

	   ,[isactive]

	   ,[createdby]

	   ,[createdon]

	   ,@userid

	   ,GETDATE()

	   ,[deactivatedby]

	   ,[deactivatedon]

	FROM db_general.customer_banks

	WHERE [custid] = @customerid



-- 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 supplier bank data into log table.', 16, 1)

RETURN

END

--delete existing bank details for this supplier

DELETE FROM [db_general].[customer_banks]

WHERE [custid] = @customerid



-- insert data for supplier banks and checking @@ERROR 

INSERT INTO [db_general].[customer_banks] ([custid], [bankid], [bankacno], [ifsc], [isactive], [createdby], [createdon])

	SELECT

		@customerid

	   ,[bankid]

	   ,[bankacno]

	   ,[ifsc]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	FROM @party_bank_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 updating supplier`s bank data.', 16, 1)

RETURN

END

END



-- check for changes in supplier contacts



-- defining column list of supplier contact persons table

SELECT

	custid

   ,[name]

   ,[mobile]

   ,[phone]

   ,[fax]

   ,[email]

   ,[isactive]

FROM [db_general].[customer_contactpersons]

WHERE custid = @customerid

EXCEPT SELECT

	@customerid

   ,[name]

   ,[mobile]

   ,[phone]

   ,[fax]

   ,[email]

   ,[isactive]

FROM @party_contacts_tvp



SELECT

	@rowcnt = @@rowcount



IF @rowcnt > 0

BEGIN

-- insert data needs to log table if query returns a row  

INSERT INTO CloudERPbklog.db_masters.customer_contactpersons ([custid], [name], [mobile], [phone], [fax],

[email], [website], [isactive], [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby], [deactivatedon])

	SELECT

		@customerid

	   ,[name]

	   ,[mobile]

	   ,[phone]

	   ,[fax]

	   ,[email]

	   ,[website]

	   ,[isactive]

	   ,[createdby]

	   ,[createdon]

	   ,@userid

	   ,GETDATE()

	   ,[deactivatedby]

	   ,[deactivatedon]

	FROM [db_general].[customer_contactpersons]

	WHERE [custid] = @customerid



-- 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 supplier contact persons data into log table.', 16, 1)

RETURN

END

--delete existing bank details for this supplier

DELETE FROM db_general.customer_contactpersons

WHERE [custid] = @customerid



-- insert data for supplier banks and checking @@ERROR 

INSERT INTO [db_general].[customer_contactpersons] ([custid], [name], [mobile], [phone], [fax], [email],

[isactive], [createdby], [createdon],position)

	SELECT

		@customerid

	   ,[name]

	   ,[mobile]

	   ,[phone]

	   ,[fax]

	   ,[email]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	   ,position

	FROM @party_contacts_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 updating customer`s contact persons data.', 16, 1)

RETURN

END

END



-- check for changes in supplier licenses

-- defining column list of supplier licenses table

SELECT

	custid

   ,[licensetype]

   ,[licenseno]

   ,[validtill]

   ,[authentication]

   ,[isactive]

FROM [db_general].[customer_licenseinfo]

WHERE custid = @customerid

EXCEPT SELECT

	@customerid

   ,[licensetype]

   ,[licenseno]

   ,[validtill]

   ,[authentication]

   ,[isactive]

FROM @party_license_tvp





SELECT

	@rowcnt = @@rowcount



IF @rowcnt > 0

BEGIN

-- insert data needs to log table if query returns a row  

INSERT INTO CloudERPbklog.[db_masters].[customer_licenseinfo] ([custid], [licensetype], [licenseno],

[validtill], [authentication], [isactive], [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby], [deactivatedon])

	SELECT

		@customerid

	   ,[licensetype]

	   ,[licenseno]

	   ,[validtill]

	   ,[authentication]

	   ,[isactive]

	   ,[createdby]

	   ,[createdon]

	   ,@userid

	   ,GETDATE()

	   ,[deactivatedby]

	   ,[deactivatedon]

	FROM db_general.customer_licenseinfo

	WHERE [custid] = @customerid



-- 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 customer license info data into log table.', 16, 1)

RETURN

END

--delete existing bank details for this supplier

DELETE FROM [db_general].[customer_licenseinfo]

WHERE [custid] = @customerid



-- insert data for supplier banks and checking @@ERROR 

INSERT INTO [db_general].[customer_licenseinfo] ([custid], [licensetype], [licenseno],

[validtill], [authentication], [isactive], [createdby], [createdon])

	SELECT

		@customerid

	   ,[licensetype]

	   ,[licenseno]

	   ,[validtill]

	   ,[authentication]

	   ,[isactive]

	   ,@userid

	   ,GETDATE()

	FROM @party_license_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 updating customer`s licenses data.', 16, 1)

RETURN

END

END

END -- end of update 	

-- If we reach this point, the commands completed successfully

--Commit the transaction....

COMMIT



END



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

CREATE PROCEDURE [db_masters].[pr_savedocsubject] 
	@statementtype nvarchar(50),
	@coid int=1,
	@boid int=1,
	@userid bigint=1,
	@id int,
	@deptid int=1,
	@subject varchar(300)

AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	Declare @subjectid int;
  Begin transaction
	If (@statementtype='Insert')
		Begin		
	        -- insert data in customer table and checking @@ERROR 
			insert into db_masters.document_subjects
			(coid,boid,deptid,[subject],isactive,createdby,createdon)
			values(@coid,@boid,@deptid,@subject,1,@userid,getdate())
			 IF @@ERROR <> 0
				BEGIN
				ROLLBACK
				RAISERROR ('Error while adding customer data.', 16, 1)
				RETURN
				END

           SELECT @subjectid= SCOPE_IDENTITY()

		  END

		  select id,deptid,subject from db_masters.document_subjects 

	--ELSE
	--  BEGIN
	--  update db_masters.document_subjects 
	--  set deptid =@deptid,
	--      [subject]= @subject,
	--	  modifiedby = @userid,
	--	  modifiedon = getdate()
	--	  where id=@id
 --     END
 COMMIT
END

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

CREATE PROCEDURE [db_masters].[pr_savedoctitle] 
	@statementtype nvarchar(50),
	@coid int=1,
	@boid int=1,
	@userid bigint=1,
	@id int,
	@subjectid int=1,
	@title varchar(300)

AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	Declare @titleid int;

  Begin transaction
	If (@statementtype='Insert')
		Begin		
	        -- insert data in customer table and checking @@ERROR 
			insert into db_masters.document_titles
		    (coid,boid,subjectid,title,isactive,createdby,createdon)
			values(@coid,@boid,@subjectid,@title,1,@userid,getdate())
			 IF @@ERROR <> 0
				BEGIN
				ROLLBACK
				RAISERROR ('Error while adding customer data.', 16, 1)
				RETURN
				END

				select @titleid=SCOPE_IDENTITY()
            
		  END

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

	--  ELSE
	--  BEGIN
	--  update db_masters.document_titles 
	--  set [subjectid]= @subjectid,
	--      [title]=@title,
	--	  modifiedby = @userid,
	--	  modifiedon = getdate()
	--	  where id=@id
    --     END

 COMMIT
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_saveemployee]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_masters].[pr_saveemployee]
	@statementtype  nvarchar(50),
	@employee       [db_masters].[employee_tvp]       readonly,
	@employeehealth [db_masters].[emphealthcard_tvp]  readonly,
	@emp_splstatus  [db_masters].[emp_splstatus_tvp]  readonly,
	@emp_eduction   [db_masters].[empeducation_tvp]   readonly,
    @emp_experience [db_masters].[empexperience_tvp]  readonly,
    @emp_relation   [db_masters].[emprelation_tvp]    readonly,
	@emp_referals   [db_masters].[empreferals_tvp]    readonly,
	@coid   int=1,
	@boid   int=1,	   	
	@fyid   int=1,
	@userid int=1
  AS
 BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	-- declare varilable for voucher no and voucher category
	 declare @rowcnt int,@empid BIGINT,@sql nvarchar(max)
	-- STEP 1: Start the transaction
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		--  insert data in employee table and checking @@ERROR 
			insert into db_masters.employee(coid,boid,empno,empname,designationid,current_address1,current_address2,current_state,current_city,current_country,permanent_address1,
			permanent_address2,permanent_state,permanent_city,permanent_country,religion,deptid,genderid,aadharno,nameinaadhar,nameinbank,mobile_no,other_phone,
			dob,doj,
			marital_statusid,esiflag,esino,pfflag,pfno,pfrate,fpfrate,uan,
			pfjoiningdate,esijoiningdate,
			domicile,citizen_of,esidispensaryid,voterid,passportno,divinglicense_no,issuedat,
            validupto,bankid,bankacno,bankbranch,bankifsc,sports_ncc_info,civildefenceinfo,csrinfo,biometric_code,
			createdby,createdon,[source],referral_remarks,email,father_husbandname,mothername)
			select coid,boid,empno,empname,designationid,current_address1,current_address2,current_state,current_city,current_country,permanent_address1,
			permanent_address2,permanent_state,permanent_city,permanent_country,religion,deptid,genderid,aadharno,nameinaadhar,nameinbank,mobile_no,other_phone,
			dob,doj,
			marital_statusid,esiflag,esino,pfflag,pfno,pfrate,fpfrate,uan,
			pfjoiningdate,esijoiningdate,
			domicile,citizen_of,esidispensaryid,voterid,passportno,divinglicense_no,issuedat,
            validupto,bankid,bankacno,bankbranch,bankifsc,sports_ncc_info,civildefenceinfo,csrinfo,biometric_code,
			@userid,getdate(),[source],referral_remarks,email,father_husbandname,mothername
			from @employee
		       -- Rollback the transaction if there were any errors
		    IF @@ERROR <> 0
			BEGIN
			  --  Rollback the transaction
			ROLLBACK
			--  Raise an error and return
			RAISERROR ('Error while creating employee.', 16, 1)
			RETURN
			END
	     	SELECT @empid= SCOPE_IDENTITY()
			 insert into db_masters.emp_healthcard(empid,bloodgroup,rhfactor,heightcm,weightkg,eyesight,soscontactname,sosdoctorname,sosdoctorno,
			 powerusingglasses,lastcheckup,nextcheckup,allergies,healthinscoid,healthinsvalidupto,isactive,createdby,createdon)
			 select @empid,bloodgroup,rhfactor,heightcm,weightkg,eyesight,soscontactname,sosdoctorname,sosdoctorno,
			 powerusingglasses,lastcheckup,nextcheckup,allergies,healthinscoid,healthinsvalidupto,isactive,@userid,getdate()
			 from @employeehealth
			 -- Rollback the transaction if there were any errors
		    IF @@ERROR <> 0
			BEGIN
			  --  Rollback the transaction
			ROLLBACK
			--  Raise an error and return
			RAISERROR ('Error while creating employee.', 16, 1)
			RETURN
			END
			 insert into db_masters.emp_splstatus(empid,splstatusid,isactive,createdby,createdon)			 	 
			 select @empid,splstatusid,isactive,@userid,getdate() from @emp_splstatus
			-- Rollback the transaction if there were any errors
		    IF @@ERROR <> 0
			BEGIN
			  --  Rollback the transaction
			ROLLBACK
			--  Raise an error and return
			RAISERROR ('Error while creating employee.', 16, 1)
			RETURN
			END
			insert into db_masters.empeducation(empid,qualificationid,institute,passingyear,grades,remarks)
			select @empid,qualificationid,institute,passingyear,grades,remarks from @emp_eduction
			  -- Rollback the transaction if there were any errors
		    IF @@ERROR <> 0
			BEGIN
			  --  Rollback the transaction
			ROLLBACK
			--  Raise an error and return
			RAISERROR ('Error while creating employee.', 16, 1)
			RETURN
			END
			insert into db_masters.empexperience(empid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,reportingto,remarks,expfrom,expto,deptid)
			select @empid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,reportingto,remarks,expfrom,expto,deptid
			from   @emp_experience
			 --Rollback the transaction if there were any errors
		     IF @@ERROR <> 0
			BEGIN
			 --  Rollback the transaction
			ROLLBACK
			 --Raise an error and return
			RAISERROR ('Error while creating  employee experience.', 16, 1)
			RETURN
			END			

			insert into  db_masters.emp_referals(coid,boid,empid,name,organization,contactno,email)
			select @coid,@boid,@empid,name,organization,contactno,email from @emp_referals

			--Rollback the transaction if there were any errors
		     IF @@ERROR <> 0
			BEGIN
			 --  Rollback the transaction
			ROLLBACK
			 -- Raise an error and return
			RAISERROR ('Error while creating  employee referals.', 16, 1)
			RETURN
			END	

			insert into  db_masters.emp_relations (empid,relationid,coid,boid,name,dob,genderid,bloodgroup)
			select @empid,relationid,@coid,@boid,name,dependant_dob,genderid,dependant_bloodgroup from @emp_relation

			 --Rollback the transaction if there were any errors
		     IF @@ERROR <> 0
			BEGIN
			 --  Rollback the transaction
			ROLLBACK
			 --Raise an error and return
			RAISERROR ('Error while creating  employee dependants.', 16, 1)
			RETURN
			END	


	   END 	 
	Else
		Begin 
			      Select top 1 @empid = id from @employee 
				    UPDATE db_masters.employee 
				    SET coid = a.coid,
                    boid = a.boid,
                    empno = a.empno,
                    empname = a.empname,
                    designationid = a.designationid,
                    current_address1 = a.current_address1,
                    current_address2 = a.current_address2,
                    current_state = a.current_state,
                    current_city = a.current_city,
                    current_country = a.current_country,
                    permanent_address1 = a.permanent_address1,
                    permanent_address2 = a.permanent_address2,
                    permanent_state = a.permanent_state,
                    permanent_city = a.permanent_city,
                    permanent_country = a.permanent_country,
                    religion = a.religion,
                    deptid = a.deptid,
                    genderid = a.genderid,
                    aadharno = a.aadharno,
                    nameinaadhar = a.nameinaadhar,
                    nameinbank= a.nameinbank,
                    mobile_no = a.mobile_no,
                    other_phone=a.other_phone,
                    dob=a.dob,
                    doj=a.doj,
                    marital_statusid=a.marital_statusid,
                    esiflag=a.esiflag,
                    esino=a.esino,
                    pfflag=a.pfflag,
                    pfno=a.pfno,
                    pfrate=a.pfrate,
                    fpfrate=a.fpfrate,
                    uan=a.uan,
                    pfjoiningdate=a.pfjoiningdate,
                    esijoiningdate=a.esijoiningdate,
                    domicile=a.domicile,
                    citizen_of=a.citizen_of,
                    esidispensaryid=a.esidispensaryid,
                    voterid=a.voterid,
                    passportno=a.passportno,
                    divinglicense_no=a.divinglicense_no,
                    issuedat=a.issuedat,
                    validupto=a.validupto,
                    bankid=a.bankid,
                    bankacno=a.bankacno,
                    bankbranch=a.bankbranch,
                    bankifsc=a.bankifsc,
                    sports_ncc_info=a.sports_ncc_info,
                    civildefenceinfo=a.civildefenceinfo,
                    csrinfo=a.csrinfo,
                    biometric_code=a.biometric_code,
                    modifiedby=@userid,
                    modifiedon=getdate(),
                    source=a.source,
                    referral_remarks=a.referral_remarks,
					email = a.email,
					father_husbandname=a.father_husbandname,
					mothername=a.mothername
					FROM   @employee a
					WHERE  db_masters.employee.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 employee record.', 16, 1)
							RETURN
					END
		  Delete from  db_masters.emp_healthcard where empid=@empid
		  insert into db_masters.emp_healthcard(empid,bloodgroup,rhfactor,heightcm,weightkg,eyesight,soscontactname,sosdoctorname,sosdoctorno,
		  powerusingglasses,lastcheckup,nextcheckup,allergies,healthinscoid,healthinsvalidupto,isactive,createdby,createdon,modifiedby,modifiedon,
		  deactivatedby,deactivatedon)	
		  select @empid,bloodgroup,rhfactor,heightcm,weightkg,eyesight,soscontactname,sosdoctorname,sosdoctorno,
		  powerusingglasses,lastcheckup,nextcheckup,allergies,healthinscoid,healthinsvalidupto,isactive,createdby,
		  createdon,modifiedby,modifiedon,deactivatedby,deactivatedon 
		  from @employeehealth
			IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating employee record.', 16, 1)
				RETURN
			END
		 Delete from  db_masters.emp_splstatus where empid=@empid
		 insert into db_masters.emp_splstatus(empid,splstatusid,isactive,createdby,createdon,modifiedby,modifiedon,deactivatedby,deactivatedon)			 	 
	     select empid,splstatusid,isactive,createdby,createdon,modifiedby,modifiedon,deactivatedby,deactivatedon from @emp_splstatus
		  IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating employee record.', 16, 1)
				RETURN
		  END
		  Delete from db_masters.empeducation where empid=@empid
		  insert into db_masters.empeducation(empid,qualificationid,institute,passingyear,grades,remarks)
		  select empid,qualificationid,institute,passingyear,grades,remarks from @emp_eduction
            -- 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 employee.', 16, 1)
			RETURN
			END
			 Delete from db_masters.empexperience where empid=@empid
			 insert into db_masters.empexperience(empid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,reportingto,remarks,expfrom,expto,deptid)
			 select empid,organization,totexpyy,totexpmm,relevantexpyy,relevantexpmm,positionheld,reportingto,remarks,expfrom,expto,deptid
			 from @emp_experience
			 -- 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  employee experience.', 16, 1)
			 RETURN
			 END


			 Delete from db_masters.emp_referals where empid =@empid

			insert into  db_masters.emp_referals(coid,boid,empid,name,organization,contactno,email)
			select @coid,@boid,@empid,name,organization,contactno,email from @emp_referals

			--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  employee referals.', 16, 1)
			RETURN
			END	

			Delete from db_masters.emp_relations where empid =@empid

			insert into  db_masters.emp_relations (empid,relationid,coid,boid,name,dob,genderid,bloodgroup)
			select @empid,relationid,@coid,@boid,name,dependant_dob,genderid,dependant_bloodgroup from @emp_relation

			 --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  employee dependants.', 16, 1)
			RETURN
			END	
		End 
		    -- end of update 	
		    -- If we reach this point, the commands completed successfully
		    -- Commit the transaction....
	COMMIT
	select @empid as empid
END

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

CREATE PROCEDURE [db_masters].[pr_saveitemmaster]
    @statementtype nvarchar(50),
	@userid int=1,
	@itemdata [db_mm].[mst_item_tvp] readonly,
	@supplieritem [db_mm].[supplier_items_tvp] readonly,
	@itembrand [db_mm].[item_brands_tvp] readonly,
	@itemtype  [db_mm].[item_types_tvp] readonly,
	@itemdimenstion [db_mm].[dtl_itemdimension_tvp] readonly
AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
	declare @itemid int, @rowcnt INT,@maxitemid INT, @itemcategoryid int ;
	declare @colstring nvarchar(max), @sql nvarchar(max),@newcode varchar(10);
	declare @itemcode varchar(15);
	-- STEP 1: Start the transaction
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		select @itemcategoryid = [itemcategoryid] from @itemdata
		-- generate new itemcode for the selected itemcategory
		select @maxitemid = isnull(max(id),0)  from db_mm.mst_item where itemcategoryid = @itemcategoryid 
		if (@maxitemid>0)
		Begin
			select @newcode =cast(cast(right(a.[itemcode],5) as VARCHAR) + 1 as varchar(5))
			from db_mm.mst_item a where id = @maxitemid
			select @itemcode = left(a.[itemcode],6) + case when len(@newcode)=1 then '0000'+ @newcode 
			else case when len(@newcode)=2 then '000'+@newcode else 
			case when len(@newcode)=3 then '00'+@newcode else case when len(@newcode)=4 then '0'+@newcode else @newcode end end end end
			from db_mm.mst_item a where id = @maxitemid 
		End
		else
		Begin
			select @newcode = cast(cast(right(itemcode,5) as VARCHAR) + 1 as varchar(5))
			from @itemdata
			select @itemcode = left(a.[itemcode],6) + case when len(@newcode)=1 then '0000'+ @newcode 
			else case when len(@newcode)=2 then '000'+@newcode else 
			case when len(@newcode)=3 then '00'+@newcode else case when len(@newcode)=4 then '0'+@newcode else @newcode end end end end
			from @itemdata a
		End
	-- insert data in item table and checking @@ERROR 
			insert into [db_mm].[mst_item] ([itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel],
				[rol],[coid],[boid],[isactive],[createdby],[createdon],[location],[accessories],[remarks],[packing],[gstid],[mrp])
			Select [itemcategoryid],@itemcode,[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel],
				[rol],[coid],[boid],[isactive],[createdby],[createdon],[location],[accessories],[remarks],[packing],[gstid],[mrp] from @itemdata
			-- 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 item data.', 16, 1)
				RETURN
				END
				SELECT @itemid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting item id.', 16, 1)
				RETURN
				END
	 ----insert opening stock into stock_trn
	    INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[coid],[boid],isactive,createdby,createdon)
				SELECT [id],[id],[openingstock],16,'+',(SELECT coid FROM @itemdata),(SELECT boid FROM @itemdata),1,@userid,getdate() FROM @itemdata
			-- insert data for supplier banks and checking @@ERROR 
			insert into [db_mm].[supplier_items] ([suplid],[itemid],[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface])
			Select [suplid],@itemid,[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface] from @supplieritem
			-- 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 item`s supplier data.', 16, 1)
				RETURN
				END
			-- insert data for item brands and checking @@ERROR 
			insert into db_mm.item_brands([brandid],[itemid],[coid],[boid])
			Select [brandid],@itemid,[coid],[boid]
			from @itembrand
			-- 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 item brand data.', 16, 1)
				RETURN
				END
		    insert into db_mm.item_types([typeid],[itemid],[coid],[boid])
			Select [typeid],@itemid,[coid],[boid] from @itemtype
			IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding item types data.', 16, 1)
				RETURN
				END
				insert into db_mm.dtl_itemwise_dimension(coid, boid, itemid, dimensionid, value, isactive, createdby, createdon)
			Select coid, boid, @itemid, dimensionid, value, isactive,@userid,getdate() from @itemdimenstion
			IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding item types data.', 16, 1)
				RETURN
				END
				end
	Else
		Begin 
		-- begin of update  
		  -- Select @itemid = (Select TOP(1) id from @itemdata)

		  select top 1 @itemid = id from @itemdata

		  SET @itemid =(Select TOP(1) id from @itemdata)

			-- check for itemcateogryid 
			select [itemcategoryid] from @itemdata Except select itemcategoryid from db_mm.mst_item where id = @itemid
			SELECT @rowcnt = @@ROWCOUNT
			IF (@rowcnt>0)
			begin
				select @maxitemid = isnull(max(id),0)  from db_mm.mst_item where itemcategoryid = @itemcategoryid
				if (@maxitemid>0)
				Begin
					select @newcode =cast(cast(right(a.[itemcode],5) as VARCHAR) + 1 as varchar(5))
                    from db_mm.mst_item a where id = @maxitemid
                    select @itemcode = left(a.[itemcode],6) + case when len(@newcode)=1 then '0000'+ @newcode 
                    else case when len(@newcode)=2 then '000'+@newcode else 
                    case when len(@newcode)=3 then '00'+@newcode else case when len(@newcode)=4 then '0'+@newcode else @newcode end end end end
                    from db_mm.mst_item a where id = @maxitemid 
				End
				else
				Begin
					select @newcode = cast(cast(right(itemcode,5) as VARCHAR) + 1 as varchar(5))
					from @itemdata
					select @itemcode = left(a.[itemcode],6) + case when len(@newcode)=1 then '0000'+ @newcode 
					else case when len(@newcode)=2 then '000'+@newcode else 
					case when len(@newcode)=3 then '00'+@newcode else case when len(@newcode)=4 then '0'+@newcode else @newcode end end end end 
					from @itemdata a
				End
			end
			else
			begin
				select @itemcode = [itemcode] from @itemdata
			end

			-- fetching item id from table type
			-- insert data into opening stock
			IF EXISTS(SELECT itemid FROM [db_mm].[item_stk_trn] WHERE trntypeid=16 AND itemid=@itemid)
			 BEGIN
				UPDATE [db_mm].[item_stk_trn] SET itemquantity=(SELECT openingstock FROM @itemdata) 
				WHERE itemid=@itemid AND trntypeid=16			END
			 else
				BEGIN
					INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[coid],[boid])
					SELECT @itemid,@itemid,[openingstock],16,'+',(SELECT coid FROM @itemdata),(SELECT boid FROM @itemdata) FROM @itemdata
				END
			select [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],[coid],[boid],[isactive],[createdby],[createdon],[location],[accessories],[remarks],[packing],[gstid],[mrp]
				from db_mm.mst_item where id =@itemid  
				EXCEPT 
				select [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],[coid],[boid],[isactive],[createdby],[createdon],[location],[accessories],[remarks],[packing],[gstid],[mrp] from @itemdata
			--print @sql
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
			     insert into CloudERPbklog.db_mm.mst_item (id, [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],[coid],[boid],[isactive],[createdby],[createdon],[location] ,[modifiedby],[accessories]) 
					Select id, [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],[coid],[boid],[isactive],[createdby],[createdon],[location], @userid,[accessories] from db_mm.mst_item  where id = @itemid
					--print @sql
					--EXEC sp_executesql @sql
					-- 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
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.mst_item 
						SET [itemcategoryid] =a.[itemcategoryid],
						[itemcode]= @itemcode,                                  
						[itemname]= a.[itemname],
						[itemalias] =a.[itemalias],
						[billingdescription]=a.[billingdescription],
				        [itemspecification]=a.[itemspecification],
				        [oldcode]=a.[oldcode],
				        [specialcode]=a.[specialcode],
				        [hsncode]=a.[hsncode],
				        [taxrate]=isnull(a.[taxrate],0),
				        [receivingunitid]=isnull(a.[receivingunitid],1),
				        [issuingunitid]=isnull(a.[issuingunitid],1),
				        [unitconversionfactor]=isnull(a.[unitconversionfactor],1),
				        [itemimage]=a.[itemimage],
				        [itemdrawing]=a.[itemdrawing],
				        [openingstock]=isnull(a.[openingstock],0),
				        [openingvalue]=isnull(a.[openingvalue],0),
				        [landedrate]=isnull(a.[landedrate],0),
				        [lastpurchaserate]=isnull(a.[lastpurchaserate],0),
				        [eoq]=isnull(a.[eoq],0),
				        [moq]=isnull(a.[moq],0),
				        [minlevel]=isnull(a. [minlevel],0),
				        [maxlevel]= isnull(a.[maxlevel],0),
				        [rol]=isnull(a.[rol],0),
				        [coid]=isnull(a.[coid],1),
				        [boid]=isnull(a.[boid],1),
				        [isactive]=a.[isactive],
				        [createdby]=a.[createdby],
						[createdon] = a.[createdon],
						[location] = a.[location],
						[accessories]=a.[accessories],
						[remarks] =a.[remarks],
						[packing]=a.[packing],
						[gstid]=a.[gstid],
						[mrp]=a.[mrp],
						modifiedby=@userid,
						modifiedon=getdate()
					FROM   @itemdata a
					WHERE db_mm.mst_item.id= @itemid
					-- 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 item record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
				  if not exists(select id from CloudERPbklog.db_mm.mst_item where id = @itemid)
					begin
				      -- insert data in supplier table and checking @@ERROR 
				   insert into CloudERPbklog.db_mm.mst_item([itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription],
			       [itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				  ,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				  ,[rol],[coid],[boid],[isactive],[createdby],[createdon],[accessories])
			       Select [itemcategoryid],[itemcode],[itemname],[itemalias],[billingdescription]
				  ,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid],[issuingunitid],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				  ,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				  ,[rol],[coid],[boid],[isactive],[createdby],[createdon],[accessories] from db_mm.mst_item where id = @itemid
							-- 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 item data.', 16, 1)
								RETURN
								END
						end
				End
			-- check for changes in supplier item  details
			-- defining column list of supplier item table
			select [suplid],[itemid],[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface]
			from [db_mm].[supplier_items] where [itemid] =@itemid 
			 EXCEPT select [suplid],@itemid,[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface] from @supplieritem
			--print @sql
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
			IF @rowcnt > 0
				Begin
					-- insert data needs to log table if query returns a row  
					insert into CloudERPbklog.db_mm.supplier_items([suplid],[itemid],[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface])
					Select [suplid],@itemid,[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface] from db_mm.supplier_items 
					where [itemid]=@itemid
					-- 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 item suplier data into log table.', 16, 1)
						RETURN
						END
					--delete existing bank details for this supplier
					delete from db_mm.supplier_items where [itemid] = @itemid
					-- insert data for supplier banks and checking @@ERROR 
					insert into db_mm.supplier_items([suplid],[itemid],[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface])
					Select [suplid], @itemid ,[brandid],[suplitemcode],[suplitemrate],[leadtimeair],[leadtimesurface] from @supplieritem
					-- 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 item`s supplier data.', 16, 1)
						RETURN
						END
				End
            select  [brandid],[itemid],[coid],[boid]
			 from [db_mm].[item_brands] where [itemid] =@itemid
			  EXCEPT select  [brandid],@itemid,[coid],[boid] from @itembrand 
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
               IF @rowcnt > 0
				Begin
					-- insert data needs to log table if query returns a row  
					insert into CloudERPbklog.db_mm.item_brands([brandid],[itemid],[coid],[boid])
			      Select [brandid],@itemid,[coid],[boid]
			      from db_mm.item_brands where [itemid] = @itemid
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while addingi tems brand data into log table.', 16, 1)
						RETURN
						END
					--delete existing bank details for this supplier
					delete from db_mm.item_brands where [itemid] = @itemid
					-- insert data for supplier banks and checking @@ERROR 
					insert into db_mm.item_brands([brandid],[itemid],[coid],[boid])
					Select [brandid],@itemid,[coid],[boid] from @itembrand
					-- 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 item`s brand data.', 16, 1)
						RETURN
						END
				End
            -- delete removed item types
            delete from [db_mm].[item_types] where itemid = @itemid and 
	         typeid not in (select typeid from @itemtype)
             insert into [db_mm].[item_types] ([typeid],[itemid],[coid],[boid])
			 Select  [typeid],@itemid,[coid],[boid] from @itemtype where typeid not in 
             (select typeid from [db_mm].[item_types] where itemid = @itemid)
                delete from db_mm.dtl_itemwise_dimension where itemid=@itemid
				insert into db_mm.dtl_itemwise_dimension(coid, boid, itemid, dimensionid, value, isactive, createdby, createdon,modifiedby, modifiedon)
			 Select coid, boid, @itemid, dimensionid, value, isactive,createdby, createdon,@userid,getdate() from @itemdimenstion

			 SELECT * from db_mm.mst_item where id=@itemid

          End -- end of update 	
		      -- If we reach this point, the commands completed successfully
		      --Commit the transaction....
		COMMIT

	SELECT * from db_mm.mst_item where id=@itemid
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_savemodel]    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_masters].[pr_savemodel] 
    @statementtype nvarchar(50),
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@id int=0,
	@makeid int=0,
	@model varchar(100)
AS
BEGIN
	SET NOCOUNT ON;
	if @statementtype='Insert'
	begin
	 insert into [db_masters].[Model](makeid,modelname,coid,boid,isactive,createdby,createdon)
	 values(@makeid,@model,@coid,@boid,1,@userid,getdate())
	end
    else
	begin
	 update [db_masters].[Model] set makeid=@makeid,modelname=@model,coid=@coid ,boid=@boid where id=@id
	end

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




CREATE  PROCEDURE [db_masters].[pr_Savemst_machine] 

    @statementtype nvarchar(50),

	@mst_machine_tvp [db_masters].[mst_machine_tvp] readonly,

	@fixedassetdata_tvp [db_masters].[fixedassetregister_tvp] readonly,

	@userid int=1

AS





BEGIN 

SET QUOTED_IDENTIFIER OFF;

	SET ANSI_NULLS ON; 

	SET NOCOUNT ON;

		declare @id int, @fassetid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)

	BEGIN TRANSACTION

	If (@statementtype='Insert')

		Begin

				

		    insert into [db_masters].[mst_machine] ([MachineName],[MCCatgId],[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],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon])

			Select [MachineName],[MCCatgId],[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],[coid],[boid],[createdby],getdate(),[modifiedby],[modifiedon] from @mst_machine_tvp

				IF @@ERROR <> 0

				BEGIN

				-- Rollback the transaction

				ROLLBACK

				-- Raise an error and return

				RAISERROR ('Error while adding machine 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



						    

			--Entry into fixedassetregister table 

			insert into [db_masters].[fixedassetregister] ([coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],[createdon],[modifiedby],[modifiedon],[mcid])

			Select [coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],getdate(),[modifiedby],[modifiedon],@id

			from @fixedassetdata_tvp WHERE assetno is not null

			IF @@ERROR <> 0

				BEGIN

				-- Rollback the transaction

				ROLLBACK

				-- Raise an error and return

				RAISERROR ('Error while adding fixedassetregister 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 @mst_machine_tvp



			select [MachineName],[MCCatgId],[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],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon]

				from [db_masters].[mst_machine] where id = @id

				 EXCEPT select [MachineName],[MCCatgId],[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],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon]

				 from @mst_machine_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 machine table and checking @@ERROR 

					UPDATE [db_masters].[mst_machine]  set 

					          [MachineName]= a.[MachineName],

                              [MCCatgId]=a.[MCCatgId],

                              [MCSRNo]=a.[MCSRNo],

                              [MCChassisNo]=a.[MCChassisNo],

							  [MCModel]=a.[MCModel],

							  [MCCapacity]=a.[MCCapacity],

							  [MCSupplierId]=a.[MCSupplierId],

							  [MCManufacturer]=a.[MCManufacturer],

							  [MaintBy]=a.[MaintBy],

							  [MainSupplierId]=a.[MainSupplierId],

							  [UnderWty]=a.[UnderWty],

                              [Wtyupto]=a.[Wtyupto],

                              [UnderAMC]=a.[UnderAMC],

                              [AMCFrom]=a.[AMCFrom],

                              [AMCUpto]=a.[AMCUpto],

                              [EmergencyContactNo]=a.[EmergencyContactNo],

                              [LastMaint]=a.[LastMaint],

                              [LMAfterOps]=a.[LMAfterOps],

                              [LastBDownMaint]=a.[LastBDownMaint],

                              [BMAfterOps]=a.[BMAfterOps],

                              [NextMaint]=a.[NextMaint],

                              [NMAfterOps]=a.[NMAfterOps],

                              [SplTools]=a.[SplTools],

                              [SplTeam]=a.[SplTeam],

                              [ProjLifeYY]=a.[ProjLifeYY],

                              [ProjLifeMM]=a.[ProjLifeMM],

                              [ProjLifeOps]=a.[ProjLifeOps],

                              [ActualLifeYY]=a.[ActualLifeYY],

                              [ActualLifeMM]=a.[ActualLifeMM],

                              [ActualLifeOps]=a.[ActualLifeOps],

                              [coid]=a.[coid],

                             [boid]=a.[boid],

                            [createdby]=a.[createdby],

                             [createdon]=a.[createdon],

                            [modifiedby]=a.[modifiedby],

                            [modifiedon]=getdate()

					FROM   @mst_machine_tvp a

					WHERE  [db_masters].[mst_machine].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 machine record.', 16, 1)

							RETURN

						END

				END -- end of row count

  

			Select [coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],[createdon],[modifiedby],[modifiedon],[mcid]

			from [db_masters].[fixedassetregister] where [mcid]=@id

			EXCEPT select [coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],[createdon],[modifiedby],[modifiedon],@id

			from @fixedassetdata_tvp



			SELECT @rowcnt = @@ROWCOUNT



			-- data needs to update if query returns a row  

			IF @rowcnt > 0

				BEGIN -- begin of row count

				

				delete from [db_masters].[fixedassetregister] where [mcid]=@id



				--Entry into fixedassetregister table 

				insert into [db_masters].[fixedassetregister] ([coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],[createdon],[modifiedby],[modifiedon],[mcid])

				Select [coid],[boid],[assetno],[currentloc],[procuredon],[installedon],[operationalon],[createdby],[createdon],[modifiedby],getdate(),@id

				from @fixedassetdata_tvp WHERE assetno>0

					-- updating existing records from fixedassetregister table and checking @@ERROR 

					--UPDATE [db_masters].[fixedassetregister]  set 

					--		  [coid]=a.[coid],

     --                         [boid]=a.[boid],

					--          [assetno]= a.[assetno],

     --                         [currentloc]=a.[currentloc],

     --                         [procuredon]=a.[procuredon],

     --                         [installedon]=a.[installedon],

					--		  [operationalon]=a.[operationalon],

					--		  [createdby]=a.[createdby],

     --                         [createdon]=a.[createdon],

     --                         [modifiedby]=a.[modifiedby],

     --                         [modifiedon]=a.[modifiedon],

					--		  [mcid]=@id

					--FROM   @mst_machine_tvp a

					--WHERE  [db_masters].[mst_machine].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 fixed asset.', 16, 1)

							RETURN

						END

				END -- end of row count



			end

								COMMIT

								

								

								END

GO
/****** Object:  StoredProcedure [db_masters].[pr_SavePODetails]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_masters].[pr_SavePODetails]   	
	@coid int =0,
	@boid  int =0,
	@userid int=0,
	@status char(1),
	@orderid varchar(20),
	@Description varchar(200),
	@orderno varchar(20)
AS
Begin
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;

BEGIN TRANSACTION

Begin
Update [db_mm].[hdr_purchaseorder] set postatus=@status where boid=@boid and orderid=Cast(@Orderid as bigint)
IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while Updating PO table', 16, 1)
				RETURN
				END
--insert into [db_masters].[POHistory] (coid,boid,PO_no,[Description],Fdate,Compdate,createdby,createdon)
--values(@coid,@boid,@orderno,@Description,getdate(),getdate(),@userid,getdate())
--IF @@ERROR <> 0
--				BEGIN
--				-- Rollback the transaction
--				ROLLBACK
--				-- Raise an error and return
--				RAISERROR ('Error while inserting details in POHistory table', 16, 1)
--				RETURN
--				END
End
COMMIT
END


GO
/****** Object:  StoredProcedure [db_masters].[pr_saveprospectcustomer]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_masters].[pr_saveprospectcustomer] 
	@statementtype nvarchar(50),
	@userid int,	
	@fyid int=1,
	@party_tvp [db_masters].[partymaster_tvp] readonly,
	@party_contacts_tvp [db_masters].[party_contactpersons_tvp] readonly,
	@party_bank_tvp [db_masters].[party_bank_tvp] readonly,
	@party_license_tvp [db_masters].[party_licenseinfo_tvp] readonly
AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	-- declare varilable for voucher no and voucher category
	declare @customerid int, @rowcnt int, @countryid int, @stateid int,@cityid int,@coid int, @accountid int,@boid int;
	declare @colstring nvarchar(max), @sql nvarchar(max), @countryname varchar(50), @statename varchar(50), @cityname varchar(50);
	-- STEP 1: Start the transaction
	BEGIN TRANSACTION
	select @countryid=country, @stateid = isnull(state,'0'), @cityid = city,@coid=coid,@countryname=newCountry,@boid=boid,
	@statename=newState, @cityname = newCity from @party_tvp
	if (@countryid=0) -- if countryid is 0, insert new country
	begin
		insert into db_masters.country (coid,boid,countryname,isactive,createdby,createdon) 
			values (@coid,@boid,@countryname,1,@userid,getdate())
		    SELECT @countryid= SCOPE_IDENTITY()
	end
	if (@stateid =0 AND @statename<>'') --  if stateid = 0, insert new state
	begin
		insert into db_masters.statemaster(coid,boid,statename,countryid,isactive,createdby,createdon)
			values (@coid,@boid,@statename,@countryid,1,@userid,getdate())
			select  @stateid = SCOPE_IDENTITY()
	end
	if (@cityid =0 AND @cityname<>'') --  if cityid = 0, insert new city
	begin
		insert into db_masters.city(coid,boid,cityname,countryid,stateid,isactive,createdby,createdon)
			values (@coid,@boid,@cityname,@countryid,@stateid,1,@userid,getdate())
			select @cityid = SCOPE_IDENTITY()
	end
	If (@statementtype='Insert')
		Begin
	        -- insert data in customer table and checking @@ERROR 
			insert into db_masters.prospectcustomers([coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[zone],[area],[region],[vendorcode],[title],[credit_days],[credit_limit],[vat_number],[vat_date]
				,[excise_regn_number],[excise_commissionerate],[excise_division],[excise_range],[currency_preference]
	            ,[eximcode]	,[iecno])
			Select  [coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],@cityid,@stateid,@countryid,[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],@userid,getdate() ,
				 [zone],[area],[region],[vendorcode],[title],[credit_days],[credit_limit],[vat_number],[vat_date]
				,[excise_regn_number] ,[excise_commissionerate]	   ,[excise_division]	   ,[excise_range]	   
				,[currency_preference] ,[eximcode],[iecno]
				 from @party_tvp
			 IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding customer data.', 16, 1)
				RETURN
				END
				SELECT @customerid= SCOPE_IDENTITY()
			-- insert data for supplier banks and checking @@ERROR 
			insert into [db_masters].[prospectcustomer_banks]
			([custid],[bankid],[bankacno],[ifsc],[isactive],[createdby],[createdon])
			Select @customerid ,[bankid],[bankacno],[ifsc],[isactive],@userid,
                   getdate() from @party_bank_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 customer`s bank data.', 16, 1)
				RETURN
				END
			-- insert data for supplier contacts and checking @@ERROR 
			insert into [db_masters].[prospectcustomer_contactpersons]
			([custid],[name],[mobile],[phone],[fax],[email],[isactive],[createdby],[createdon],[position])
			Select @customerid,[name],[mobile],[phone],[fax],[email],[isactive],@userid,getdate(),position
			from @party_contacts_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 prospect data.', 16, 1)
				RETURN
				END
			-- insert data for supplier licenses and checking @@ERROR 
			insert into [db_masters].[prospectcustomer_licenseinfo]([custid],[licensetype],[licenseno],[validtill],[authentication],
				[isactive],[createdby],[createdon])
			Select @customerid,[licensetype],[licenseno],[validtill],[authentication],[isactive],@userid,getdate() 
			from @party_license_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 prospect license data.', 16, 1)
				RETURN
				END
		 End
	Else
		  Begin -- begin of update 
			  select top 1 @customerid = id from @party_tvp
					UPDATE db_masters.prospectcustomers 
						   SET [coid]=a.[coid],
							[boid]=a.[boid],
							[name]=a.[name],
							[categoryid]=a.[categoryid],
						    [segmentid] = a.[segmentid],
							[gsTin]=a.[gsTin],
							[pan]=a.[pan],
							[address1]=a.[address1],
							[address2]=a.[address2],
							[city]=@cityid,
							[state]=@stateid,
							[country]=@countryid,
							[pin]=a.[pin],
							[mobile_number]=a.[mobile_number],
							[phone_number]=a.[phone_number],
							[fax]=a.[fax],
							[email]=a.[email],
							[website]=a.[website],
							[tds_applicable]=a.[tds_applicable],
							[tds_rate]=a.[tds_rate],
							[tcs_applicable]=a.[tcs_applicable],
							[tcs_rate]=a.[tcs_rate],
							[isactive]=a.[isactive],
							[createdby]=a.[createdby],
							[createdon]=a.[createdon],
							[modifiedby]=@userid,
							[modifiedon]=getdate(),
							[deactivatedby]=a.[deactivatedby],
							[deactivatedon] = a.[deactivatedon], 
							[zone]=a.[zone],
							[area]=a.[area],
							[region]=a.[region],
							[vendorcode]=a.[vendorcode],
							[title] =a.[title],
							[credit_days]=a.[credit_days],
							[credit_limit]=a.[credit_limit],
							[vat_number]=a.[vat_number],
							[vat_date]=a.[vat_date],
							[currency_preference] = a.[currency_preference],
                            [excise_regn_number] = a.[excise_regn_number],
                            [excise_commissionerate] = a.[excise_commissionerate],
                            [excise_division] = a.[excise_division],
                            [excise_range] = a.[excise_range],
                            [eximcode]=a.[eximcode],
                            [iecno]=a.[iecno]							
					FROM   @party_tvp a
					WHERE  db_masters.prospectcustomers.id= a.id 
					-- delete existing bank details for this supplier
				   delete from [db_masters].[prospectcustomer_banks] where [custid] = @customerid 
					-- insert data for supplier banks and checking @@ERROR 
				    insert into [db_masters].[prospectcustomer_banks]
					([custid],[bankid],[bankacno],[ifsc],[isactive],[createdby],[createdon])
					Select @customerid ,[bankid],[bankacno],[ifsc],[isactive],@userid, getdate() from @party_bank_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 updating prospect`s bank data.', 16, 1)
						RETURN
						END
				-- End
		        -- select custid,[name],[mobile],[phone],[fax],[email],[isactive] 
		        -- from [db_masters].[customer_contactpersons] 
		        -- where custid =@customerid  
		        -- EXCEPT select @customerid,[name],[mobile],[phone],[fax],[email],[isactive] from @party_contacts_tvp
		        -- SELECT @rowcnt = @@ROWCOUNT
		        -- IF @rowcnt > 0
		        --	Begin
		        -- delete existing bank details for this supplier
				  delete from [db_masters].[prospectcustomer_contactpersons] where [custid] = @customerid 
					-- insert data for supplier banks and checking @@ERROR 
				  insert into [db_masters].[prospectcustomer_contactpersons] 
				  ([custid],[name],[mobile],[phone],[fax],[email],[isactive],[createdby],[createdon],position)
				  Select @customerid,[name],[mobile],[phone],[fax],[email],[isactive],@userid,getdate(),position 
				  from @party_contacts_tvp
			--	END
			--  End
			--  select custid,[licensetype],[licenseno],[validtill],[authentication],[isactive]
			--  from [db_masters].[customer_licenseinfo] where custid =@customerid
	        --  EXCEPT select @customerid,[licensetype],[licenseno],[validtill],[authentication],[isactive] from @party_license_tvp 
			--  SELECT @rowcnt = @@ROWCOUNT
			--  IF @rowcnt > 0
			--	Begin				
			--		-- 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 prospect license info data into log table.', 16, 1)
			--			RETURN
			--		END
			--     delete existing bank details for this supplier
					delete from [db_masters].[prospectcustomer_licenseinfo] where [custid] = @customerid 
					-- insert data for supplier banks and checking @@ERROR 
					insert into [db_masters].[prospectcustomer_licenseinfo]([custid],[licensetype],[licenseno],
					[validtill],[authentication],[isactive],[createdby],[createdon])
					Select @customerid ,[licensetype],[licenseno],[validtill],[authentication],[isactive],@userid, getdate() 
					from @party_license_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 updating prospect`s licenses data.', 16, 1)
						RETURN
						END
				-- End
		  -- End 		
       END
 COMMIT
 	   select Cust.id,Cust.name,CT.cityname city, isnull(Cust.address1,'''') address1, isnull(Cust.address2,'''') address2,
	          Cust.gstin,Cust.mobile_number,Cust.pan,Cust.email,St.statename as state,Cy.countryname as country
	   from [db_masters].[prospectcustomers] Cust
	   left join db_masters.statemaster St on Cust.state = St.id 
	   left join db_masters.country Cy on Cust.country = Cy.id
	   left join db_masters.city CT on Cust.City = CT.Id
	   where cust.id=@customerid 
END
GO
/****** Object:  StoredProcedure [db_masters].[pr_saveprospetoctcustomer]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- exec [db_masters].[pr_saveprospetoctcustomer]  1,1,12

CREATE PROCEDURE [db_masters].[pr_saveprospetoctcustomer] 	
	@userid int,	
	@fyid int=1,
	@custid bigint =0
AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;


------get customer group id from control table     mohit
	DECLARE  @sdebtorsgroupid BIGINT,@accountid BIGINT,@customerid BIGINT SET @sdebtorsgroupid = (SELECT distinct (sdebtorsid)
	FROM db_general.company_control)
-- insert data in accounthead table and checking @@ERROR 

INSERT INTO db_accounts.accountHeads (coid, boid, groupid, accounthead, clbal, opbal, yob)
	SELECT		[coid]	   ,[boid]	   ,isnull(@sdebtorsgroupid,0)	   ,[name]	   ,0
	   ,0	   ,0	 FROM db_masters.prospectcustomers where [id]=@custid

SELECT	@accountid = SCOPE_IDENTITY()

-----insert data into yearopening
INSERT INTO db_accounts.yearopening (coid, boid, accountid, openingbalance, parentgroupid, fyid)
	SELECT		[coid],[boid],@accountid ,0   ,isnull(@sdebtorsgroupid,0),@fyid	
	FROM db_masters.prospectcustomers where [id]=@custid

	-- insert data in customer table and checking @@ERROR 
INSERT INTO db_masters.customer ([coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[zone],[area],[region],[vendorcode],[title],[credit_days],[credit_limit],[vat_number],[vat_date]
				,[excise_regn_number],[excise_commissionerate],[excise_division],[excise_range],[currency_preference]
	            ,[eximcode]	,[iecno],accountid)
 
select  [coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[zone],[area],[region],[vendorcode],[title],[credit_days],[credit_limit],[vat_number],[vat_date]
				,[excise_regn_number],[excise_commissionerate],[excise_division],[excise_range],[currency_preference]
	            ,[eximcode]	,[iecno],@accountid
	    from db_masters.prospectcustomers where [id]=@custid 
			

SELECT 	@customerid = SCOPE_IDENTITY()

update db_accounts.accountHeads set partyid=@customerid where id=@accountid
-- insert data for supplier banks and checking @@ERROR 
INSERT INTO db_general.customer_banks ([custid], [bankid], [bankacno], [ifsc], [isactive], [createdby], [createdon])
	select  @customerid,[bankid],[bankacno],[ifsc],[isactive],@userid,getdate()
	 from  [db_masters].[prospectcustomer_banks] where [custid]=@custid
			


-- insert data for supplier contacts and checking @@ERROR 
 INSERT INTO db_general.customer_contactpersons ([custid], [name], [mobile], [phone], [fax], [email], [isactive]
 , [createdby], [createdon])
 select @customerid,[name],[mobile],[phone],[fax],[email],[isactive],@userid ,GETDATE()
	FROM [db_masters].[prospectcustomer_contactpersons]  where [custid]=@custid

-- insert data for supplier licenses and checking @@ERROR 
 INSERT INTO db_general.customer_licenseinfo ([custid], [licensetype], [licenseno], [validtill], [authentication],
 [isactive], [createdby], [createdon])
 SELECT		@customerid,[licensetype],[licenseno],[validtill],[authentication],[isactive],@userid,GETDATE()
 FROM [db_masters].[prospectcustomer_licenseinfo] where [custid]=@custid

-- 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 customer data.', 16, 1)
RETURN
END

Update db_masters.prospectcustomers set custid=@customerid where id= @custid 

select * from db_masters.customer where id=@customerid

END



GO
/****** Object:  StoredProcedure [db_masters].[pr_savestatus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_masters].[pr_savestatus] 
    @statementtype nvarchar(50),
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@id int=0,
	@colorcode varchar(100),
	@name varchar(100),
	@status varchar(100)
AS
BEGIN
	SET NOCOUNT ON;
	if @statementtype='Insert'
	begin
	 insert into [db_mktg].[mst_enqstatus](status,colorcode,coid,boid,createdby,createdon)
	 values(@status,@colorcode,@boid,1,@userid,getdate())
	end
    else
	begin
	 update [db_mktg].[mst_enqstatus]set status=@status,coid=@coid ,boid=@boid where id=@id
	end

	select * from [db_masters].[Model]
END

GO
/****** Object:  StoredProcedure [db_masters].[pr_savesupplier]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--drop procedure [db_masters].[pr_savesupplier] 
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,19-11-2018>
-- Description:	<Description,save/update supplier data>
-- =============================================

CREATE PROCEDURE [db_masters].[pr_savesupplier] 
	@statementtype nvarchar(50),
	@userid int=1,
	@fyid int=1,
	@party_tvp [db_masters].[partymaster_tvp] readonly,
	@party_contacts_tvp [db_masters].[party_contactpersons_tvp] readonly,
	@party_bank_tvp [db_masters].[party_bank_tvp] readonly,
	@party_license_tvp [db_masters].[party_licenseinfo_tvp] readonly
AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	------get supplier group id from control table     mohit
	DECLARE  @creditergroupid BIGINT
 --   SET @creditergroupid=(SELECT distinct(screditorsid) FROM  db_general.company_control)
	
	-- declare varilable for voucher no and voucher category
	declare @supplierid BIGINT, @rowcnt int, @countryid int, @stateid int,@cityid int,@coid int, @accountid BIGINT,@boid int,@yob decimal, @partyid bigint;
	declare @colstring nvarchar(max), @sql nvarchar(max), @countryname varchar(50), @statename varchar(50), @cityname varchar(50);
	
	-- STEP 1: Start the transaction
	BEGIN TRANSACTION

	select @countryid=country, @stateid = state, @cityid = city,@coid=coid,@countryname=newCountry,@boid=boid,@yob=openingbal
	,@statename=newState,@cityname = newCity from @party_tvp

	------get supplier group id from control table     mohit
	SET @creditergroupid = (SELECT 	(screditorsid)	FROM db_general.company_control where coid=@coid and boid=@boid)

	if (@countryid=0) -- if countryid is 0, insert new country
	begin
		insert into db_masters.country (coid,boid,countryname,isactive,createdby,createdon) 
			values (@coid,@boid,@countryname,1,@userid,getdate())
		SELECT @countryid= SCOPE_IDENTITY()
	end

	if (@stateid =0) --  if stateid = 0, insert new state
	begin
		insert into db_masters.statemaster(coid,boid,statename,countryid,isactive,createdby,createdon)
			values (@coid,@boid,@statename,@countryid,1,@userid,getdate())
			select @stateid = SCOPE_IDENTITY()
	end

	if (@cityid =0) --  if stateid = 0, insert new state
	begin
		insert into db_masters.city(coid,boid,cityname,countryid,stateid,isactive,createdby,createdon)
			values (@coid,@boid,@cityname,@countryid,@stateid,1,@userid,getdate())
			select @cityid = SCOPE_IDENTITY()
	end

	If (@statementtype='Insert')
		Begin
		-- insert data in accounthead table and checking @@ERROR 
			insert into db_accounts.accountHeads (coid,boid,groupid,accounthead,clbal,opbal,yob) 
				select [coid],[boid],@creditergroupid,[name],0,0,@yob from @party_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 opening account head for the supplier.', 16, 1)
				RETURN
				END
		SELECT @accountid= SCOPE_IDENTITY()

		-----insert data into yearopening
				INSERT INTO db_accounts.yearopening(coid,boid,accountid,openingbalance,parentgroupid,fyid)
				SELECT [coid],[boid],@accountid,[openingbal],@creditergroupid,@fyid from @party_tvp
	-- insert data in supplier table and checking @@ERROR 
			insert into db_masters.supplier([coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[accountid],[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],[excise_division]
				,[excise_range],[vendorcode],[title],[vat_number],[vat_date],iecno,eximcode,isdealer,associateacid)
			Select [coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],@cityid,@stateid,@countryid,[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],@userid
				,getdate(),@accountid,[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],[excise_division],
				[excise_range],[vendorcode],[title],[vat_number],[vat_date],iecno,eximcode,isdealer,associateacid FROM @party_tvp
		
			SELECT @partyid= SCOPE_IDENTITY()
		update db_accounts.accountHeads set partyid=@partyid where id=@accountid
		
			-- 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 supplier data.', 16, 1)
				RETURN
				END

				SELECT @supplierid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting supplier id.', 16, 1)
				RETURN
				END
				
				
			
			-- insert data for supplier banks and checking @@ERROR 
		
			insert into db_masters.supplier_banks([suplid],[bankid],[bankacno],[ifsc],[isactive],[createdby],[createdon])
			Select @supplierid,[bankid],[bankacno],[ifsc],[isactive],@userid,
				getdate() from @party_bank_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 supplier`s bank data.', 16, 1)
				RETURN
				END

			-- insert data for supplier contacts and checking @@ERROR 
			
			insert into db_masters.supplier_contactpersons([suplid],[name],[mobile],[phone],[fax],[email],[isactive]
				,[createdby],[createdon],position)
			Select @supplierid,[name],[mobile],[phone],[fax],[email],[isactive],@userid,getdate(),position
			from @party_contacts_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 supplier data.', 16, 1)
				RETURN
				END
				 
			--	select count(*) from @party_license_tvp
			--	EXEC sp_executesql @sql
			--	print @sql
			--SELECT @rowcnt = @@ROWCOUNT
			
			--IF @rowcnt > 0	
			--begin		-- insert data for supplier licenses and checking @@ERROR 
			
		     
			insert into db_masters.supplier_licenseinfo([suplid],[licensetype],[licenseno],[validtill],[authentication],
				[isactive],[createdby],[createdon])
			Select @supplierid,[licensetype],[licenseno],[validtill],[authentication],[isactive],@userid,getdate() 
			from @party_license_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 supplier license data.', 16, 1)
				RETURN
				END



				END 

		
	Else
		Begin -- begin of update 
			-- fetching supplier id from table type
			select top 1 @supplierid = id from @party_tvp
			--print @supplierid
			--check for changes in row data 
			select [coid],[boid],[name],[categoryid],[segmentid]
			,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],
				[excise_division],[excise_range],[vendorcode],[title] from db_masters.supplier 
				where id =@supplierid
				 EXCEPT select [coid],[boid],[name],[categoryid],[segmentid]
			,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],
				[excise_division],[excise_range],[vendorcode],[title] from @party_tvp
			
			

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_masters.supplier(id,[coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],
				[excise_division],[excise_range],[vendorcode],[title],[modifiedby]) 
					Select id,[coid],[boid],[name],[categoryid],[segmentid]
				,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
				,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
				,[createdon],[credit_days],[credit_limit],[currency_preference],[excise_regn_number],[excise_commissionerate],
				[excise_division],[excise_range],[vendorcode],[title],@userid from db_masters.supplier 
				where id = @supplierid

					--print @sql

					--EXEC sp_executesql @sql

					-- 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
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_masters.supplier 
						SET [coid]=a.[coid],
							[boid]=a.[boid],
							[name]=a.[name],
							[categoryid]=a.[categoryid],
							[segmentid] =a.[segmentid] ,
							[gsTin]=a.[gsTin],
							[pan]=a.[pan],
							[address1]=a.[address1],
							[address2]=a.[address2],
							[city]=@cityid,
							[state]=@stateid,
							[country]=@countryid,
							[pin]=a.[pin],
							[mobile_number]=a.[mobile_number],
							[phone_number]=a.[phone_number],
							[fax]=a.[fax],
							[email]=a.[email],
							[website]=a.[website],
							[tds_applicable]=a.[tds_applicable],
							[tds_rate]=a.[tds_rate],
							[tcs_applicable]=a.[tcs_applicable],
							[tcs_rate]=a.[tcs_rate],
							[isactive]=a.[isactive],
							[modifiedby]=@userid,
							[modifiedon]=getdate(),
							[deactivatedby]=a.[deactivatedby],
							[deactivatedon] = a.[deactivatedon],
							[credit_days] = a.[credit_days],
							[credit_limit] = a.[credit_limit],
							[currency_preference]=a.[currency_preference],
							[excise_regn_number]=a.[excise_regn_number],
							[excise_commissionerate]=a.[excise_commissionerate],
							[excise_division]=a.[excise_division],
							[excise_range]=a.[excise_range],
							[vendorcode]=a.[vendorcode],
							[title]=a.[title],
							[vat_number]=a.[vat_number],
							[vat_date]=a.[vat_date],
							isdealer=a.isdealer,
							associateacid=a.associateacid
					FROM   @party_tvp a
					WHERE  db_masters.supplier.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 supplier record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select id from CloudERPbklog.db_masters.supplier where id = @supplierid)
						begin
							-- insert data in supplier table and checking @@ERROR 
							insert into CloudERPbklog.db_masters.supplier([id],[coid],[boid],[name],[categoryid],[segmentid]
								,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number],[phone_number],[fax]
								,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
								,[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[credit_days],[credit_limit],[currency_preference])
							Select [id],[coid],[boid],[name],[categoryid],[segmentid]
								,[gsTin],[pan],[address1],[address2],[city],[state],[country],[pin],[mobile_number]
								, [phone_number],[fax]
								,[email],[website],[tds_applicable],[tds_rate],[tcs_applicable],[tcs_rate],[isactive],[createdby]
								,[createdon],@userid,getdate(),[deactivatedby],[deactivatedon],[credit_days],[credit_limit],[currency_preference] 
								from db_masters.supplier where ID = @supplierid
							-- 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 supplier data.', 16, 1)
								RETURN
								END
						end
				End
			

			-- check for changes in supplier bank details

			
			select [suplid],[bankid],[bankacno],[ifsc],[isactive]  
						from [db_masters].[supplier_banks] where [suplid] =@supplierid
						 EXCEPT select @supplierid,[bankid],[bankacno],[ifsc],[isactive] from @party_bank_tvp

			SELECT @rowcnt = @@ROWCOUNT
			
			IF @rowcnt > 0
				Begin
					-- insert data needs to log table if query returns a row  
					insert into CloudERPbklog.db_masters.supplier_banks([id],[suplid],[bankname],[bankacno],[ifsc],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon])
					Select [id],[suplid],[bankid],[bankacno],[ifsc],[isactive],[createdby],[createdon],@userid,getdate(),[deactivatedby],
						[deactivatedon] from db_masters.supplier_banks where [suplid] = @supplierid 
					
					-- 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 supplier bank data into log table.', 16, 1)
						RETURN
						END
					--delete existing bank details for this supplier
					delete from db_masters.supplier_banks where [suplid] = @supplierid 

					-- insert data for supplier banks and checking @@ERROR 
					insert into db_masters.supplier_banks([suplid],[bankid],[bankacno],[ifsc],[isactive],[createdby],[createdon])
					Select @supplierid ,[bankid],[bankacno],[ifsc],[isactive],@userid,
						getdate() from @party_bank_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 updating supplier`s bank data.', 16, 1)
						RETURN
						END
				End

			-- check for changes in supplier contacts

			-- defining column list of supplier contact persons table
			--set @colstring = '[id],[suplid],[name],[mobile],[phone],[fax],[email],[website],[isactive]'
				-- creating dynamic query to check for changes in row data 
			select [suplid],[name],[mobile],[phone],[fax],[email],[isactive] 
			from [db_masters].[supplier_contactpersons] 
			where [suplid] =@supplierid 
			 EXCEPT select @supplierid, [name],[mobile],[phone],[fax],[email],[isactive] from @party_contacts_tvp
			
			
			SELECT @rowcnt = @@ROWCOUNT
			
			IF @rowcnt > 0
				Begin
					-- insert data needs to log table if query returns a row  
					insert into CloudERPbklog.db_masters.supplier_contactpersons([id],[suplid],[name],[mobile],[phone],[fax],
					[email],[website],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon])
					Select [id],[suplid],[name],[mobile],[phone],[fax],[email],[website],[isactive],[createdby],[createdon],@userid,getdate(),[deactivatedby],
						[deactivatedon] from db_masters.supplier_contactpersons where [suplid] = @supplierid 
					
					-- 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 supplier contact persons data into log table.', 16, 1)
						RETURN
						END
					--delete existing bank details for this supplier
					delete from db_masters.supplier_contactpersons where [suplid] = @supplierid 

					-- insert data for supplier banks and checking @@ERROR 
					insert into db_masters.supplier_contactpersons([suplid],[name],[mobile],[phone],[fax],[email],
						[isactive],[createdby],[createdon],position)
					Select @supplierid ,[name],[mobile],[phone],[fax],[email],[isactive],@userid,
						getdate(),position from @party_contacts_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 updating supplier`s contact persons data.', 16, 1)
						RETURN
						END
				End
			
			-- check for changes in supplier licenses
			select [suplid],[licensetype],[licenseno],[validtill],[authentication],[isactive] 
			FROM [db_masters].[supplier_licenseinfo] 
			where [suplid] =@supplierid
			 EXCEPT select @supplierid,[licensetype],[licenseno],[validtill],[authentication],[isactive] from @party_license_tvp
			
			
			SELECT @rowcnt = @@ROWCOUNT
			
			IF @rowcnt > 0
				Begin
					-- insert data needs to log table if query returns a row  
					insert into CloudERPbklog.db_masters.supplier_licenseinfo([id],[suplid],[licensetype],[licenseno],
					[validtill],[authentication],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon])
					Select [id],[suplid],[licensetype],[licenseno],[validtill],[authentication],[isactive],[createdby],[createdon],@userid,getdate(),[deactivatedby],
						[deactivatedon] from db_masters.supplier_licenseinfo where [suplid] = @supplierid 
					
					-- 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 supplier license info data into log table.', 16, 1)
						RETURN
						END
					--delete existing bank details for this supplier
					delete from db_masters.supplier_licenseinfo where [suplid] = @supplierid 

					-- insert data for supplier banks and checking @@ERROR 
					insert into db_masters.supplier_licenseinfo([suplid],[licensetype],[licenseno],
					[validtill],[authentication],[isactive],[createdby],[createdon])
					Select @supplierid ,[licensetype],[licenseno],[validtill],[authentication],[isactive],@userid,
						getdate() from @party_license_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 updating supplier`s licenses data.', 16, 1)
						RETURN
						END
				End
		End -- end of update 	
		-- If we reach this point, the commands completed successfully
		--Commit the transaction....
		COMMIT
END






GO
/****** Object:  StoredProcedure [db_masters].[pr_saveuser]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- drop procedure [db_masters].[pr_saveuser] 
-- =============================================
-- Author:		<Author,,Amit>
-- Create date: <Create Date,20-02-2019>
-- Description:	<Description,save/update user data>
-- =============================================

CREATE PROCEDURE [db_masters].[pr_saveuser] 
	@statementtype nvarchar(50),
	@userid int=1,
	@user_tvp [db_masters].[users_tvp] readonly,
	@userbranches_tvp [db_general].[user_branches_tvp] readonly,
	@accesstoken varchar(100)
AS
BEGIN 
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	declare @nuserid int, @rowcnt int, @designationid int, @departmentid int,@coid int,@boid int,@useid int;
	declare @colstring nvarchar(max), @sql nvarchar(max), @designation varchar(50), @department varchar(50);
	select @designationid=designationid, @departmentid = departmentid, @designation = designation,
	@department=department, @coid=coid,@boid=boid,@nuserid = userid from @user_tvp
	-- STEP 1: Start the transaction
	BEGIN TRANSACTION
	if (@designationid=0) -- if @designationid is 0, insert new designation
	begin
		insert into db_masters.designations (coid,boid, designation,isactive,createdby,createdon) 
			values (@coid,@boid,@designation,1,@userid,getdate())
		SELECT @designationid= SCOPE_IDENTITY()
	end
	if (@departmentid =0) --  if departmentid = 0, insert new department
	begin
		insert into db_masters.department(coid,boid,deptname,isactive,createdby,createdon)
			values (@coid,@boid,@department,1,@userid,getdate())
			select @departmentid = SCOPE_IDENTITY()
	end
	If (@statementtype='Insert')
		Begin
		-- insert data in user and checking @@ERROR 
			insert into db_masters.users (coid,boid,firstname,lastname,emailid,username,usrpwd,isActive,createdby,createdon,
			designationid,departmentid,mobileuser,shifttimein,shifttimeout,mobileno) 
				select [coid],[boid],firstname,lastname,emailid,username,usrpwd,isActive,@userid,getdate(), 
				@designationid,@departmentid,mobileuser,shifttimein,shifttimeout,mobile from @user_tvp
				SELECT @useid= SCOPE_IDENTITY()
				insert into db_general.user_branches( userid, boid, coid, isactive,reportingto,roleid, createdby, createdon)
			select @useid, [boid],[coid],isActive,isnull(reportingto,0),isnull(roleid,0), @userid,getdate() from @userbranches_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 creating user.', 16, 1)
				RETURN
				END
		End
	Else
		Begin -- begin of update 
			UPDATE db_masters.users 
				SET [coid]=a.[coid],
						[boid]=a.[boid],
						[firstname]=a.[firstname],
						[lastname]=a.[lastname],
						[emailid] =a.[emailid] ,
						[username]=a.[username],
						[usrpwd]=a.[usrpwd],
						[departmentid]=@departmentid,
						[designationid]=@designationid,
						[mobileuser]=a.[mobileuser],
						[modifiedby]=@userid,
						[modifiedon]=getdate(),
						[shifttimein]= a.[shifttimein],
						[shifttimeout]= a.[shifttimeout],
						[mobileno]=a.[mobile]
				FROM   @user_tvp a
				WHERE db_masters.users.userid= a.userid 
				-- 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 user record.', 16, 1)
						RETURN
					END*/
				--( userid, boid, coid, isactive,reportingto,roleid, createdby, createdon)
				delete from db_general.user_branches where boid not in (select boid from @userbranches_tvp) and userid = @nuserid 

				update db_general.user_branches set 
				userid = a.userid, boid= a.boid, coid = a.coid, isactive= a.isactive,
				reportingto= a.reportingto, roleid = isnull(a.roleid,0), modifiedby = @userid, modifiedon = getdate() 
				from @userbranches_tvp a where db_general.user_branches.boid =a.boid 
				and db_general.user_branches.userid = a.userid

				insert into db_general.user_branches( userid, boid, coid, isactive,reportingto,roleid, createdby, createdon)
				select userid, [boid],[coid],isActive,isnull(reportingto,0),isnull(roleid,0), @userid,getdate() from @userbranches_tvp where id =0
		End -- end of update 	
		-- If we reach this point, the commands completed successfully
		--Commit the transaction....
		COMMIT
END

GO
/****** Object:  StoredProcedure [db_masters].[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_masters].[pr_vouchercategory] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;

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



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

Create PROCEDURE [db_mktg].[pr_changestatus]
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@status int
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100)
	BEGIN TRANSACTION 
	  Update [db_mktg].hdr_enq set enqstatus = @status where id = @enqid	
   commit
END

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

-- exec [db_mktg].[pr_checkduplicate_customer_prospect_supplier_emailphone] 1,1,1,'C','','mohitkhatana111@gmail.com'


CREATE PROCEDURE [db_mktg].[pr_checkduplicate_customer_prospect_supplier_emailphone]
    @coid int,
	@boid int,
	@userid int,
	@type char(1),	
	@phone varchar(20)='0',
	@email varchar(200)=null,
	@id int=0

AS

BEGIN

	SET NOCOUNT ON;

	declare @sql nvarchar(max);
	declare @tablename nvarchar(max);

	if @type='C'
	begin
	set @tablename='[db_masters].[customer]'
	end 
	else if (@type='P')
	begin
	set @tablename='[db_masters].[prospectcustomers]'
	end 
	else if (@type='S')
	begin
	set @tablename='[db_masters].supplier'
	end 
	set @sql= 'select count(id) count
	from ' + @tablename + ' Cust'
	set @sql += ' where cust.coid = '+ cast(@coid as varchar(5)) +' and cust.boid='+ cast(@boid as varchar(5))+''
		IF (@id <>'' and @id is not null and @id !=0)
	BEGIN
	set @sql += ' and Cust.id !='+ cast(@id as varchar(200))+''
	End	
	IF (@phone <>'0' and  @phone is not null)
	BEGIN
	set @sql += ' and Cust.mobile_number ='''+ cast(@phone as varchar(20))+''' or Cust.phone_number ='''+ cast(@phone as varchar(20))+''' '
	End
	else	IF (@email <>'-' and @email is not null)
	BEGIN
	set @sql += ' and Cust.email ='''+ cast(@email as varchar(200))+''''
	End
	

	print @SQL
 
	EXEC sp_executesql @SQL

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

-- [db_mktg].[pr_checkenquiryactions] 28,1,1,1

CREATE PROCEDURE [db_mktg].[pr_checkenquiryactions]
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
    
	-- select enqid,dealerid from [db_mktg].[fwdtodealer_enq] where enqid=@enqid

	-- select enqid,deptid   from [db_mktg].[fwdtodepartment_enq] where enqid=@enqid

    --   select case 
	--when hdr.ishold=1 and hdr.holdremark <>''  then 'Hold'
	--when hdr.rejectionid >0 and hdr.rejectionremark <>'' then 'Reject'
	--when dl.dealerid <> '' then 'Fwd to dealer'
	--when dt.deptid <> '' then 'Fwd to dept'
	--when hdr.intimationto <> '' then 'Intimated'
	--else '' end as [status],holddate,holdremark,rejectionid,rejectionremark,intimationto,dl.dealerid,dt.deptid
	--from [db_mktg].[hdr_enq] hdr
	--left join [db_mktg].[fwdtodealer_enq] dl on hdr.id =dl.enqid
	--left join [db_mktg].[fwdtodepartment_enq] dt on hdr.id = dt.enqid
	--where hdr.id=@enqid

   	 --get Dealer
     select id,name,email from db_masters.supplier where isdealer=1
   
    --get Intimation
     select userid, isnull(firstname,'') + isnull(lastname,'') empname from db_masters.users 
   
    --get Department
     select id,deptname from db_masters.department
   
    --get Reject reason
     select id,name as rejectreason from [db_mktg].[mst_rejectreason]

	  --get 
	 select id,status as [status] from db_mktg.mst_enqstatus 

END


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


-- [db_mktg].[pr_checkquoteactions] 17,1,1,1

CREATE PROCEDURE [db_mktg].[pr_checkquoteactions]
	@quoteid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
    
	-- select enqid,dealerid from [db_mktg].[fwdtodealer_enq] where enqid=@enqid

	-- select enqid,deptid   from [db_mktg].[fwdtodepartment_enq] where enqid=@enqid

    --   select case 
	--when hdr.ishold=1 and hdr.holdremark <>''  then 'Hold'
	--when hdr.rejectionid >0 and hdr.rejectionremark <>'' then 'Reject'
	--when dl.dealerid <> '' then 'Fwd to dealer'
	--when dt.deptid <> '' then 'Fwd to dept'
	--when hdr.intimationto <> '' then 'Intimated'
	--else '' end as [status],holddate,holdremark,rejectionid,rejectionremark,intimationto,dl.dealerid,dt.deptid
	--from [db_mktg].[hdr_enq] hdr
	--left join [db_mktg].[fwdtodealer_enq] dl on hdr.id =dl.enqid
	--left join [db_mktg].[fwdtodepartment_enq] dt on hdr.id = dt.enqid
	--where hdr.id=@enqid

   	 --get Dealer
     select id,name,email from db_masters.supplier where isdealer=1
   
    --get Intimation
     select userid, isnull(firstname,'') + isnull(lastname,'') empname from db_masters.users 
   
    --get Department
     select id,deptname from db_masters.department
   
    --get Reject reason
     select id,name as rejectreason from [db_mktg].[mst_rejectreason]

	  --get 
	 select id,status as [status] from db_mktg.mst_enqstatus 

END



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

CREATE PROCEDURE [db_mktg].[pr_commonapi_quotepi]
	@coid int,
	@boid int,
	@fyid int = null,
	@userid int=1
	-- @token varchar(200)=null
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;
   --get Max No
    SELECT ISNULL(MAX(pino), 0) as pinno from [db_mktg].hdr_quote_pi where coid=@coid and boid=@boid  and fyid=@fyid 
   
    -- get buisnesssegment
    -- select id,businesssegementname from db_masters.businesssegement where parentid=0
	select id,businesssegementname,
	case when businesssegementname ='Export' then 'E'
	else '' end as type
	from db_masters.businesssegement where parentid=0

	--get Payment Terms
    select id paymenttermid,name paymentterm,srno from [db_mktg].[mst_paymentterms]

 
	--get terms condition
	select termsandcondition =stuff((select '','' + name from [db_mktg].[mst_termsandconditions]  FOR XML PATH ('br')), 1, 0, '')
    --select id as termsandconditionsid,name as termsandcondition , srno from [db_mktg].[mst_termsandconditions] WHERE isexport IS null

	--get document
	select userid,firstname from [db_masters].[users]

    --get HSN
     Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	 from [db_mm].[mst_gst] h join 
     db_mm.mst_hsn g on h.gstid=g.gstid
	 where h.coid = @coid and h.boid = @boid 
	 order by hsncode asc


	 select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	 join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	 join  [db_mm].[mst_gst] g on m.gstid=g.gstid
	 --get UOM master
	 select id, uom from [db_mm].[mst_itemuom] where isactive=1
	 ---get Currency master
	 SELECT id,ordertype FROM db_sop.mst_ordertype  where coid=@coid and boid =@boid and fyid=@fyid

     SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
end	

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

-- exec [db_mktg].[pr_commonapienq] 1,1,1

CREATE PROCEDURE [db_mktg].[pr_commonapienq]
	@coid int,
	@boid int,
	@fyid int = null,
	@search varchar(50)='',
	@userid int=1,
	@token varchar(500)=''
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;

   --get Max No
    SELECT ISNULL(MAX(enqno), 0) as enqno from [db_mktg].hdr_enq where coid=@coid and boid=@boid  and fyid=@fyid 

   --get buisnesssegment
   	select id,businesssegementname,
	case when businesssegementname ='Export' then 'E'
	else '' end as type
	from db_masters.businesssegement where parentid=0


   --get quoteStage
    select id,name from [db_mktg].[mst_quotestage] order by name

	--get document
	select userid,firstname from [db_masters].[users] where issale=1

	select id ,name as Sourcename from [db_mktg].[mst_enqsource] 

	select id , name as bsize from [db_mktg].[mst_buisnesssize]
 
	select id ,name as enqtype from [db_mktg].[mst_enquirytype] enqlist where enqlist.id in (select categoryid from [db_mktg].[enquirycategory_userrights] where userid   in
			(select * from dbo.fngetchilduserids( @userid))) order by id

	select id ,[status] as enqstatus from db_mktg.mst_enqstatus

	-- get cust type
	-- select id,categoryname as custtype from db_masters.customer_category
	     select * from db_mm.mst_itemuom	
end	



GO
/****** Object:  StoredProcedure [db_mktg].[pr_commonapienquirycategoryrights]    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_commonapienquirycategoryrights] 1,1
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_commonapienquirycategoryrights] 
	@coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	select firstname, lastname, username, userid from db_masters.users
	where isactive=1 and departmentid = (select saledeptid from db_general.company_control where coid = @coid and boid =@boid)
	IF OBJECT_ID('tempdb..#tempcategorylist') IS NOT NULL DROP TABLE #tempcategorylist
	create table #tempcategorylist(
	userid int,
	enqtypeid	int,
	enqtypename	varchar(100),
	checked bit
	)
	insert into #tempcategorylist
	select users.userid, et.id,et.name,0  from db_masters.users, db_mktg.mst_enquirytype et 
	where users.coid = @coid and users.boid = @boid and users.departmentid = (select saledeptid from db_general.company_control 
	where coid = @coid and boid =@boid)
	update #tempcategorylist set checked = 1 from
	(select userid, categoryid from [db_mktg].[enquirycategory_userrights]) a 
	where #tempcategorylist.userid = a.userid and enqtypeid = a.categoryid
	select * from #tempcategorylist order by userid, enqtypeid
end

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

-- exec [db_mktg].[pr_commonapiquote] 1,1,1

CREATE PROCEDURE [db_mktg].[pr_commonapiquote]
	@coid int,
	@boid int,
	@fyid int = null,
	@search varchar(50)='',
	@userid int=1,
	@token varchar(200)=null
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;

   --get Max No
    SELECT ISNULL(MAX(quoteno), 0) as quoteno from [db_mktg].hdr_quote where coid=@coid and boid=@boid  and fyid=@fyid 
	
   --get buisnesssegment
    --select id,businesssegementname from db_masters.businesssegement where parentid=0
	select id,businesssegementname,
	case when businesssegementname ='Export' then 'E'
	else '' end as type
	from db_masters.businesssegement where parentid=0


   --get quoteStage
    select id,name from [db_mktg].[mst_quotestage]

	--get Payment Terms
    select id paymenttermid,name paymentterm,srno from [db_mktg].[mst_paymentterms]

	--get Installation info
    select id as installationid,name as installationinfo from [db_mktg].[mst_installationinfo]

	--get terms condition
	
	select termsandcondition =stuff((select '','' + name from [db_mktg].[mst_termsandconditions]  FOR XML PATH ('br')), 1, 0, '')
	
    --select id as termsandconditionsid,name as termsandcondition , srno from [db_mktg].[mst_termsandconditions] WHERE isexport IS null

	--get document reqd
	select id as documentid,name as documentinfo, srno  from [db_mktg].[mst_documentsreqd]

	--get document
	select userid,firstname from [db_masters].[users]

	--get HSN
	-- Select [description],[hsncode],[igst],[sgst],[cgst],gstid from [db_mm].[mst_gst] 
     Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	 from [db_mm].[mst_gst] h join 
     db_mm.mst_hsn g on h.gstid=g.gstid
	 where h.coid = @coid and h.boid = @boid 
	 order by hsncode asc

	 Select * from db_mktg.mst_quoteratetype 

	 select * from db_mm.mst_itemuom
	   
	 select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	 join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	 join  [db_mm].[mst_gst] g on m.gstid=g.gstid

	
	--get UOM master

	select id, uom from [db_mm].[mst_itemuom] where isactive=1

	---get Currency master

	SELECT id,ordertype FROM db_sop.mst_ordertype  where coid=@coid and boid =@boid and fyid=@fyid

    SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
		
end	

GO
/****** Object:  StoredProcedure [db_mktg].[pr_convertquote_to_pi]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mktg].[pr_convertquote_to_pi]
@statementtype NVARCHAR(50),
@quoteid bigint,
@userid bigint = 1,
@fyid int=null,
@coid int=null,
@boid int=null
AS
BEGIN

	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @piid bigint,@rowcnt INT,@colstring NVARCHAR(MAX),@sql NVARCHAR(MAX)
	DECLARE @invno bigint,@pinno bigint
	DECLARE @concessionaltax bit

	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN	
		 set @pinno = (Select ISNULL(MAX(pino),0) + 1 from [db_mktg].[hdr_quote_pi])
		 insert INTO db_mktg.hdr_quote_pi 
		 (pino,pidate,quoteid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],
		 pin,customergstno,country,quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,
		 roundoff,userid,cancelledon,cancelledbyuserid,remarks,coid,boid,fyid,createdby,createdon,modifiedby,modifiedon,
		 invoicetype,senderinfo,isconverttoorder,ordertype,conversionrate,Currency)	

	     select @pinno,getdate(),quoteid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],
		 pin,customergstno,country,quoteno,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,
		 roundoff,userid,cancelledon,cancelledbyuserid,remarks,coid,boid,fyid,createdby,createdon,modifiedby,modifiedon,
		 invoicetype,senderinfo,isconverttoorder,ordertype,conversionrate,Currency
         from [db_mktg].[hdr_quote] where quoteid = @quoteid
		 IF @@error <> 0
		 BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice header data.', 16, 1)
			RETURN
		 END
		 set @piid = SCOPE_IDENTITY()
		 INSERT INTO db_mktg.dtl_quote_pi
		 (piid,itemid,billingdescription,uom,gstid,igstrate,sgstrate,cgstrate,cessrate,basicamount,mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,cessamt,totalamt,remarks,focqty,hsnid)
		
		 select @piid,itemid,billingdescription,uom,isnull(gstid,0),igstrate,sgstrate,cgstrate,cessrate,basicamount,mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,cessamt,totalamt,remarks,focqty,hsnid
	     from  [db_mktg].dtl_quote where quoteid = @quoteid
		
		 --payment terms 
		 insert into [db_mktg].[quote_pi_paymentterms]
		 (piid,paymenttermid,paymentterm,createdby,createdon,[percent],amount)
		 select @piid,id, name,@userid,getdate(),1,1 from db_mktg.mst_paymentterms

		 --terms condition 
		 insert into [db_mktg].[quote_pi_termsandconditions]
		 (piid,termsandconditionsid,termsandcondition,createdby,createdon)
		 select @piid,id,name,@userid,getdate() from db_mktg.mst_termsandconditions

		 --levies


	  END
	  	   
	    Update db_mktg.hdr_quote set isconverttoinvoice = 1 where quoteid=@quoteid

   COMMIT
     
	 select @piid as piid
  END

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

-- exec [db_mktg].[pr_convertquotetoorder] 'Insert',177,1 

CREATE PROCEDURE [db_mktg].[pr_convertquotetoorder]
@statementtype NVARCHAR(50),
@quoteid bigint,
@userid INT = 1
AS
BEGIN

	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;

	DECLARE @invid bigint,@rowcnt INT,@colstring NVARCHAR(MAX),@custid bigint,@fyid int,@sql NVARCHAR(MAX),@custtype CHAR(1)
	DECLARE @oaid bigint,@ordernumber bigint
	DECLARE @concessionaltax bit,@tempitemcount int

	BEGIN TRANSACTION
   
	IF (@statementtype = 'Insert')
	BEGIN
	select @custid=[customerid],@fyid=fyid ,@custtype=custtype from  [db_mktg].[hdr_quote]	where quoteid = @quoteid
	 set @tempitemcount=(select count(itemid) from  [db_mktg].dtl_quote where itemtype='T' and  quoteid = @quoteid)
	if (@tempitemcount>0)
	begin
	select 'This Offer/Quotation contains some Temp. Items. Please Convert these into Regular Items first.' 
	end
	else
	begin
	set @ordernumber =  (SELECT ISNULL(MAX(oano), 0) + 1 FROM [db_sop].[hdr_saleorder])
	print @ordernumber
	if (@custtype='P')
	begin
		
	exec [db_masters].[pr_saveprospetoctcustomer] @userid ,@fyid,@custid

	insert into [db_sop].[hdr_saleorder] ([oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],
			[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],
			[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],
			[approvedbymarketingheaduserid],[approvedbycommercialuserid],[remarks],[coid],[boid],[fyid],[createdby],[createdon],[ordertype],[marketexecutive],[currency],country)

	    select @ordernumber,getdate(),[custid],[customername],customeraddr1,customeraddr2,q.city,
		q.[state],q.pin,[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
		[customercontactpersondepartment],[quoteno],[quotedate],basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,userid,
	    approvedbymarketingheaduserid,approvedbycommercialuserid,remarks,q.coid,q.boid,fyid,
	    @userid,getdate(),1,@userid,q.Currency,co.id
        from  [db_mktg].[hdr_quote] q
		join db_masters.prospectcustomers c on q.customerid=c.id
		left join db_masters.country co on c.country=co.id
		where quoteid = @quoteid
	end
	else 
	begin 
	insert into [db_sop].[hdr_saleorder] ([oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],
			[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],
			[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],
			[approvedbymarketingheaduserid],[approvedbycommercialuserid],[remarks],[coid],[boid],[fyid],[createdby],[createdon],[ordertype],[marketexecutive],[currency],country)

	    select @ordernumber,getdate(),c.[id],[customername],customeraddr1,customeraddr2,q.city,
		q.[state],q.pin,[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
		[customercontactpersondepartment],[quoteno],[quotedate],basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,userid,
	    approvedbymarketingheaduserid,approvedbycommercialuserid,remarks,q.coid,q.boid,fyid,
	    @userid,getdate(),1,@userid,q.Currency,co.id
        from  [db_mktg].[hdr_quote] q
		join db_masters.customer c on q.customerid=c.id
		left join db_masters.country co on c.country=co.id
		where quoteid = @quoteid
	end 
	
	 
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK

			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice header data.', 16, 1)
			RETURN
		END

	
		 set @oaid = SCOPE_IDENTITY()		
		-- add transaction details
		insert into [db_sop].[dtl_saleorder] ([oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],
		[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty])

		select @oaid,itemid,billingdescription,isfoc,issample,specialcode,packing,uom,gstid,igstrate,sgstrate,cgstrate,cessrate,basicamount,
		rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,
		       netamt,igstamt,cgstamt,sgstamt,cessamt,totalamt,remarks,[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty]
	    from  [db_mktg].dtl_quote where quoteid = @quoteid
			 
			 
			 insert into [db_sop].[order_paymentterms] ([orderid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[coid],[boid],[percent],[amount])          
		                                        select  @oaid,[srno],isnull([paymenttermid],0),isnull([paymentterm],' '),@userid,getdate(),[coid],[boid],[percent],[amount]
												 from [db_mktg].[quote_paymentterms] where [quoteid]=	@quoteid  		  	
	  
	  -- INSERT TERMS AND CONDITIONS
	  insert into [db_sop].[order_termsandconditions] ([orderid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon])
				                               select  @oaid,[srno],[termsandconditionsid],[termsandcondition],@userid,getdate() 
											   from [db_mktg].[quote_termsandconditions] where [quoteid]=	@quoteid  
				-- INSERT DOCUMENT REQUIRED
	  insert into [db_sop].[order_documentsreqd]([orderid],[srno],[documentid],[documentinfo],[createdby],[createdon])
			                              select @oaid,[srno],[documentid],[documentinfo],@userid,getdate() 
										  from [db_mktg].[quote_documentsreqd] where [quoteid]=	@quoteid  
				-- INSERT INSTALLATION INFORMATION
	 insert into [db_sop].[order_installationinfo] ([orderid],[srno],[installationid],[installationinfo],[createdby],[createdon])
				                             select @oaid,[srno],[installationid],[installationinfo],@userid,getdate()
											  from [db_mktg].[quote_installationinfo] where [quoteid]=	@quoteid  
				
	  
	   Update db_mktg.hdr_quote set isconverttoorder = 1 where quoteid=@quoteid
	   select oaid from [db_sop].[hdr_saleorder] where oaid=@oaid
	   END END
   COMMIT
  


  END

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

-- select * from  db_masters.businesssegement

-- exec [db_mktg].[pr_getbsegmentchild] 1,1,1,1

CREATE PROCEDURE [db_mktg].[pr_getbsegmentchild]
	@coid int,
	@boid int,
	@fyid int = null,
	@parentid varchar(50)=''
	as
BEGIN
declare @sql nvarchar(max);
SET NOCOUNT ON;
	 
   select id,businesssegementname name from db_masters.businesssegement where parentid = @parentid
	    	
end	
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getcustomerorprspect]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_getcustomerorprspect] 1,200,1,1,'P',''

CREATE PROCEDURE [db_mktg].[pr_getcustomerorprspect]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@type char(1),
	@search varchar(100)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @tablename nvarchar(max);
	if @type='C'
	begin
	set @tablename='[db_masters].[customer]'
	end
 if @type='P'
	begin
	set @tablename='[db_masters].[prospectcustomers]'
	end
	if @type='S'
	begin
	set @tablename='[db_masters].[supplier]'
	end
	begin
	set @sql= 'select Cust.id,Cust.name,CT.cityname city, isnull(Cust.address1,'''') address1, isnull(Cust.address2,'''') address2,
	       Cust.gstin,Cust.mobile_number,Cust.pan,Cust.email,St.statename as state,
		   Cy.countryname as country,cy.id as countryid,isnull(Cust.currency_preference,'''') as currency,segmentid as bsegment
	from '+ @tablename +' Cust
	left join db_masters.statemaster St on Cust.state = St.id 
	left join db_masters.country Cy on Cust.country = Cy.id
	left join db_masters.city CT on Cust.City = CT.Id'
	--where Cust.createdby in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))'
	set @sql += ' where cust.coid = '+ cast(@coid as varchar(5)) +' and cust.boid='+ cast(@boid as varchar(5))+''
	if(@search!='')
		begin
		 set @sql += ' and cust.name 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 id as termsandconditionsid,name as termsandcondition , srno,isexport from [db_mktg].[mst_termsandconditions] 
END
end
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenqfollowup]    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,10
-- =============================================

Create PROCEDURE [db_mktg].[pr_getenqfollowup] 
	@coid int,
	@boid int,
	@enqid int
AS
BEGIN
SET NOCOUNT ON;
   
	Select ih.id,[ih].[enqno], [ih].[enqdate],ih.enqsourceid,ih.enqtype,ih.custtype,ih.marketexecutive,ih.fwdmarketexcecutive,ih.businesssegment,ih.enqstage,
	ih.buisnesssizeid,ih.[customerid],ih.[customername],ih.[customeraddr1],ih.[customeraddr2],ih.[city],ih.[state],ih.[pin],cn.countryname as customercountry,
	ih.contactname,ih.contactphone,ih.contactdesignation,ih.contactdept,ih.contactemail,ih.quoteid,ih.quoteNo,ih.quotedate,ih.enqrefremarks,ih.IsTender,ih.tender_openingon,
	ih.tender_publishon,ih.tender_dueon,ih.lastfollowupdate,ih.nextfollowupdate,ih.buisnesssizeid
	from [db_mktg].hdr_enq ih
	left join db_masters.customer cust on ih.customerid = cust.id
	left join db_masters.prospectcustomers pr on ih.customerid= pr.id
	left join db_masters.country cn on cust.country= cn.id
	where ih.id =@enqid
	 
	select * from db_mktg.followup_enq where enqid=@enqid

end

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

CREATE PROCEDURE [db_mktg].[pr_getenqfollowuplist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@enqtype  varchar(10)='',
	@enqstatus varchar(10)='',
	@enqid bigint
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	begin
	set @sql= 'select remarks,cdate,ctime,enqflwup.nextfollowupdate,u.firstname as esclateto
               from db_mktg.followup_enq enqflwup
               left join db_masters.users u on enqflwup.escalateto = u.userid'
	set @sql += ' where enqflwup.coid = '+ cast(@coid as varchar(5)) +' and enqflwup.boid='+ cast(@boid as varchar(5))+'
	            and enqflwup.enqid='+ cast(@enqid as varchar(10)) +''
	end
		
	--if(@search!='')
	--	begin
	--	 set @sql += 'and hdr.enqno 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(enqflwup.[id])records 
    from db_mktg.followup_enq enqflwup
    left join db_masters.users u on enqflwup.escalateto = u.userid
	where enqflwup.enqid=@enqid

	select top(1) case when count(id)>0 then 1 else 0 end enqsavestatus from db_mktg.followup_enq where nextfollowupdate >getdate() and enqid= @enqid
END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenqphoneoremailwise]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_getenqphoneoremailwise] 1,1,1,'9034442229',''

CREATE PROCEDURE [db_mktg].[pr_getenqphoneoremailwise]
    @coid int,
	@boid int,
	@fyid int,
    @phone varchar(15)='',
	@email varchar(50)='',
	@custid bigint = null,
	@custtype varchar(10)=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @rowcount varchar(max)
	begin
	set @sql='select hdr.id,hdr.enqno,hdr.enqdate, 
    case 
    when hdr.custtype=''C'' then ''Customer'' 
    when hdr.custtype=''P'' then ''Prospect'' 
	else '''' end as type , 
    case 
    when hdr.custtype=''C'' then cust.name +'' '' + isnull(cust.address1,'''')+ isnull(cust.address2,'''')
    when hdr.custtype=''P'' then pcust.name +'' '' + isnull(pcust.address1,'''')+ isnull(pcust.address2,'''') 
	else '''' end as Custname , 
	usr.firstname as mktg_Exec,
	''Test'' as Item, 
	enqtype.name as enqstatus,
	mstg.name as enqstage,
	isnull(hdr.lastfollowupdate,'''') lastfollowupdate ,isnull(hdr.nextfollowupdate,'''') nextfollowupdate,
	hdr.contactphone,hdr.contactemail
    from [db_mktg].[hdr_enq] hdr
    left join db_masters.customer cust on hdr.customerid=cust.id
    left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
    left join db_masters.users usr on hdr.marketexecutive = usr.userid
	left join db_mktg.mst_enqstatus st on hdr.enqstatus =  st.id
	left join db_mktg.mst_quotestage mstg on mstg.id= hdr.enqstage
	left join db_mktg.mst_enquirytype enqtype on hdr.enqtype= enqtype.id '
    if(@phone<>'' and @email='')
	begin 
	set @sql +=' where hdr.contactphone='+''''+cast(@phone as VARCHAR(12))+''''
	end
	if(@email<>'' and @phone='')
	begin 
	set @sql +=' where  hdr.contactemail = '''+cast(@email as VARCHAR(50))+''''
	end
	if(@phone<>'' and @email!='' )
	begin
	set @sql +='where hdr.contactphone='+''''+cast(@phone as VARCHAR(12))+''' and  hdr.contactemail = '''+cast(@email as VARCHAR(50))+''''
	end
	if(@phone='' and @email='' )
	begin
	set @sql =''
	end

	--if(@phone<>'' and @email!='' )
	--begin
 --    set @sql +='where hdr.contactphone='+''''+cast(@phone as VARCHAR(12))+''' or hdr.contactemail = '''+cast(@email as VARCHAR(50))+''' 
	--             or hdr.Custtype = '''+cast(@custtype as VARCHAR(50))+''' or hdr.customerid= '''+cast(@custid as VARCHAR(50))+''''
	--end

	print @sql
	EXEC sp_executesql @sql
 end
END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenqstatus]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_getenqstatus] 1,1,3

CREATE PROCEDURE [db_mktg].[pr_getenqstatus]
    @coid int,
	@boid int,
	@userid int=1
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	select id,status as enqstatus  from db_mktg.mst_enqstatus 

	select id ,name as enqtype from [db_mktg].[mst_enquirytype] enqlist 

	-- where enqlist.id in (select categoryid from [db_mktg].[enquirycategory_userrights] where userid in
	-- (select * from dbo.fngetchilduserids( @userid))) order by id

	select userid, firstname as esclateto from db_masters.users

	select id,zonename from db_masters.zonemaster 

	SELECT Id,regionname FROM db_masters.regionmaster

	select id,name from [db_mktg].[mst_quotestage] order by name

END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenquiryactions]    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,10
-- =============================================

CREATE PROCEDURE [db_mktg].[pr_getenquiryactions] 
	@coid int,
	@boid int
AS
BEGIN
SET NOCOUNT ON;

  --get Dealer
  select id,name,email from db_masters.supplier where isdealer=1

  --get Intimation
  select userid, isnull(firstname,'') + isnull(lastname,'') empname from db_masters.users 

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

  --get Reject reason
  select id,name as rejectreason from [db_mktg].[mst_rejectreason]

end

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenquirydata]    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,10051
-- =============================================

CREATE PROCEDURE [db_mktg].[pr_getenquirydata] 
	@coid int,
	@boid int,
	@enqid bigint
AS
BEGIN
SET NOCOUNT ON;   
	Select ih.id,[ih].[enqno], [ih].[enqdate],ih.enqsourceid,ih.enqtype,ih.custtype,ih.marketexecutive,ih.fwdmarketexcecutive,ih.businesssegment,ih.enqstage,
	ih.buisnesssizeid,ih.[customerid],ih.[customername],ih.[customeraddr1],ih.[customeraddr2],ih.[city],ih.[state],ih.[pin],ih.country as country,
	ih.contactname,ih.contactphone,ih.contactdesignation,ih.contactdept,ih.contactemail,ih.quoteid,ih.quoteNo,ih.quotedate,ih.enqrefremarks,ih.IsTender,ih.tender_openingon,
	ih.tender_publishon,ih.tender_dueon,ih.lastfollowupdate,ih.nextfollowupdate,ih.buisnesssizeid,ih.iscustomermeetingdone,ih.emdamt,ih.BGamt,ih.splattn,ih.splremarks,
	case when st.status='Follow-up' then 0
		 else '1' end as Editrow
	from [db_mktg].hdr_enq ih
	left join db_masters.customer cust on ih.customerid = cust.id
	left join db_masters.prospectcustomers pr on ih.customerid= pr.id
	left join db_masters.country cn on cust.country= cn.id
	left join db_mktg.mst_enqstatus st on ih.enqstatus =  st.id
	where ih.id =@enqid
	 
	select id.id, case when id.itemtype='I' then im.itemname
	              when id.itemtype='T' then tm.name
				  else '' end as itemname, 
		    case when id.itemtype='I' then im.itemcode
	             when id.itemtype='T' then tm.code
				 else '' end as itemcode,
			case when id.itemtype='I' then im.oldcode
	             when id.itemtype='T' then tm.code
				 else '' end as oldcode,
			case when id.itemtype='I' then im.billingdescription
	             when id.itemtype='T' then tm.description
				 else '' end as billingdescription,
			case when id.itemtype='I' then u.uom
	             when id.itemtype='T' then u.uom
				 else '' end as uom,
    id.itemid,id.itemtype,id.qtyreqd,id.deliveryindays,id.itemremarks,id.buisnesssegment,id.createdby,
	id.createdon,id.modifiedby,id.modifiedon,id.lastfollowupdate,id.nextfollowupdate
	from [db_mktg].[dtl_enq] id
	left join [db_mm].[mst_item] im  on id.itemid= im.id
	left join db_mktg.mst_tenderItemMaster tm on id.itemid= tm.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	where id.enqid =@enqid;

	--select bsegmtid as id ,qty as value from db_mktg.dtl_bsegmt_enq where enqid=@enqid

end



GO
/****** Object:  StoredProcedure [db_mktg].[pr_getenquirylist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_getenquirylist] 1,100,1,1,'','id','','','',3,1,6

CREATE PROCEDURE [db_mktg].[pr_getenquirylist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@enqtype  varchar(10)='',
	@enqstatus varchar(10)='',
	@userid int = NULL,
	@zoneid int = NULL,
	@regionid int = NULL
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);
	begin
	set @sql= 'select * from (select hdr.id,hdr.coid,hdr.boid,hdr.userid,hdr.enqtype,hdr.enqno,hdr.enqdate,hdr.city,hdr.state,
    case 
    when hdr.custtype=''C'' then ''Customer''	else ''Prospect'' end as type , 
    case when hdr.custtype=''C'' then cust.name +'' '' + isnull(cust.address1,'''')+ isnull(cust.address2,'''')   
	else pcust.name +'' '' + isnull(pcust.address1,'''')+ isnull(pcust.address2,'''')  end as Custname , 
	usr.firstname as mktg_Exec,	coalesce(itm.itemname,titm.name) as firstproduct,
	st.status as enqstatus,	mstg.name as enqstage,	hdr.quoteid as viewquote,
	--''0'' as viewquote, 
	case when hdr.nextfollowupdate =''1900-01-01 00:00:00'' then '''' 
	else FORMAT (hdr.nextfollowupdate,''dd-MM-yyyy'') end nextfollowupdate,
	case when hdr.lastfollowupdate =''1900-01-01 00:00:00'' then '''' 
	else FORMAT (hdr.lastfollowupdate,''dd-MM-yyyy'') end lastfollowupdate,
	mstg.backgroundcolor colorcode,
	case when hdr.enqstatus in (1,4)  then ''1'' else ''0'' end as Followpcheck,
    hdr.enqstatus as enqstatusid,hdr.rejectionid,
	hdr.intimationto,hdr.dealerid,hdr.deptid,hdr.rejectionremark as rejectionremarks,
	CASE WHEN hdr.custtype=''P'' THEN pcust.zone		 ELSE cust.zone END AS zone,
    CASE WHEN hdr.custtype=''P'' THEN pcust.region		 ELSE cust.region END AS region,
	case WHEN isnull(hdr.quoteid,0) = 0 then ''0''	else ''1'' end as isconvertedtoquote,enqrefremarks
    from [db_mktg].[hdr_enq] hdr
	inner join (select enqid,min(id) id from db_mktg.dtl_enq group by enqid) mindtl on hdr.id=mindtl.enqid
	join db_mktg.dtl_enq dtl on mindtl.id = dtl.id
	left join db_mktg.mst_tenderItemMaster titm on dtl.itemid = titm.id
	left join db_mm.mst_item itm on dtl.itemid = itm.id
    left join db_masters.customer cust on hdr.customerid=cust.id
    left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
    left join db_masters.users usr on hdr.marketexecutive = usr.userid
	left join db_mktg.mst_enqstatus st on hdr.enqstatus =  st.id
	left join db_mktg.mst_quotestage mstg on mstg.id= hdr.enqstage
	left join db_mktg.mst_enquirytype enqtype on hdr.enqtype= enqtype.id 
	where hdr.userid in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))) as enqlist'
	set @sql += ' where enqlist.coid = '+ cast(@coid as varchar(5)) +' and enqlist.boid='+ cast(@boid as varchar(5))+''
	end
	if(@userid!='')
	begin 
	set @sql +=' and enqlist.userid in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+'))'
	end
	if(@enqtype!='')  
		begin 
			set @sql +=' and enqlist.enqtype='+''''+cast(@enqtype as VARCHAR(10))+''''
		end
	else
		begin
			set @sql+=' and enqlist.enqtype in (select categoryid from [db_mktg].[enquirycategory_userrights] where userid in
			(select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+')))'
		end
	if(@enqstatus!='')
	begin 
	set @sql +=' and enqlist.enqstatusid='+''''+cast(@enqstatus as VARCHAR(10))+''''
	END
	if(@zoneid<>'')
	begin 
	set @sql +=' and enqlist.zone  ='+''''+cast(@zoneid as VARCHAR(10))+''''
	END
	if(@regionid<>'')
	begin 
	set @sql +=' and enqlist.region  ='+''''+cast(@regionid as VARCHAR(10))+''''
	end
	if(@search<>'')
	begin
	set @sql += ' and enqlist.enqno like '+'''%'+cast(@search as varchar(50)) + '%'' or enqlist.custname like '+'''%'+cast(@search as varchar(50)) + '%'' 
	              or enqlist.city like '+'''%'+cast(@search as varchar(50)) + '%'' or enqlist.state like '+'''%'+cast(@search as varchar(50)) + '%'' 
				  or enqlist.firstproduct 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() records
	
END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getinvoicedata]    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_getinvoicedata] 1,1,10149
-- =============================================

CREATE PROCEDURE [db_mktg].[pr_getinvoicedata] 
	@coid int,
	@boid int,
	@invid int
AS
BEGIN
	SET NOCOUNT ON;
	--declare @orderid bigint =(select top 1 oaid from db_sop.dtl_sale where invid=@invid)
	Select ih.id,ih.[oaids],[pino],[pidate],[confirmed],ih.[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],[ih].[quoteid],quote.quoteno,quote.quotedate,
	ih.[cancelledon],ih.[cancelledbyuserid],[invprefix],[invpostfix],ih.[customerid],ih.[customername],ih.[customeraddr1],ih.[customeraddr2],ih.[city],ih.[state],ih.[country] as customercountry,c.id countryid,
	ih.[pin],ih.[customergstno],ih.[billtocustomername],ih.[billtocustomeraddr1],ih.[billtocustomeraddr2],ih.[billtocity],ih.[billtostate],
	ih.[billtopin],ih.[billtocustomergstno],ih.[consigneecustomerid],ih.[consigneecustomername],ih.[consigneecustomeraddr1],ih.[consigneecustomeraddr2],
	ih.[consigneecity],ih.[consigneestate],ih.[consigneepin],ih.[consigneecustomergstno],ih.[custPoNo],ih.[custPodate],ih.[basicamt],ih.[discamt],ih.[netamt],ih.[igstamt],
	ih.[cgstamt],ih.[sgstamt],[invamt],ih.[userid],ih.[approvedbymarketingheaduserid],ih.[approvedbycommercialuserid],[approvedbyaccountsuserid],ih.[remarks],
	ih.[coid],ih.[boid],ih.[fyid],ih.[createdby],ih.[createdon],ih.[modifiedby],ih.[modifiedon], ih.consigneecustomerid,quote.custtype,
	isnull(ih.billtocustomerid,ih.customerid) billtocustomerid,
	isnull(ih.billtocustomerid,ih.customerid) as billtocustomerid1,
    (select id from db_sop.mst_ordertype where id=ih.invoicetype) ordertype,ih.currency,ih.country,ih.custtype
    from [db_mktg].[quote_hdr_sale] ih
	left join [db_mktg].hdr_quote quote on quote.quoteid =ih.quoteid
	left join [db_masters].[country] c on ih.country=c.countryname
    where ih.id = @invid
	select im.[itemcode],im.[oldcode],im.[itemname],id.[itemid],id.oaid,id.quoteid,0 as oano,qut.quoteno,qut.quotedate,od.custpono, id.[billingdescription],id.[isfoc],id.[issample],id.[specialcode],id.[packing],isnull(u.[uom],'Nos'),
	id.[gstid],id.[igstrate],id.[sgstrate],id.[cgstrate],id.[cessrate],id.[basicamount],id.[rate],id.[netrate],id.[orderedquantity],id.[itemdiscpercent],
	id.[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],id.[totalamt],id.[remarks]
	,id.qtyalreadydispatched, id.qtytodispatch,id.focqty,[batch],h.hsncode,0 stock
	from [db_mktg].[quote_dtl_sale] id
	join [db_mktg].[quote_hdr_sale] od on id.invid = od.id 
	join db_mktg.hdr_quote qut on id.quoteid = qut.quoteid
	join [db_mm].[mst_item] im  on id.itemid= im.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	--left join [db_mm].[mst_gst] g on h.gstid=h.gstid
	where id.invid=@invid
	select id,invid,oaid,itemid,packing,qty,focqty,batch,mfgdate,expdate 
	from [db_sop].[dtl_sale_batches] where invid = @invid
	select termsandconditionsid id,termsandconditionsid,t1.termsandcondition 
	from [db_mktg].[quote_sale_termsandconditions] t1 
	where t1.invid=@invid
	select id, [paymenttermid], [paymentterm], [percent], [amount] 
	from  [db_mktg].[quote_sale_paymentterms] t2 
	where t2.invid=@invid
	select id,ordertype from db_sop.mst_ordertype
    select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid
	
	Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	from [db_mm].[mst_gst] h join 
    db_mm.mst_hsn g on h.gstid=g.gstid
	where h.coid = @coid and h.boid = @boid 
	order by hsncode asc

	select id, uom from [db_mm].[mst_itemuom] where isactive=1

end

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getquotationdata]    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,03-12-2018>
-- Description:	<Description,Get supplier data>
-- [db_mktg].[pr_getquotationdata] 1,1,103
-- =============================================


CREATE PROCEDURE [db_mktg].[pr_getquotationdata] 
	@coid int,
	@boid int,
	@quoteid  int
AS
BEGIN
	SET NOCOUNT ON;
	
	 Select ih.quoteid,[ih].[quoteno],ih.revisedno AS revisedno,[ih].[quotedate] ,ih.[customerid],
	 case when ih.custtype ='C' then cust.name     else pcust.name end as customername,
	 case when ih.custtype ='C' then cust.address1     else pcust.address1 end as customeraddr1,
	 case when ih.custtype ='C' then cust.address2     else pcust.address2 end as customeraddr2,
	 ih.city,ih.[state],ih.country,cn.id as countryid,[customergstno],
	 ih.quotstage,ih.bsegment,ih.enqNo,ih.enqid, case when ih.enqid=0  then 1 else 0 end as enquiryEditable,
	 [customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
	 [customercontactpersondepartment],
	  case when ih.enqdate like '%1900-01-01%' then ''	 else ih.enqdate end enqdate,
	 --case when ih.enqdate like '%1900-01-01%' then ''	 else FORMAT (ih.enqdate,'dd-MM-yyyy') end enqdate,
	 [ourquoteno],[ourquotedate],isnull([basicamt],0) basicamt,
	 isnull([discamt],0) discamt,isnull([netamt],0) netamt,
	 isnull([igstamt],0) igstamt,isnull([cgstamt],0) cgstamt,isnull([sgstamt],0) sgstamt,isnull([orderamt],0) orderamt,[remarks],[invoicetype],
	 [ih].[marketexecutive],[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo],ih.custtype,ih.disctype,ih.[quoteratetype],senderinfo,
	 ih.ordertype,ih.currency,ih.conversionrate
	 from [db_mktg].hdr_quote ih
	 left join db_masters.customer cust on ih.customerid = cust.id
	 left join db_masters.prospectcustomers pcust on ih.customerid =pcust.id
	 left join db_masters.country cn on rtrim(ih.country)= rtrim(cn.countryname)
	 where ih.quoteid=@quoteid
	 select id.id,case when id.itemtype='I' then im.itemname				  else tm.name end as itemname, 
		    case when id.itemtype='I' then im.itemcode				 else tm.code end as itemcode,
			case when id.itemtype='I' then im.oldcode				 else tm.code end as oldcode,
			case when id.itemtype='I' then im.billingdescription				 else tm.description end as billingdescription,
     id.itemid,id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],u.[uom],id.[gstid],
	[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]
	,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],h.hsncode,id.[remarks],id.[mrp],id.[focqty],id.itemtype,[id].hsnid
	from [db_mktg].[dtl_quote] id
	left join [db_mm].[mst_item] im  on id.itemid= im.id
	left join db_mktg.mst_tenderItemMaster tm on id.itemid= tm.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	--left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	where id.quoteid =@quoteid
	select termsandconditionsid,termsandcondition from [db_mktg].[quote_termsandconditions] where quoteid=@quoteid
	select [srno],[paymenttermid],[paymentterm],[percent],[amount] from db_mktg.quote_paymentterms where quoteid=@quoteid
	select installationid,installationinfo from [db_mktg].quote_installationinfo where quoteid=@quoteid
	select documentid,documentinfo from db_mktg.quote_documentsreqd where quoteid=@quoteid
	---get market executive
	select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	 ---get gst list
	Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	from [db_mm].[mst_gst] h join 
     db_mm.mst_hsn g on h.gstid=g.gstid
	 where h.coid = @coid and h.boid = @boid 
	 order by hsncode asc
	  --get buisnesssegment
	select id,businesssegementname from db_masters.businesssegement
	   --get quoteStage
    select id,name from [db_mktg].[mst_quotestage]
	select * from [db_mktg].[mst_quoteratetype]
	select * from db_mm.mst_itemuom
	select * from [db_mktg].[dtl_qoute_levies] where qouteid=@quoteid 
    select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid
    SELECT id,ordertype FROM db_sop.mst_ordertype 
    SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
    SELECT ROW_NUMBER() OVER( ORDER BY id) sr,imageinfo,[filename] FROM [db_mktg].[quote_images] WHERE quoteid=@quoteid
	SELECT revisedno= ('R-'+ CAST(ih.revisedno AS VARCHAR(5))) FROM [db_mktg].hdr_quote_revised ih WHERE ih.quoteid=@quoteid
	END

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

-- exec [db_mktg].[pr_getQuotationlist] 1,200,1,1,'','quoteid','desc',1,3,0

CREATE PROCEDURE [db_mktg].[pr_getQuotationlist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='quoteid',
	@sortorder nvarchar(100)='desc',
	@userid INT = NULL,
	@zoneid INT = NULL,
	@regionid INT = NULL,
	@quotestatus VARCHAR(10)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	DECLARE @totalcount NVARCHAR(MAX);
	
	begin
	set @sql= 'select * from (select hdr.quoteid,hdr.revisedno,hdr.quoteno,hdr.quotedate,hdr.city,hdr.state,hdr.coid,hdr.boid,hdr.userid,
    case 
    when hdr.custtype=''C'' then ''Customer'' 
    when hdr.custtype=''P'' then ''Prospect'' 
	else '''' end as type , 
    case 
    when hdr.custtype=''C'' then cust.name 
    when hdr.custtype=''P'' then pcust.name 
	else '''' end as Custname , 
	CASE WHEN hdr.custtype=''C'' THEN cust.zone
	     WHEN hdr.custtype=''P'' THEN pcust.zone
	ELSE 0 END AS zone,
	CASE WHEN hdr.custtype=''C'' THEN cust.region
	     WHEN hdr.custtype=''P'' THEN pcust.region
	ELSE 0 END AS region,
	usr.firstname as mktg_Exec,
	isnull(st.status,'''') status,COALESCE(itm.itemname,titm.name) as firstproduct, hdr.lastfollowupdate,hdr.nextfollowupdate,
	st.colorcode,
    case when st.status=''Pending'' then 1
	     when st.status=''Follow-up'' then 1
		 else ''0'' end as Followpcheck,	
	hdr.quotestatus as quotestatusid,
	hdr.intimationto,hdr.dealerid,hdr.deptid,hdr.rejectionremark as rejectionremarks,isnull(hdr.isconverttoinvoice ,0) isconverttoinvoice,
	isnull(hdr.isconverttoorder,0) isconverttoorder
    from [db_mktg].[hdr_quote] hdr
	inner join (select quoteid,min(id) id from db_mktg.dtl_quote group by quoteid) mindtl on hdr.quoteid = mindtl.quoteid
	join db_mktg.dtl_quote dtl on mindtl.id=dtl.id
	left join db_mktg.mst_tenderItemMaster titm on dtl.itemid = titm.id
	left join db_mm.mst_item itm on dtl.itemid = itm.id
    left join db_masters.customer cust on hdr.customerid=cust.id
    left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
    left join db_masters.users usr on hdr.marketexecutive = usr.userid
	left join [db_mktg].[mst_enqstatus] st on hdr.quotestatus=st.id ) as quotelist'
	set @sql += ' where quotelist.coid = '+ cast(@coid as varchar(5)) +' and quotelist.boid='+ cast(@boid as varchar(5))+''
	END
	if(@quotestatus!='')
	begin 
	set @sql +=' and quotelist.quotestatusid  ='+''''+cast(@quotestatus as VARCHAR(10))+''''
	END

	if(@userid!='')
	begin 
	set @sql +='and quotelist.userid='+ cast(@userid as varchar(5))+''
	end
	if(@zoneid!='')
	begin 
	set @sql +=' and quotelist.zone  ='+''''+cast(@zoneid as VARCHAR(10))+''''
	END
	if(@regionid!='')
	begin 
	set @sql +=' and quotelist.region  ='+''''+cast(@regionid as VARCHAR(10))+''''
	end
	if(@search!='')
	begin
	set @sql += ' and quotelist.quoteno like '+'''%'+cast(@search as varchar(50)) + '%'' or quotelist.custname like '+'''%'+cast(@search as varchar(50)) + '%'' or quotelist.city like '+'''%'+cast(@search as varchar(50)) + '%'' or quotelist.state 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() records

	--set @totalcount ='select  count(hdr.[id])records 
 --   from [db_mktg].[hdr_quote] hdr
 --   left join db_masters.customer cust on hdr.customerid=cust.id
 --   left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
 --   left join db_masters.users usr on hdr.marketexecutive = usr.userid'  
	--if(@quotestatus!='')
	--begin 
	--set @totalcount +=' and hdr.quotestatus='+''''+cast(@quotestatus as VARCHAR(10))+''''
	--end

	--print @totalcount

	--EXEC sp_executesql @totalcount

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

-- exec [db_mktg].[pr_getquotefollowuplist] 1,200,1,1,'','id','','','',14

CREATE PROCEDURE [db_mktg].[pr_getquotefollowuplist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@enqtype  varchar(10)='',
	@enqstatus varchar(10)='',
	@quoteid bigint
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	begin
	set @sql= 'select remarks,cdate,ctime,quotflwup.nextfollowupdate,u.firstname as esclateto
               from db_mktg.followup_quot quotflwup
               left join db_masters.users u on quotflwup.escalateto = u.userid'
	set @sql +=' where quotflwup.coid = '+ cast(@coid as varchar(5)) +' and quotflwup.boid='+ cast(@boid as varchar(5))+'and quotflwup.quoteid = '+ cast(@quoteid as varchar(5)) +''
	end
		
	--if(@search!='')
	--	begin
	--	 set @sql += 'and hdr.enqno 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(quotflwup.[id])records 
    from db_mktg.followup_quot quotflwup
    left join db_masters.users u 
	on quotflwup.escalateto = u.userid
	where quotflwup.quoteid = @quoteid

END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_getQuoteinvoicelist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mktg].[pr_getQuoteinvoicelist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='pino',
	@sortorder nvarchar(100)='desc',
	@type char(1)='P',
	@search varchar(50)='',
	@searchtype varchar(25) = ''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql = 'select id,piid,pino,pidate,quoteid,revisedno,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,state,pin,
                customergstno,country,quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,
                roundoff,userid,cancelledon,cancelledbyuserid,remarks,coid,boid,fyid,createdby,createdon,modifiedby,modifiedon,
                invoicetype,senderinfo,isconverttoorder,ordertype,conversionrate,Currency from  db_mktg.hdr_quote_pi hdr '
		set @sql += ' where coid = ' + cast(@coid as varchar(5)) + ' and boid = ' + cast(@boid as varchar(5))
         -- if (@searchtype = 'pino' and @search!='') 
	     --  begin
	     --	set @sql += ' and h.pino = ' + @search
	     --	 set @sql +=' order by h.pino ' + @sortorder + ' '
	     --  end
	     -- else if (@searchtype = 'customername' and @search!='')
	     -- begin
	     --	set @sql += ' and  h.customername like ''%' + cast(@search as varchar(50)) + '%'''
	     --	 set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',customername)asc, LEN(customername)' + @sortorder + ' '
	     -- end
	     -- else
	  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(hdr.[id]) records 
                    from db_mktg.hdr_quote_pi hdr
                    join [db_masters].[users] u on hdr.createdby = u.userid'
		set @sql += ' where hdr.coid = ' + cast(@coid as varchar(5)) + ' and hdr.boid = ' + cast(@boid as varchar(5))

	print @sql

	EXEC sp_executesql @SQL
END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getquotepidata]    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_getquotepidata]  1,1,1,1,1
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_getquotepidata] 
	@coid int,
	@boid int,
	@piid bigint,
	@fyid int,
	@userid bigint
AS
BEGIN
	SET NOCOUNT ON;
	
	--declare @orderid bigint =(select top 1 oaid from db_sop.dtl_sale where invid=@invid)

	Select ih.id,piid,pino,pidate,quoteid,ih.revisedno AS revisedno,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,state,pin,customergstno,
    country,c.id as countryid,quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,cancelledon,
    cancelledbyuserid,remarks,ih.coid,ih.boid,ih.fyid,ih.createdby,ih.createdon,ih.modifiedby,ih.modifiedon,invoicetype,senderinfo,isconverttoorder,ordertype,
     conversionrate,Currency
    -- (select id from db_sop.mst_ordertype where id=ih.invoicetype) ordertype,ih.currency,ih.country,ih.custtype
    from [db_mktg].hdr_quote_pi ih
	--left join [db_mktg].hdr_quote quote on quote.quoteid =ih.quoteid
	left join [db_masters].[country] c on ih.country=c.countryname
    where ih.id = @piid

	select id.id,piid,itemid,id.billingdescription,isnull(uom,'') uom,id.gstid,igstrate,sgstrate,cgstrate,cessrate,
	        basicamount,id.mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,
			cessamt,totalamt,isnull(id.remarks,'') remarks,focqty,hsnid,im.itemname,im.itemcode,im.oldcode,h.hsncode
	from db_mktg.dtl_quote_pi id	
	join [db_mm].[mst_item] im  on id.itemid= im.id
	--join [db_mktg].[quote_hdr_sale] od on id.invid = od.id 
	--join db_mktg.hdr_quote qut on id.quoteid = qut.quoteid
	--left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	--left join [db_mm].[mst_gst] g on h.gstid=h.gstid
	where id.piid=@piid

	select termsandconditionsid id,termsandconditionsid,t1.termsandcondition 
	from [db_mktg].quote_pi_termsandconditions t1 
	where t1.piid=@piid

	select id, [paymenttermid], [paymentterm], [percent], [amount] 
	from  [db_mktg].quote_pi_paymentterms t2 
	where t2.piid=@piid

	select * from [db_mktg].[dtl_qoute_pi_levies] where piid=@piid

	select id,ordertype from db_sop.mst_ordertype where coid=@coid and boid =@boid and fyid=@fyid

    select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid

	Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	from [db_mm].[mst_gst] h join 
    db_mm.mst_hsn g on h.gstid=g.gstid
	where h.coid = @coid and h.boid = @boid order by hsncode asc

	 select id, uom from [db_mm].[mst_itemuom] where isactive=1

	select id,businesssegementname,
	case when businesssegementname ='Export' then 'E'
	else '' end as type
	from db_masters.businesssegement where parentid=0

    --get document
	select userid,firstname from [db_masters].[users]
    --get HSN
    SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency

	SELECT revisedno= ('R-'+ CAST(ih.revisedno AS VARCHAR(5))) FROM [db_mktg].hdr_quote_pi_revised ih WHERE ih.piid=@piid

end

GO
/****** Object:  StoredProcedure [db_mktg].[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_mktg].[pr_getenquirydata] 1,1,10
-- =============================================

CREATE PROCEDURE [db_mktg].[pr_getresumedetails] 
	@coid int,
	@boid int,
	@userid int,
	@resumeid int
AS
BEGIN
SET NOCOUNT ON;

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

   select * from [db_hr].[dtl_resumeexperience] where resumeid=@resumeid

   select * from [db_hr].[dtl_resumequalification] where resumeid=@resumeid

   select * from [db_hr].[dtl_resumeskills] where resumeid=@resumeid

   select * from [db_hr].[dtl_resumecategory] where resumeid=@resumeid

end

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getreviseddata]    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,07-01-2020>
-- Description:	<Description,Get revised data for offer quote>
-- [db_mktg].[pr_getreviseddata] 1,1,3,184
-- =============================================


CREATE PROCEDURE [db_mktg].[pr_getreviseddata] 
	@coid int,
	@boid int,
	@revisedno  INT,
	@quoteid  int
AS
BEGIN
	SET NOCOUNT ON;
	
	 Select ih.quoteid,[ih].[quoteno],ih.revisedno AS revisedno,[ih].[quotedate] ,ih.[customerid],
	 case when ih.custtype ='C' then cust.name     else pcust.name end as customername,
	 case when ih.custtype ='C' then cust.address1     else pcust.address1 end as customeraddr1,
	 case when ih.custtype ='C' then cust.address2     else pcust.address2 end as customeraddr2,
	 ih.city,ih.[state],ih.country,cn.id as countryid,[customergstno],
	 ih.quotstage,ih.bsegment,ih.enqNo,ih.enqid, case when ih.enqid=0  then 1 else 0 end as enquiryEditable,
	 [customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
	 [customercontactpersondepartment],
	  case when ih.enqdate like '%1900-01-01%' then ''	 else ih.enqdate end enqdate,
	 --case when ih.enqdate like '%1900-01-01%' then ''	 else FORMAT (ih.enqdate,'dd-MM-yyyy') end enqdate,
	 [ourquoteno],[ourquotedate],isnull([basicamt],0) basicamt,
	 isnull([discamt],0) discamt,isnull([netamt],0) netamt,
	 isnull([igstamt],0) igstamt,isnull([cgstamt],0) cgstamt,isnull([sgstamt],0) sgstamt,isnull([orderamt],0) orderamt,[remarks],[invoicetype],
	 [ih].[marketexecutive],[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo],ih.custtype,ih.disctype,ih.[quoteratetype],senderinfo,
	 ih.ordertype,ih.currency,ih.conversionrate
	 from [db_mktg].hdr_quote_revised ih
	 left join db_masters.customer cust on ih.customerid = cust.id
	 left join db_masters.prospectcustomers pcust on ih.customerid =pcust.id
	 left join db_masters.country cn on rtrim(ih.country)= rtrim(cn.countryname)
	 where ih.quoteid=@quoteid AND ih.revisedno=@revisedno
	 select id.id,case when id.itemtype='I' then im.itemname				  else tm.name end as itemname, 
		    case when id.itemtype='I' then im.itemcode				 else tm.code end as itemcode,
			case when id.itemtype='I' then im.oldcode				 else tm.code end as oldcode,
			case when id.itemtype='I' then im.billingdescription				 else tm.description end as billingdescription,
     id.itemid,id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],u.[uom],id.[gstid],
	[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]
	,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],h.hsncode,id.[remarks],id.[mrp],id.[focqty],id.itemtype,[id].hsnid
	from [db_mktg].[dtl_quote_revised] id
	left join [db_mm].[mst_item] im  on id.itemid= im.id
	left join db_mktg.mst_tenderItemMaster tm on id.itemid= tm.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	--left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	where id.quoteid =@quoteid AND id.revisedno=@revisedno
	select termsandconditionsid,termsandcondition from [db_mktg].[quote_termsandconditions_revised] where quoteid=@quoteid AND revisedno=@revisedno
	select [srno],[paymenttermid],[paymentterm],[percent],[amount] from db_mktg.quote_paymentterms_revised where quoteid=@quoteid AND revisedno=@revisedno
	select installationid,installationinfo from [db_mktg].quote_installationinfo_revised where quoteid=@quoteid AND revisedno=@revisedno
	select documentid,documentinfo from db_mktg.quote_documentsreqd_revised where quoteid=@quoteid AND revisedno=@revisedno
	---get market executive
	select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	 ---get gst list
	Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	from [db_mm].[mst_gst] h join 
     db_mm.mst_hsn g on h.gstid=g.gstid
	 where h.coid = @coid and h.boid = @boid 
	 order by hsncode asc
	  --get buisnesssegment
	select id,businesssegementname from db_masters.businesssegement
	   --get quoteStage
    select id,name from [db_mktg].[mst_quotestage]
	select * from [db_mktg].[mst_quoteratetype]
	select * from db_mm.mst_itemuom
	select * from [db_mktg].[dtl_qoute_levies] where qouteid=@quoteid 
    select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid
    SELECT id,ordertype FROM db_sop.mst_ordertype 
    SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
    SELECT ROW_NUMBER() OVER( ORDER BY id) sr,imageinfo,[filename] FROM [db_mktg].[quote_images] WHERE quoteid=@quoteid
	SELECT revisedno= ('R-'+ CAST(ih.revisedno AS VARCHAR(5))) FROM [db_mktg].hdr_quote_revised ih WHERE ih.quoteid=@quoteid
	END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getrevisedpidata]    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,01-09-2020>
-- Description:	<Description,Get Revised PI data>
-- [db_mktg].[pr_getrevisedpidata]  1,1,1,1,1
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_getrevisedpidata] 
	@coid int,
	@boid int,
	@revisedno  INT,
	@piid bigint
AS
BEGIN
	SET NOCOUNT ON;
	
	--declare @orderid bigint =(select top 1 oaid from db_sop.dtl_sale where invid=@invid)

	Select ih.id,piid,pino,pidate,quoteid,ih.revisedno AS revisedno,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,state,pin,customergstno,
    country,c.id as countryid,quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,cancelledon,
    cancelledbyuserid,remarks,ih.coid,ih.boid,ih.fyid,ih.createdby,ih.createdon,ih.modifiedby,ih.modifiedon,invoicetype,senderinfo,isconverttoorder,ordertype,
     conversionrate,Currency
    -- (select id from db_sop.mst_ordertype where id=ih.invoicetype) ordertype,ih.currency,ih.country,ih.custtype
    from [db_mktg].hdr_quote_pi_revised ih
	--left join [db_mktg].hdr_quote quote on quote.quoteid =ih.quoteid
	left join [db_masters].[country] c on ih.country=c.countryname
    where ih.piid = @piid AND ih.revisedno=@revisedno

	select id.id,piid,itemid,id.billingdescription,isnull(uom,'') uom,id.gstid,igstrate,sgstrate,cgstrate,cessrate,
	        basicamount,id.mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,
			cessamt,totalamt,isnull(id.remarks,'') remarks,focqty,hsnid,im.itemname,im.itemcode,im.oldcode,h.hsncode
	from db_mktg.dtl_quote_pi_revised id	
	join [db_mm].[mst_item] im  on id.itemid= im.id
	--join [db_mktg].[quote_hdr_sale] od on id.invid = od.id 
	--join db_mktg.hdr_quote qut on id.quoteid = qut.quoteid
	--left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	--left join [db_mm].[mst_gst] g on h.gstid=h.gstid
	where id.piid=@piid AND id.revisedno=@revisedno

	select termsandconditionsid id,termsandconditionsid,t1.termsandcondition 
	from [db_mktg].quote_pi_termsandconditions_revised t1 
	where t1.piid=@piid AND t1.revisedno=@revisedno

	select id, [paymenttermid], [paymentterm], [percent], [amount] 
	from  [db_mktg].quote_pi_paymentterms_revised t2 
	where t2.piid=@piid AND t2.revisedno=@revisedno

	select * from [db_mktg].[dtl_qoute_pi_levies_revised] where piid=@piid AND revisedno=@revisedno

	select id,ordertype from db_sop.mst_ordertype where coid=@coid and boid =@boid

    select distinct( m.id),levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid

	Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]
	from [db_mm].[mst_gst] h join 
    db_mm.mst_hsn g on h.gstid=g.gstid
	where h.coid = @coid and h.boid = @boid order by hsncode asc

	 select id, uom from [db_mm].[mst_itemuom] where isactive=1

	select id,businesssegementname,
	case when businesssegementname ='Export' then 'E'
	else '' end as type
	from db_masters.businesssegement where parentid=0

    --get document
	select userid,firstname from [db_masters].[users]
    --get HSN
    SELECT id,code,name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency

	SELECT revisedno= ('R-'+ CAST(ih.revisedno AS VARCHAR(5))) FROM [db_mktg].hdr_quote_pi_revised ih WHERE ih.piid=@piid

end

GO
/****** Object:  StoredProcedure [db_mktg].[pr_getstatuslist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- 5

CREATE PROCEDURE [db_mktg].[pr_getstatuslist]
   @PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='id',
	--@sortorder nvarchar(100)='asc',
	 @search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select name,status,colorcode,coid,boid from [db_mktg].[mst_enqstatus] h '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		--if(@search!='')
		--begin
		-- set @sql += ' and H.dprnumber = ' + cast(@search 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

	
				
	
	
	
END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_gettermsandcondition]    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_gettermsandcondition] 1,1,5
-- =============================================

CREATE PROCEDURE [db_mktg].[pr_gettermsandcondition] 
	@coid int,
	@boid int,
	@type int
AS
BEGIN
	SET NOCOUNT ON;

	declare @sql varchar(100);

	set @sql = (SELECT ordertype FROM db_sop.mst_ordertype where id=@type)

	select * from [db_mktg].[mst_termsandconditions]

	if(@sql='Export')
	begin
	select termsandcondition =stuff((select '','' + name from [db_mktg].[mst_termsandconditions]  where isexport=1 FOR XML PATH ('br')), 1, 0, '')
	end
	else
	begin
	 select termsandcondition =stuff((select '','' + name from [db_mktg].[mst_termsandconditions] where isexport =isnull(isexport,0) For XML PATH ('br')), 1, 0, '')
    end	
end

GO
/****** Object:  StoredProcedure [db_mktg].[pr_marketingterms]    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-12-2019>
-- Description:	<Description,Get list of terms and condition>
-- exec [db_mktg].[pr_marketingterms] 1,1,9

CREATE PROCEDURE [db_mktg].[pr_marketingterms]
	@coid int = 1,
	@boid int = 1,
	@type int = null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@isexport bit;
    
	select @isexport =isexportterms from db_sop.mst_ordertype where id=@type
	
	select * from db_mktg.mst_termsandconditions where isnull(isexport,0)=isnull(@isexport,0)
	
END
GO
/****** Object:  StoredProcedure [db_mktg].[pr_printcustomerinvoice]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- [db_mktg].[pr_printcustomerinvoice]  1,1,11,1
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_printcustomerinvoice] 
	@coid int,
	@boid int,
	@id int,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;
	-- header data -- company information
	-- select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	-- b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	-- from db_general.company_branches b
	-- join db_masters.company c on  b.coid = c.coid
	-- where b.coid = @coid and b.boid = @boid

	select  c.companyname,b.unitname,(isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' ' + isnull(b.city,'')+'-' + isnull(b.pin,'')) address,b.state,
	b.country,case when len(u.mobileno)>1 then ('+91-' + ltrim(u.mobileno)) else '' end phone_number,u.emailid useremail,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	join db_masters.users u on u.boid=b.boid
	where b.coid = @coid and b.boid = @boid and u.userid=@userid
	-- invoice and customer information
	--Select  s.id,  pino, pidate, confirmed, confirmedbyuserid, confirmedon, invno, invdate, revisedbyuserid, revisedon, cancelledon, cancelledbyuserid, invprefix, invpostfix, customerid, customername, 
 --   customeraddr1, customeraddr2, s.city, s.state, 
	--case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,	
	--case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,
	--case when s.custtype ='C' then cust.gstin else pcust.gstin end as customergstno,
	--case when s.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	--else (isnull(pcust.phone_number,'')+' '+ isnull(pcust.mobile_number,'')) 		 end as mobile_number,
	----case when s.custtype ='C' then cust.mobile_number else pcust.mobile_number end as mobile_number,
	----case when s.custtype ='C' then cust.phone_number  else pcust.phone_numbe end as phone_number,
	--billtocustomerid, billtocustomername, billtocustomeraddr1, billtocustomeraddr2, billtocity, billtostate, billtopin, billtocustomergstno, 
 --   consigneecustomerid, consigneecustomername, consigneecustomeraddr1, consigneecustomeraddr2, consigneecity, consigneestate, consigneepin, consigneecustomergstno, custPoNo, custPodate, basicamt, 
 --   discamt, netamt, igstamt, cgstamt, sgstamt, invamt, userid, approvedbymarketingheaduserid, approvedbycommercialuserid, approvedbyaccountsuserid, remarks, s.coid, s.boid, s.fyid, s.createdby, s.createdon, 
 --   s.modifiedby, s.modifiedon, invoicetype, customer_gstno, customer_phonenumber, customer_taxnumber, roundoff, concessionaltax, advancereceived, 
	--billseriesid,invoicetype type,sm.statecode,currency,symbol
 --   FROM   db_mktg.quote_hdr_sale s
 --   left join db_masters.statemaster sm on s.state=sm.statename
 --   left join db_masters.currency c on s.currency=c.code
	--left join db_masters.customer cust on s.customerid=cust.id
	--left join db_masters.prospectcustomers pcust on s.customerid=pcust.id
 --   where s.id =@id
    select s.id,piid,pino,pidate,quoteid,revisedno,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,s.city,s.state,
    case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,	
	case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,
	case when s.custtype ='C' then cust.gstin else pcust.gstin end as customergstno,
	case when s.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	else (isnull(pcust.phone_number,'')+' '+ isnull(pcust.mobile_number,'')) 	end as mobile_number,
    customergstno,s.country,
    quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,cancelledon,cancelledbyuserid,remarks,
    s.coid,s.boid,s.fyid,invoicetype,senderinfo,isconverttoorder,ordertype,conversionrate,Currency,c.symbol
    from db_mktg.hdr_quote_pi s
    left join db_masters.statemaster sm on s.state=sm.statename
    left join db_masters.currency c on s.currency=c.code
    left join db_masters.customer cust on s.customerid=cust.id
    left join db_masters.prospectcustomers pcust on s.customerid=pcust.id
    where s.id =@id
 --   select [itemcode],im.[itemname],id.[itemid],id.[billingdescription],id.[isfoc],sh.custPoNo,id.[issample],id.[specialcode],id.[packing],
 --   u.[uom], id.[gstid],g.igst as igstrate, g.sgst as [sgstrate], g.cgst as[cgstrate],id.[cessrate],id.[basicamount],id.[rate],id.[netrate],id.[orderedquantity],
 --   id.[itemdiscpercent],id.[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],id.[totalamt],id.[remarks],
 --   id.qtyalreadydispatched, id.qtytodispatch,id.focqty,h.hsncode ,0 [weight],sb.batch,id.batchmfgdate, id.batchexpirydate,g.description as gstpercent
 --   from  db_mktg.quote_hdr_sale sh
 --   left join [db_mktg].quote_dtl_sale id on sh.id =id.invid
 --   left join [db_mktg].quote_dtl_sale sb on sh.id =sb.invid and id.itemid=sb.itemid
 --   left join [db_mm].[mst_item] im  on id.itemid= im.id
 --   left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	--left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	--left join [db_mm].[mst_hsn] h on id.hsnid = h.id  		 
	--where id.invid= @id 
	select id.id,piid,itemid,id.billingdescription,isnull(uom,'') uom,id.gstid,igstrate,sgstrate,cgstrate,cessrate,
	        basicamount,id.mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,
			cessamt,totalamt,isnull(id.remarks,'') remarks,focqty,hsnid,im.itemname,im.itemcode,im.oldcode,h.hsncode,
			g.description as gstpercent
	from db_mktg.dtl_quote_pi id	
	join [db_mm].[mst_item] im  on id.itemid= im.id
	--left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	where id.piid=@id

	-- tax summary
	Select 'IGST ' description,sum(netamt) amount, sum(igstamt) taxamount from [db_mktg].dtl_quote_pi 
	where piid= @id 
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_mktg].dtl_quote_pi
	where piid= @id  	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_mktg].dtl_quote_pi
	where piid= @id 	group by cgstrate having sum(isnull(cgstamt,0))>0
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
   create table #temp
   (
    id int ,
    description VARCHAR(300),
    amount  decimal(13,2)
    );
    insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, sum(id.netamt) amount from [db_mktg].dtl_quote_pi id where id.piid= @id group by piid
	union 
	--select 2 id, 'Discount Amount' description, isnull(itemdiscamt,0) amount from [db_mktg].dtl_quote_pi where piid= @id 
	select 2 id, 'Discount Amount' description, sum(isnull(itemdiscamt,0)) amount from [db_mktg].dtl_quote_pi where piid=@id group by piid
	union
	Select 3 id, 'IGST Amt' description,sum(igstamt) amount from [db_mktg].dtl_quote_pi 
	where piid= @id 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 4 id, 'SGST Amt' description,sum(sgstamt) amount from [db_mktg].dtl_quote_pi 
	where piid= @id  	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 5 id, 'CGST Amt' description,sum(cgstamt) amount from [db_mktg].dtl_quote_pi 
	where piid= @id  	group by cgstrate having sum(isnull(cgstamt,0))>0
	union 
	select 6 id, 'GRAND TOTAL' description, sum(isnull(totalamt,0)) amount from [db_mktg].dtl_quote_pi where piid= @id group by piid
	)
	select * from #temp order by id
	-- convert inv-Amt to words
	SELECT db_general.NumberToWords(isnull(orderamt,0),currency) NumberToWords from [db_mktg].hdr_quote_pi WHERE id=@id 
	--select  termsandcondition from [db_sop].[order_termsandconditions] where orderid=@oaid
	select  termsandcondition from [db_mktg].quote_pi_termsandconditions where piid=@id
    select  * from [db_mktg].quote_pi_paymentterms where piid=@id
    --select * from [db_sop].[dtl_sale_batches] where invid=@id
	select top(1) name,acno,branchcode,branch,swiftcode,ifsccode  from db_masters.bankmaster
END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_printquoteprint]    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,03-25-2019>
--  Description:	<Description,Get supplier data>
--  [db_mktg].[pr_printquoteprint]   1,1,90,1,1
--  =============================================

CREATE PROCEDURE [db_mktg].[pr_printquoteprint] 
	@coid int,
	@boid int,
	@quoteid int,
	@userid int,
	@fyid int,
	@accesstoken varchar(50)=null
AS
    BEGIN
	SET NOCOUNT ON;
	

		select  c.companyname,b.unitname,(isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' ' + isnull(b.city,'')+'-' + isnull(b.pin,'')) address,b.state,
	b.country,case when len(u.mobileno)>1 then ('+91-' + ltrim(u.mobileno)) else '' end phone_number,u.emailid email,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	join db_masters.users u on u.boid=b.boid
	where b.coid = @coid and b.boid = @boid and u.userid=@userid

	declare @symbol nvarchar=(	select symbol from db_mktg.hdr_quote q left join 
	 db_masters.currency c on q.currency=c.code where q.quoteid=@quoteid)

   SELECT @symbol as symbol, quoteno,revisedno,quotedate,customername,customeraddr1,customeraddr2,city,state,case when len(isnull(custphonenumber,''))>1 then 
  code+'-'+ ltrim(custphonenumber) else '' end customermobilenumber,
   custemail,title,gstin,remarks,senderinfo,offertype,country from 
    (select  hdr.quoteno,hdr.revisedno,format(hdr.quotedate,'dd/MM/yyyy') quotedate,hdr.customername,hdr.customeraddr1,hdr.customeraddr2,hdr.city,hdr.[state], 
	case when hdr.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	else (isnull(prspct.phone_number,'')+' '+ isnull(prspct.mobile_number,'')) 		 end as custphonenumber,		
	case when hdr.custtype='C' then cust.email 	    else prspct.email 		 end as custemail,
	case when hdr.custtype='C' then cust.title 	     else prspct.title		 end as title,
	case when hdr.custtype='C' then cust.gstin 	     else prspct.gstin		 end as gstin,
	hdr.remarks,hdr.senderinfo, quotert.type as offertype ,hdr.country,c.code
from db_mktg.hdr_quote hdr
	left join db_masters.customer cust on hdr.customerid=cust.id
	left join db_masters.prospectcustomers prspct on hdr.customerid=prspct.id
	left join [db_mktg].[mst_quoteratetype] quotert on hdr.quoteratetype = quotert.id
	left join db_masters.country c on hdr.country=c.countryname
	where hdr.quoteid=@quoteid) AS cutomerdetails


		
	-- invoice details
select @symbol as symbol, id.id,case when id.itemtype='I' then im.itemname				  else tm.name end as itemname, 
		    case when id.itemtype='I' then im.itemcode				 else tm.code end as itemcode,
			case when id.itemtype='I' then im.oldcode				 else tm.code end as oldcode,
			case when id.itemtype='I' then im.billingdescription				 else tm.description end as billingdescription,
     id.itemid,id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],id.[uom],id.[gstid],
	[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[rate] AS [netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]
	,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],h.hsncode,id.[remarks],id.[mrp],id.[focqty],id.itemtype,g.igst gst,(isnull([igstamt],0)+isnull([cgstamt],0)+isnull([sgstamt],0)) gstamt
	from [db_mktg].[dtl_quote] id 
	left join [db_mm].[mst_item] im  on id.itemid= im.id
	left join db_mktg.mst_tenderItemMaster tm on id.itemid= tm.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	left join [db_mm].[mst_hsn] h on id.hsnid=h.id
	where id.quoteid =@quoteid
		 
	 select * from  [db_mktg].[quote_termsandconditions] where quoteid=@quoteid

 
END






GO
/****** Object:  StoredProcedure [db_mktg].[pr_printquoterevisedprint]    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,01-08-2020>
--  Description:	<Description,Get Print revised data>
--  [db_mktg].[pr_printquoterevisedprint]   1,1,90,1,1
--  =============================================

CREATE PROCEDURE [db_mktg].[pr_printquoterevisedprint] 
	@coid int,
	@boid int,
	@quoteid int,
	@revisedid int,
	@userid int,
	@fyid int,
	@accesstoken varchar(50)=null
AS
    BEGIN
	SET NOCOUNT ON;
	

		select  c.companyname,b.unitname,(isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' ' + isnull(b.city,'')+'-' + isnull(b.pin,'')) address,b.state,
	b.country,case when len(u.mobileno)>1 then ('+91-' + ltrim(u.mobileno)) else '' end phone_number,u.emailid email,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	join db_masters.users u on u.boid=b.boid
	where b.coid = @coid and b.boid = @boid and u.userid=@userid

	declare @symbol nvarchar=(	select symbol from db_mktg.hdr_quote q left join 
	 db_masters.currency c on q.currency=c.code where q.quoteid=@quoteid)

   SELECT @symbol as symbol, quoteno,revisedno,quotedate,customername,customeraddr1,customeraddr2,city,state,case when len(isnull(custphonenumber,''))>1 then 
  code+'-'+ ltrim(custphonenumber) else '' end customermobilenumber,
   custemail,title,gstin,remarks,senderinfo,offertype,country from 
    (select  hdr.quoteno,hdr.revisedno,format(hdr.quotedate,'dd/MM/yyyy') quotedate,hdr.customername,hdr.customeraddr1,hdr.customeraddr2,hdr.city,hdr.[state], 
	case when hdr.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	else (isnull(prspct.phone_number,'')+' '+ isnull(prspct.mobile_number,'')) 		 end as custphonenumber,		
	case when hdr.custtype='C' then cust.email 	    else prspct.email 		 end as custemail,
	case when hdr.custtype='C' then cust.title 	     else prspct.title		 end as title,
	case when hdr.custtype='C' then cust.gstin 	     else prspct.gstin		 end as gstin,
	hdr.remarks,hdr.senderinfo, quotert.type as offertype ,hdr.country,c.code
from db_mktg.hdr_quote_revised hdr
	left join db_masters.customer cust on hdr.customerid=cust.id
	left join db_masters.prospectcustomers prspct on hdr.customerid=prspct.id
	left join [db_mktg].[mst_quoteratetype] quotert on hdr.quoteratetype = quotert.id
	left join db_masters.country c on hdr.country=c.countryname
	where hdr.quoteid=@quoteid AND hdr.revisedno=@revisedid) AS cutomerdetails


		
	-- invoice details
select @symbol as symbol, id.id,case when id.itemtype='I' then im.itemname				  else tm.name end as itemname, 
		    case when id.itemtype='I' then im.itemcode				 else tm.code end as itemcode,
			case when id.itemtype='I' then im.oldcode				 else tm.code end as oldcode,
			case when id.itemtype='I' then im.billingdescription				 else tm.description end as billingdescription,
     id.itemid,id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],id.[uom],id.[gstid],
	[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[rate] AS [netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]
	,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],h.hsncode,id.[remarks],id.[mrp],id.[focqty],id.itemtype,g.igst gst,(isnull([igstamt],0)+isnull([cgstamt],0)+isnull([sgstamt],0)) gstamt
	from [db_mktg].[dtl_quote_revised] id 
	left join [db_mm].[mst_item] im  on id.itemid= im.id
	left join db_mktg.mst_tenderItemMaster tm on id.itemid= tm.id
	left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	left join [db_mm].[mst_hsn] h on id.hsnid=h.id
	where id.quoteid =@quoteid AND id.revisedno=@revisedid
		 
	 select * from  [db_mktg].[quote_termsandconditions] where quoteid=@quoteid

 
END






GO
/****** Object:  StoredProcedure [db_mktg].[pr_report_commanapiformarketing]    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,03-08-2019>
-- Description:	<Description,Get supplier data>
-- [db_mktg].[pr_report_commanapiformarketing]   1,1,2,'enq'
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_report_commanapiformarketing] 
	@coid int,
	@boid int,
	@fyid int,
	@type varchar(20)
AS
BEGIN
	SET NOCOUNT ON;
-----	get distinct customers
  select id,'Customer  '+(name +' '+isnull(address1 ,'')+' '+ isnull(address2,' ')) name from db_masters.customer  c    where id in 
  (SELECT  distinct(customerid) FROM  [db_mktg].[hdr_enq]  h where h.custtype='C' and h.coid=@coid and h.boid=@boid and h.fyid=@fyid)
  union all
  select id,'Prospect  '+(name +' '+isnull(address1 ,'')+' '+ isnull(address2,' ')) name from [db_masters].[prospectcustomers] c    where id in 
  (SELECT  distinct(customerid) FROM  [db_mktg].[hdr_enq]  h where h.custtype='P' and h.coid=@coid and h.boid=@boid and h.fyid=@fyid)
  -----	get distinct businesssegement
   select id,businesssegementname name from db_masters.businesssegement where id in
    (SELECT  distinct(businesssegment) FROM  [db_mktg].[hdr_enq] h join  db_masters.customer  c on h.customerid=c.id where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)
-----	get distinct marketexecutive
    select userid id,firstname name from db_masters.users where userid in
	 (SELECT  distinct(marketexecutive) FROM [db_mktg].[hdr_enq] h where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)

	select id,status as enqstatus  from db_mktg.mst_enqstatus 

	select id,zonename from db_masters.zonemaster 

	SELECT id,regionname FROM db_masters.regionmaster



	 select 1 as id,'Enquiry Register' name
	 union ALL
	 Select 2 as id,'Quotation Register' name

END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_revisedprintcustomerinvoice]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- [db_mktg].[pr_revisedprintcustomerinvoice]  1,1,74
-- =============================================
CREATE PROCEDURE [db_mktg].[pr_revisedprintcustomerinvoice] 
	@coid int,
	@boid int,
	@id int,
	@revisedid int,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;
	-- header data -- company information
	--select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	--b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	--from db_general.company_branches b
	--join db_masters.company c on  b.coid = c.coid
	--where b.coid = @coid and b.boid = @boid
	select  c.companyname,b.unitname,(isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' ' + isnull(b.city,'')+'-' + isnull(b.pin,'')) address,b.state,
	b.country,case when len(u.mobileno)>1 then ('+91-' + ltrim(u.mobileno)) else '' end phone_number,u.emailid useremail,b.PAN, b.TAN ,insurance_info,b.gstno,c.website,c.code,b.mktginfo
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	join db_masters.users u on u.boid=b.boid
	where b.coid = @coid and b.boid = @boid and u.userid=@userid

	-- invoice and customer information
	--Select  s.id,  pino, pidate, confirmed, confirmedbyuserid, confirmedon, invno, invdate, revisedbyuserid, revisedon, cancelledon, cancelledbyuserid, invprefix, invpostfix, customerid, customername, 
 --   customeraddr1, customeraddr2, s.city, s.state, 
	--case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,	
	--case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,
	--case when s.custtype ='C' then cust.gstin else pcust.gstin end as customergstno,
	--case when s.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	--else (isnull(pcust.phone_number,'')+' '+ isnull(pcust.mobile_number,'')) 		 end as mobile_number,
	----case when s.custtype ='C' then cust.mobile_number else pcust.mobile_number end as mobile_number,
	----case when s.custtype ='C' then cust.phone_number  else pcust.phone_numbe end as phone_number,
	--billtocustomerid, billtocustomername, billtocustomeraddr1, billtocustomeraddr2, billtocity, billtostate, billtopin, billtocustomergstno, 
 --   consigneecustomerid, consigneecustomername, consigneecustomeraddr1, consigneecustomeraddr2, consigneecity, consigneestate, consigneepin, consigneecustomergstno, custPoNo, custPodate, basicamt, 
 --   discamt, netamt, igstamt, cgstamt, sgstamt, invamt, userid, approvedbymarketingheaduserid, approvedbycommercialuserid, approvedbyaccountsuserid, remarks, s.coid, s.boid, s.fyid, s.createdby, s.createdon, 
 --   s.modifiedby, s.modifiedon, invoicetype, customer_gstno, customer_phonenumber, customer_taxnumber, roundoff, concessionaltax, advancereceived, 
	--billseriesid,invoicetype type,sm.statecode,currency,symbol
 --   FROM   db_mktg.quote_hdr_sale s
 --   left join db_masters.statemaster sm on s.state=sm.statename
 --   left join db_masters.currency c on s.currency=c.code
	--left join db_masters.customer cust on s.customerid=cust.id
	--left join db_masters.prospectcustomers pcust on s.customerid=pcust.id
 --   where s.id =@id

    select s.id,piid,pino,pidate,quoteid,revisedno,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,s.city,s.state,
    case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,	
	case when s.custtype ='C' then cust.pin  else pcust.pin end as pin,
	case when s.custtype ='C' then cust.gstin else pcust.gstin end as customergstno,
	case when s.custtype='C' then (isnull(cust.phone_number,'')+' '+ isnull(cust.mobile_number,'')) 
	else (isnull(pcust.phone_number,'')+' '+ isnull(pcust.mobile_number,'')) 	end as mobile_number,
    customergstno,s.country,
    quoteNo,quotedate,bsegment,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,cancelledon,cancelledbyuserid,remarks,
    s.coid,s.boid,s.fyid,invoicetype,senderinfo,isconverttoorder,ordertype,conversionrate,Currency,c.symbol
    from db_mktg.hdr_quote_pi_revised s
    left join db_masters.statemaster sm on s.state=sm.statename
    left join db_masters.currency c on s.currency=c.code
    left join db_masters.customer cust on s.customerid=cust.id
    left join db_masters.prospectcustomers pcust on s.customerid=pcust.id
    where s.piid =@id and s.revisedno=@revisedid

 --   select [itemcode],im.[itemname],id.[itemid],id.[billingdescription],id.[isfoc],sh.custPoNo,id.[issample],id.[specialcode],id.[packing],
 --   u.[uom], id.[gstid],g.igst as igstrate, g.sgst as [sgstrate], g.cgst as[cgstrate],id.[cessrate],id.[basicamount],id.[rate],id.[netrate],id.[orderedquantity],
 --   id.[itemdiscpercent],id.[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],id.[totalamt],id.[remarks],
 --   id.qtyalreadydispatched, id.qtytodispatch,id.focqty,h.hsncode ,0 [weight],sb.batch,id.batchmfgdate, id.batchexpirydate,g.description as gstpercent
 --   from  db_mktg.quote_hdr_sale sh
 --   left join [db_mktg].quote_dtl_sale id on sh.id =id.invid
 --   left join [db_mktg].quote_dtl_sale sb on sh.id =sb.invid and id.itemid=sb.itemid
 --   left join [db_mm].[mst_item] im  on id.itemid= im.id
 --   left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	--left join [db_mm].[mst_gst] g on id.gstid=g.gstid
	--left join [db_mm].[mst_hsn] h on id.hsnid = h.id  		 
	--where id.invid= @id 

	select id.id,piid,id.revisedno,itemid,id.billingdescription,isnull(uom,'') uom,id.gstid,igstrate,sgstrate,cgstrate,cessrate,
	        basicamount,id.mrp,rate,netrate,orderedquantity,itemdiscpercent,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,
			cessamt,totalamt,isnull(id.remarks,'') remarks,focqty,hsnid,im.itemname,im.itemcode,im.oldcode,h.hsncode
	from db_mktg.dtl_quote_pi_revised id	
	join [db_mm].[mst_item] im  on id.itemid= im.id
	--left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	left join [db_mm].[mst_hsn] h on id.hsnid = h.id
	--left join [db_mm].[mst_gst] g on h.gstid=h.gstid
	where id.piid=@id and id.revisedno=@revisedid

	-- tax summary
	Select 'IGST ' description,sum(netamt) amount, sum(igstamt) taxamount from [db_mktg].dtl_quote_pi_revised 
	where piid= @id and revisedno=@revisedid
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_mktg].dtl_quote_pi_revised
	where piid= @id and revisedno=@revisedid group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_mktg].dtl_quote_pi_revised
	where piid= @id and revisedno=@revisedid	group by cgstrate having sum(isnull(cgstamt,0))>0
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
   create table #temp
   (
    id int ,
    description VARCHAR(300),
    amount  decimal(13,2)
    );
    insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, sum(netamt) amount from [db_mktg].dtl_quote_pi_revised id where id.piid= @id and revisedno=@revisedid
	union 
	select 2 id, 'Discount Amount' description, isnull(itemdiscamt,0) amount from [db_mktg].dtl_quote_pi_revised where piid= @id and revisedno=@revisedid
	union
	Select 3 id, 'IGST Amt' description,sum(igstamt) amount from [db_mktg].dtl_quote_pi_revised 
	where piid= @id and revisedno=@revisedid 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 4 id, 'SGST Amt' description,sum(sgstamt) amount from [db_mktg].dtl_quote_pi_revised 
	where piid= @id and revisedno=@revisedid 	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 5 id, 'CGST Amt' description,sum(cgstamt) amount from [db_mktg].dtl_quote_pi_revised 
	where piid= @id and revisedno=@revisedid 	group by cgstrate having sum(isnull(cgstamt,0))>0
		union 
	select 6 id, 'GRAND TOTAL' description, isnull(totalamt,0) amount from [db_mktg].dtl_quote_pi_revised where piid= @id and revisedno=@revisedid
	)
	select * from #temp order by id
	-- convert inv-Amt to words
	SELECT db_general.NumberToWords(isnull(orderamt,0),currency) NumberToWords from [db_mktg].hdr_quote_pi_revised WHERE id=@id and revisedno=@revisedid
	--select  termsandcondition from [db_sop].[order_termsandconditions] where orderid=@oaid
	select  termsandcondition from [db_mktg].quote_pi_termsandconditions_revised where piid=@id and revisedno=@revisedid

    select  * from [db_mktg].quote_pi_paymentterms_revised where piid=@id and revisedno=@revisedid
    --select * from [db_sop].[dtl_sale_batches] where invid=@id
	select top(1) name,acno,branchcode,branch,swiftcode,ifsccode  from db_masters.bankmaster
END



GO
/****** Object:  StoredProcedure [db_mktg].[pr_save_quote_pi]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_savequote_pi] 'Insert',13,1 

CREATE PROCEDURE [db_mktg].[pr_save_quote_pi]
@statementtype NVARCHAR(50),
@quoteprofomaheader [db_mktg].[hdr_quote_pi_tvp] READONLY,
@quoteproformadetail [db_mktg].[dtl_quote_pi_tvp] READONLY,
@leviesarray [db_mktg].[dtl_sale_levies_tvp] READONLY,
@paymentterms [db_mktg].[quote_pi_paymentterms_tvp] READONLY,
@termscondition [db_mktg].[quote_pi_termsandconditions_tvp] readonly,
@userid INT = 1
AS
BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @piid INT,@rowcnt INT,@colstring NVARCHAR(MAX),@sql NVARCHAR(MAX),@revisedno INT
	DECLARE @invno bigint,@pinno bigint
	DECLARE @concessionaltax bit

	BEGIN TRANSACTION
	 IF (@statementtype = 'Insert')
	 BEGIN	
		set @pinno = (Select ISNULL(MAX(pino),0) + 1 from [db_mktg].[hdr_quote_pi])
		INSERT INTO [db_mktg].[hdr_quote_pi]  
	    (pino, pidate, quoteid, marketexecutive, custtype, customerid, customername, customeraddr1, customeraddr2, city, state, pin, customergstno, country, quoteNo, quotedate, bsegment, basicamt, discamt, netamt, 
                         igstamt, cgstamt, sgstamt, orderamt, cessamt, roundoff, userid, cancelledon, cancelledbyuserid, remarks, coid, boid, fyid, createdby, createdon, isconverttoorder,
                        ordertype, conversionrate, Currency)
	    select @pinno, pidate, quoteid, marketexecutive, custtype, customerid, customername, customeraddr1, customeraddr2, city, state, pin, customergstno, country, quoteNo, quotedate, bsegment, basicamt, discamt, netamt, 
                         igstamt, cgstamt, sgstamt, totalamt, cessamt, roundoff, userid, cancelledon, cancelledbyuserid, remarks, coid, boid, fyid, @userid, getdate(),  isconverttoorder, 
						 ordertype, conversionrate, Currency
        from  @quoteprofomaheader 
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI header data.', 16, 1)
			RETURN
		END
		 set @piid = SCOPE_IDENTITY()

		INSERT INTO [db_mktg].[dtl_quote_pi]
		(piid, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid)
		select @piid, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid
	    from  @quoteproformadetail 
	    IF @@error <> 0
		BEGIN
		  -- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Details data.', 16, 1)
			RETURN
		END
		 -----------------------------------payment terms------------------------------------ 
		 insert into [db_mktg].[quote_pi_paymentterms]
		 (piid, srno, paymenttermid, paymentterm, createdby, createdon, [percent], amount)
		 select @piid, srno, paymenttermid, paymentterm, createdby, createdon,  [percent], amount from @paymentterms
		 IF @@error <> 0
		 BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Payment Terms Data data.', 16, 1)
			RETURN
		 END
		 ----------------------terms condition------------------------------------------------- 
		 insert into [db_mktg].[quote_pi_termsandconditions]
		 (piid, srno, termsandconditionsid, termsandcondition, createdby, createdon)
		  select @piid,srno, termsandconditionsid, termsandcondition, createdby, createdon from @termscondition
		 	IF @@error <> 0
		    BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Terms and condition  data.', 16, 1)
			RETURN
		    END
          --------------------Detail Levies------------------------------------------------------ 
		   insert into [db_mktg].[dtl_qoute_pi_levies]
		   (piid,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,createdby,createdon)
		   select @piid,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,@userid,getdate()
		   from  @leviesarray
		   IF @@error <> 0
		    BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Terms and condition  data.', 16, 1)
			RETURN
		    END


	  END

	  if (@statementtype='Update')
	  BEGIN

	  set @piid =(select id from @quoteprofomaheader)
	  
	  --Get Maximum revisedno 
	  set @revisedno=(SELECT isnull(max(revisedno),0) +1 FROM [db_mktg].[hdr_quote_pi_revised] WHERE piid=@piid)

	  --Entry into Quote Header Pi Revised
	  INSERT INTO [db_mktg].[hdr_quote_pi_revised] 
	    (piid,pino, pidate, quoteid,revisedno, marketexecutive, custtype, customerid, customername, customeraddr1, customeraddr2, city, state, pin, customergstno, country, quoteNo, quotedate, bsegment, basicamt, discamt, netamt, 
                         igstamt, cgstamt, sgstamt, orderamt, cessamt, roundoff, userid, cancelledon, cancelledbyuserid, remarks, coid, boid, fyid, createdby, createdon, isconverttoorder,
                         ordertype,conversionrate, Currency)
	    select @piid,pino, pidate, quoteid,@revisedno, marketexecutive, custtype, customerid, customername, customeraddr1, customeraddr2, city, state, pin, customergstno, country, quoteNo, quotedate, bsegment, basicamt, discamt, netamt, 
                         igstamt, cgstamt, sgstamt, orderamt, cessamt, roundoff, userid, cancelledon, cancelledbyuserid, remarks, coid, boid, fyid, @userid, getdate(),  isconverttoorder, 
                         ordertype,conversionrate, Currency
        from [db_mktg].[hdr_quote_pi] WHERE id=@piid

	  UPDATE [db_mktg].[hdr_quote_pi] set  
         pino =a.pino,
         pidate=a.pidate,
         quoteid=a.quoteid,
		 revisedno=@revisedno,
         marketexecutive=a.marketexecutive,
         custtype=a.custtype,
         customerid=a.customerid,
         customername=a.customername,
         customeraddr1=a.customeraddr1,
         customeraddr2=a.customeraddr2,
         city=a.city,
         [state]=a.state,
         pin=a.pin,
         customergstno=a.customergstno,
         country=a.country,
         quoteNo=a.quoteNo,
         quotedate=a.quotedate,
         bsegment=a.bsegment,
         basicamt=a.basicamt,
         discamt = a.discamt,
         netamt=a.netamt,
         igstamt=a.igstamt,
         cgstamt=a.cgstamt,
         sgstamt=a.sgstamt,
         cessamt=a.cessamt,
         roundoff=a.roundoff,
         userid=a.userid,
         cancelledon=a.cancelledon,
         cancelledbyuserid=a.cancelledbyuserid,
         remarks=a.remarks,
         coid=a.coid,
         boid=a.boid,
         fyid=a.fyid,
         modifiedby=@userid,
         modifiedon=getdate(),
         isconverttoorder=a.isconverttoorder,
		 ordertype=a.ordertype,
         conversionrate=a.conversionrate,
         Currency=a.currency
	     FROM  @quoteprofomaheader a 
		 where [db_mktg].[hdr_quote_pi].id = a.id 

		 --Entry into Quote Detail Pi Revised

		INSERT INTO [db_mktg].[dtl_quote_pi_revised]
		(piid,revisedno, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid)
		select @piid,@revisedno, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid
	    from  [db_mktg].[dtl_quote_pi] WHERE piid=@piid

		 Delete from [db_mktg].[dtl_quote_pi] where piid =@piid 

		 INSERT INTO [db_mktg].[dtl_quote_pi]
		 (piid, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		 netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid)
		 select @piid, itemid, billingdescription, uom, gstid, igstrate, sgstrate, cgstrate, cessrate, basicamount,  rate, netrate, orderedquantity, itemdiscpercent, itemdiscamt, 
		 netamt, igstamt, cgstamt, sgstamt, cessamt, totalamt, remarks, focqty, hsnid
	     from  @quoteproformadetail 

		 IF @@error <> 0
		 BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Payment Terms Data data.', 16, 1)
			RETURN
		 END

		 -----------------------------------payment terms------------------------------------ 

		 --Entry into Payment Terms Revised
		 insert into [db_mktg].[quote_pi_paymentterms_revised]
		 (piid, srno,revisedno, paymenttermid, paymentterm, createdby, createdon, [percent], amount)
		 select @piid, srno,@revisedno, paymenttermid, paymentterm, createdby, createdon,  [percent], amount from [db_mktg].[quote_pi_paymentterms] where piid =@piid

		 Delete from [db_mktg].[quote_pi_paymentterms] where piid =@piid

		 insert into [db_mktg].[quote_pi_paymentterms]
		 (piid, srno, paymenttermid, paymentterm, createdby, createdon, [percent], amount)
		 select @piid, srno, paymenttermid, paymentterm, createdby, createdon,  [percent], amount from @paymentterms
		 IF @@error <> 0
		 BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Payment Terms Data data.', 16, 1)
			RETURN
		 END
		 ----------------------terms condition------------------------------------------------- 

		 --Entry into Terms Condition Revised
		 insert into [db_mktg].[quote_pi_termsandconditions_revised]
		 (piid, srno,revisedno, termsandconditionsid, termsandcondition, createdby, createdon)
		  select @piid,srno,@revisedno, termsandconditionsid, termsandcondition, createdby, createdon from [db_mktg].[quote_pi_termsandconditions] where piid =@piid

		 Delete from [db_mktg].[quote_pi_termsandconditions] where piid =@piid 

		 insert into [db_mktg].[quote_pi_termsandconditions]
		 (piid, srno, termsandconditionsid, termsandcondition, createdby, createdon)
		  select @piid,srno, termsandconditionsid, termsandcondition, createdby, createdon from @termscondition
		 	IF @@error <> 0
		    BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Terms and condition  data.', 16, 1)
			RETURN
		    END
          --------------------Detail Levies------------------------------------------------------ 
		  --Entry into Detail Levies Revised
		   insert into [db_mktg].[dtl_qoute_pi_levies_revised]
		   (piid,revisedno,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,createdby,createdon)
		   select @piid,@revisedno,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,@userid,getdate()
		   from  [db_mktg].[dtl_qoute_pi_levies] where piid =@piid 

		   Delete from [db_mktg].[dtl_qoute_pi_levies] where piid =@piid 

		   insert into [db_mktg].[dtl_qoute_pi_levies]
		   (piid,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,createdby,createdon)
		   select @piid,levyid,quantity,rate,uom,uomid,amount,hsncode,gstid,igstamt,cgstamt,sgstamt,igstrate,cgstrate,sgstrate,@userid,getdate()
		   from  @leviesarray
		   IF @@error <> 0
		    BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding Quote PI Terms and condition  data.', 16, 1)
			RETURN
		    END
	  END
	   -- Update db_mktg.hdr_quote set isconverttoinvoice = 1 where quoteid=@quoteid
   COMMIT
      select @piid as piid
  END

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

CREATE PROCEDURE [db_mktg].[pr_saveenqactions] 
    @statementtype varchar(100),	   
	@userid int,
	@coid int,
	@boid int,
	@fyid int,
	@enqid bigint,
	@rejectionremarks varchar(100)=null,
	@rejectid int=null,
	@dealerids varchar(100),
	@deptids varchar(100),
	@status int,
	@intimationto int=null
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
   BEGIN TRANSACTION     
	if(@statementtype='Update')
	-- select * from db_mktg.hdr_enq
	 BEGIN	   
	  Update db_mktg.hdr_enq set enqstatus=@status, rejectionid=@rejectid,rejectionremark=@rejectionremarks, intimationto=@intimationto,
	         dealerid=@dealerids,deptid=@deptids
	  where id =@enqid
	 End	 		
   commit
END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_saveenqfollowup]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mktg].[pr_saveenqfollowup] 
    @statementtype nvarchar(50),
	@enqheader  [db_mktg].[hdr_enq_tvp] readonly,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@remarks varchar(500),
	@nextfollowupdate varchar(20),
	@escalateto bigint=1,
	@cdate varchar(20),
	@ctime varchar(22)
	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @enqid int, @enqno int,@error VARCHAR(100),@enqdate date
	BEGIN TRANSACTION 

	if (@statementtype='Insert')
	   BEGIN
	      
			-- fetching quote id from table type
			select top 1 @enqid = [id] from @enqheader

			select top 1 @enqno = [id] from @enqheader

			select top 1 @enqdate = [enqdate] from @enqheader
			
			UPDATE db_mktg.hdr_enq  set lastfollowupdate=@cdate , [nextfollowupdate]= @nextfollowupdate ,enqstatus=4
			FROM   @enqheader a WHERE  db_mktg.hdr_enq.id=a.id

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

             insert into db_mktg.followup_enq
			 (enqid,cdate,ctime,nextfollowupdate,remarks,escalateto,coid,boid,fyid,createdby,createdon)
			 values(@enqid,@cdate,@ctime,@nextfollowupdate,@remarks,@escalateto,@coid,@boid,@fyid,@userid,getdate())

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


			 insert into db_general.notifications 
			 (templateid,senderid,receiverid,notificationdate,notificationtext,[status],escalateto,escalationtime,isescalated,parentid,isactive)
			 select u.templateid,@userid,gu.userid, @enqdate,t.templatetext,'Pending',null,null,null,0,1
             from db_general.notification_template_users u
             inner join db_general.mst_notification_templates t on t.id = u.templateid
             inner join db_general.notification_user_groups g on g.id = u.groupid 
             inner join db_general.notification_group_users gu on gu.groupid = g.id
             where u.notificationid = 15



     End
  commit

END

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

CREATE PROCEDURE [db_mktg].[pr_saveenquiry] 
    @statementtype nvarchar(50),
	@enqheader  [db_mktg].[hdr_enq_tvp] readonly,
	@enqdetail  [db_mktg].[dtl_enq_tvp] readonly,
	@enqbseg    [db_mktg].[hdr_enqbseg_tvp] readonly,
	@userid int=1,
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @enqid int, @rowcnt int,@suplid int, @colstring nvarchar(max),@sql nvarchar(max),@enqno bigint,@enqdate date
	DECLARE @error VARCHAR(100),@username varchar(200)
	BEGIN TRANSACTION 
		If (@statementtype='Insert')
		BEGIN
			set @enqno = (SELECT ISNULL(MAX(enqno), 0) + 1 as enqno from [db_mktg].hdr_enq where coid=@coid and boid=@boid) 
			set @enqdate =(select enqdate from @enqheader)
		    insert into [db_mktg].[hdr_enq]
			(enqno,enqdate,enqsourceid,enqtype,custtype,marketexecutive,fwdmarketexcecutive,businesssegment,enqstage,buisnesssizeid,custinteractiondoneby,custinteractiondoneon,custinteractionremarks,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,contactname,
			 contactphone,contactdesignation,contactdept,quoteid,quoteNo,quotedate,userid,enqstatus,enqstatusremarks,IsEnqFwd,coid,boid,fyid,createdby,createdon,IsTender,tender_openingon,tender_publishon,tender_dueon,enqrefremarks,contactemail,splattn,splremarks,tenderfee,emdamt,BGamt,BGper,iscustomermeetingdone,country)
			Select @enqno,@enqdate,enqsourceid,enqtype,custtype,marketexecutive,fwdmarketexcecutive,businesssegment,enqstage,buisnesssizeid,custinteractiondoneby,custinteractiondoneon,custinteractionremarks,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,contactname,
			        contactphone,contactdesignation,contactdept,quoteid,quoteNo,quotedate,userid,1,enqstatusremarks,IsEnqFwd,coid,boid,fyid,createdby,getdate(),IsTender,tender_openingon,tender_publishon,tender_dueon
,enqrefremarks,contactemail,splattn,splremarks,tenderfee,emdamt,BGamt,BGper,iscustomermeetingdone,country
			from @enqheader	
			IF @@ERROR <> 0
					BEGIN
					-- Rollback the transaction
					ROLLBACK     
					-- Raise an error and return
					RAISERROR ('Error while adding Enq header data.', 16, 1)
					SET @error = 'Error while adding Enq header data.  error no: ' + CAST(@@error AS VARCHAR(3))
					RETURN @error 
				END
				SELECT @enqid= SCOPE_IDENTITY()		
				insert into [db_mktg].[dtl_enq]
				      (enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,createdby,createdon,uom)
				select @enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,@userid,getdate(),uom
				from @enqdetail
				IF @@ERROR <> 0
					BEGIN
					-- Rollback the transaction
					ROLLBACK
					-- Raise an error and return
						RAISERROR ('Error while adding Enq detail data.', 16, 1)
					SET @error = 'Error while adding Enq detail data.  error no: ' + CAST(@@error AS VARCHAR(800))
					RETURN @error 
					END 
			       insert into db_mktg.dtl_bsegmt_enq(enqid,bsegmtid,qty,createdby,createdon)  
			       select @enqid,id,value,@userid,getdate() from @enqbseg  
				  insert into db_general.notifications 
			      (templateid,senderid,receiverid,notificationdate,notificationtext,[status],escalateto,escalationtime,isescalated,parentid,isactive)
				  select u.templateid,@userid,gu.userid, getdate(),t.templatetext,'Pending',null,null,null,0,1
                  from db_general.notification_template_users u
                  inner join db_general.mst_notification_templates t on t.id = u.templateid
                  inner join db_general.notification_user_groups g on g.id = u.groupid 
                  inner join db_general.notification_group_users gu on gu.groupid = g.id
                  where u.notificationid = 12
			    End								 
	else
		  Begin 
		     -- begin of update 
			-- fetching quote id from table type
			select top 1 @enqid = [id] from @enqheader

			select top 1 @enqno = [id] from @enqheader

			select enqno,enqdate,enqsourceid,custtype,marketexecutive,businesssegment,enqstage,buisnesssizeid,custinteractiondoneby,custinteractiondoneon,custinteractionremarks,customerid,[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],contactname,contactphone,contactdesignation,contactdept,quoteid,
			       quoteNo,quotedate,userid,enqstatus,enqstatusremarks,IsEnqFwd,coid,boid,fyid,IsTender,tender_openingon,tender_publishon,tender_dueon
			from [db_mktg].[hdr_enq] where id =@enqid 

			EXCEPT select enqno,enqdate,enqsourceid,custtype,marketexecutive,businesssegment,enqstage,buisnesssizeid,custinteractiondoneby,custinteractiondoneon,custinteractionremarks,customerid,[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],contactname,contactphone,contactdesignation,contactdept,quoteid,
			       quoteNo,quotedate,userid,enqstatus,enqstatusremarks,IsEnqFwd,coid,boid,fyid,IsTender,tender_openingon,tender_publishon,tender_dueon
			from @enqheader
			SELECT @rowcnt = @@ROWCOUNT
			IF @rowcnt > 0
				BEGIN 
					   UPDATE db_mktg.hdr_enq  set 
					   modifiedby=@userid,
					   modifiedon=getdate(),
					   [enqno]   = a.enqno,
                       [enqdate] = a.enqdate,
                       [enqsourceid] = a.enqsourceid,
                       [custtype] = a.custtype,
                       [marketexecutive]= a.marketexecutive,
                       [businesssegment]= a.businesssegment,
                       [enqstage] = a.enqstage,
                       [buisnesssizeid]= a.buisnesssizeid,
                       [custinteractiondoneby]=a.custinteractiondoneby,
                       [custinteractiondoneon]= a.custinteractiondoneon,
                       [custinteractionremarks]=a.custinteractionremarks,
                       [customerid]= a.customerid,
					   [customername]=a.[customername],
					   [customeraddr1]=a.[customeraddr1],
					   [customeraddr2]=a.[customeraddr2],
					   [city]=a.[city],
					   [state]=a.[state],
					   [pin]=a.[pin],
                       [contactname]= a.contactname,
                       [contactphone]= a.contactphone,
                       [contactdesignation]= a.contactdesignation,
                       [contactdept]= a.contactdept,
                       [quoteid]= a.quoteid,
                       [quoteNo]=a.quoteNo,
                       [quotedate]= a.quotedate,                   
                       [enqstatusremarks]= a.enqstatusremarks,
                       [IsEnqFwd]= a.IsEnqFwd,
                       [coid]= a.coid,
                       [boid]= a.boid,
                       [fyid]= a.fyid,                      
                       [lastfollowupdate]=a.lastfollowupdate,
                       [nextfollowupdate]=a.nextfollowupdate,
                       [IsTender]=a.IsTender,
                       [tender_openingon]= a.tender_openingon,
                       [tender_publishon]=a.tender_publishon,
                       [tender_dueon]=a.tender_dueon,
					   [enqrefremarks]= a.enqrefremarks,
					   [contactemail]= a.contactemail,
					   [enqtype]= a.enqtype,
					   [fwdmarketexcecutive]= a.fwdmarketexcecutive,
					   [splattn]=a.splattn,
					   [splremarks]= a.splremarks,
					   [tenderfee] =a.tenderfee,
					   [emdamt]=a.emdamt,
					   [BGamt]=a.BGamt,
					   [BGper]=a.BGper,
					   [enqstatus]=1,
					   [iscustomermeetingdone]=a.iscustomermeetingdone,
					   [country]=a.country				   				   				
					FROM  @enqheader a
					WHERE db_mktg.hdr_enq.id=a.id
				End
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
			-- error in except statement and in data insertion in bkup db
				select enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,uom
				from  @enqdetail
				EXCEPT 
				select @enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,uom
					   from [db_mktg].[dtl_enq] where [enqid] =@enqid				
				SELECT @rowcnt = @@ROWCOUNT
				-- data needs to update if query returns a row  
				IF @rowcnt > 0
				   BEGIN -- begin of row count						
					 delete from [db_mktg].[dtl_enq] where [enqid] =@enqid
					insert into [db_mktg].[dtl_enq]
				    (enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,createdby,createdon,lastfollowupdate,nextfollowupdate,uom)
				    select @enqid,itemid,itemtype,qtyreqd,deliveryindays,itemremarks,buisnesssegment,coid,boid,fyid,@userid,getdate(),lastfollowupdate,nextfollowupdate,uom
				    from @enqdetail
						-- 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 po termsandconditions record.', 16, 1)
								RETURN
							END
				   End  
			IF @rowcnt > 0
			Begin				     
			 DELETE from  [db_mktg].dtl_bsegmt_enq where enqid=@enqid
		     insert into [db_mktg].dtl_bsegmt_enq(enqid,bsegmtid,qty,createdby,createdon)  
		     select @enqid,id,value,@userid,getdate() from @enqbseg     
	        End
	 End
commit
END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_saveenquirycategoryrights]    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_mktg].[pr_saveenquirycategoryrights] 
@coid int,
@boid int,	
@userid int,
@rights_tvp [db_mktg].[enquirycategory_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_mktg].[enquirycategory_userrights] where userid = @user and 
	categoryid not in (select categoryid from @rights_tvp)
	
	-- insert new records
	insert into [db_mktg].[enquirycategory_userrights] (userid,categoryid,coid,boid,createdby,createdon)
	select userid,categoryid,coid,boid,@userid,getdate() from @rights_tvp  
	where categoryid not in (select categoryid from [db_mktg].[enquirycategory_userrights] where userid = @user) 

	select * from [db_mktg].[enquirycategory_userrights] where userid = @user 

END



GO
/****** Object:  StoredProcedure [db_mktg].[pr_saveenquirytoquote]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_saveenquirytoquote] 'Insert',40085,1,1,1,1

CREATE  PROCEDURE [db_mktg].[pr_saveenquirytoquote] 
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @oaid int, @rowcnt int,@custid bigint, @colstring nvarchar(max),@sql nvarchar(max),@quoteid int,@quoteno int,
	@Currency varchar(10),@custtype varchar(10),@username varchar(10)
	DECLARE @error VARCHAR(100)
	BEGIN TRANSACTION 
    If (@statementtype='Insert')
		BEGIN
			set @quoteid = (SELECT ISNULL(MAX(quoteid), 0) + 1 FROM [db_mktg].[hdr_quote])
			set @quoteno = (SELECT ISNULL(MAX(quoteno), 0) + 1 as quoteno from [db_mktg].hdr_quote where coid=@coid and boid=@boid) 
			set @custtype = (select enq.custtype from db_mktg.hdr_enq enq where enq.id = @enqid)
			set @custid =  (select enq.customerid from db_mktg.hdr_enq enq where enq.id = @enqid )
			set @userid =  (select enq.userid from db_mktg.hdr_enq enq where enq.id =@enqid)
			set @username = (select username from db_masters.users where userid=@userid)

			if(@custtype='P') 
			set @Currency = (select isnull(currency_preference,'') from db_masters.prospectcustomers where id=@custid)
			else 
			set @Currency = (select isnull(currency_preference,'') from db_masters.customer where id=@custid)
		    insert into [db_mktg].[hdr_quote]
			(quoteid,quoteno,quotedate,enqid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,enqNo,enqdate,quotstage,bsegment,
			[coid],[boid],[fyid],[createdby],[createdon],quotestatus,country,Currency,conversionrate,remarks,senderinfo)
			select @quoteid,@quoteno,enqdate,id,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,enqno,enqdate,enqstage,businesssegment, 
			coid,boid,fyid,1,getdate(),1,country,@Currency,1,'<p><strong>Subject</strong> :</p><p>Dear Sir,</p><p>Details of Spares required from your side are mentioned below:</p>',
			'<p>Thanks & Regards</p><p>'+@username+'</p>'
			from db_mktg.hdr_enq where id=@enqid
		    insert into db_mktg.dtl_bsegmt_Quote(Quoteid,bsegmtid,qty,createdby,createdon)  
		    select @quoteid,bsegmtid,1,1,getdate() from db_mktg.dtl_bsegmt_enq  
			 IF @@ERROR <> 0
			   BEGIN
				-- Rollback the transaction
				ROLLBACK     
				-- Raise an error and return
				RAISERROR ('Error while adding Quote header data.', 16, 1)
				SET @error = 'Error while adding po header data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
			 END
             insert into [db_mktg].[dtl_quote]
			  (quoteid,itemid,billingdescription,isfoc,issample,specialcode,packing,itemtype,coid,boid,fyid,orderedquantity)
				select @quoteid,[itemid],'',0,0,'','',itemtype,@coid,boid,@fyid,qtyreqd from db_mktg.dtl_enq where enqid=@enqid
				IF @@ERROR <> 0
					BEGIN
					-- Rollback the transaction
					ROLLBACK
					-- Raise an error and return
						RAISERROR ('Error while adding Quote detail data.', 16, 1)
					SET @error = 'Error while adding Quote detail data.  error no: ' + CAST(@@error AS VARCHAR(800))
					RETURN @error 
					END
				insert into [db_mktg].[quote_paymentterms] ([quoteid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[coid],[boid],[percent],[amount])
				select @quoteid ,srno,id,name,createdby,getdate(),coid,boid,0,0 from db_mktg.mst_paymentterms
					IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding po pyt data.', 16, 1)
						SET @error = 'Error while adding po pyt data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
				-- INSERT TERMS AND CONDITIONS
				 insert into [db_mktg].[quote_termsandconditions] 
				([quoteid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon])
				 select @quoteid,[srno],id,name,@userid,getdate()from db_mktg.mst_termsandconditions WHERE isexport IS NULL
					IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding quote terms data.', 16, 1)
						SET @error = 'Error while adding quote terms data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
				-- INSERT DOCUMENT REQUIRED
				insert into [db_mktg].[quote_documentsreqd]
			    ([quoteid],[srno],[documentid],[documentinfo],[createdby],[createdon])
				select @quoteid,[srno],id,name,@userid,getdate() from db_mktg.mst_documentsreqd
				 	IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding sop delivery data.', 16, 1)
						SET @error = 'Error while adding sop delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
			   -- INSERT INSTALLATION INFORMATION
				 insert into [db_mktg].[quote_installationinfo]
				 ([quoteid],[srno],[installationid],[installationinfo],[createdby],[createdon])
				 select @quoteid,[srno],id,name,@userid,getdate() from db_mktg.mst_installationinfo
				 	IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding sop installation information.', 16, 1)
						SET @error = 'Error while adding sop installation information.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
				     END
		   END	
  COMMIT
     Update db_mktg.hdr_enq set quoteid=@quoteid ,quoteNo=@quoteno where id=@enqid
     select @quoteid quoteid,@quoteno quoteno
END

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

CREATE PROCEDURE [db_mktg].[pr_savefwdtodealer]
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@dealerid varchar(100)


AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100)
	BEGIN TRANSACTION 
	if (@statementtype='Insert')
	BEGIN
       insert into [db_mktg].[fwdtodealer_enq](enqid,dealerid,coid,boid,fyid,createdby,createdon)
	   values(@enqid,@dealerid,@coid,@boid,@fyid,@userid,getdate())
    End

	if (@statementtype='Update')
	BEGIN
	 
	   delete from [db_mktg].[fwdtodealer_enq] where enqid=@enqid

	   update [db_mktg].[fwdtodealer_enq] set dealerid=@dealerid,coid=@coid,boid=@boid 
	   where enqid=@enqid
	End
  commit
END

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

CREATE PROCEDURE [db_mktg].[pr_savefwdtodept]
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@deptids varchar(100)	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100) 
	if (@statementtype='Insert')
	    BEGIN        
		insert into [db_mktg].[fwdtodepartment_enq](enqid,deptid,coid,boid,fyid,createdby,createdon)
	     values(@enqid,@deptids,@coid,@boid,@fyid,@userid,getdate()) 
	  	 		 	            
		End
     if (@statementtype='Update')
	    BEGIN

		 Delete from [db_mktg].[fwdtodepartment_enq] where enqid=@enqid

		 Update [db_mktg].[fwdtodepartment_enq] set deptid=@deptids,coid=@coid,boid=@boid,modifiedby=@userid,
		 modifiedon =getdate() where enqid=@enqid		
		End
END

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

CREATE PROCEDURE [db_mktg].[pr_saveholdreason]
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@holddate date,
	@holdremarks varchar(100)
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100)

	BEGIN TRANSACTION 
	if (@statementtype='Insert')
	   BEGIN			
			UPDATE db_mktg.hdr_enq  set ishold = 1, holddate = @holddate, holdremark=@holdremarks,enqstatus=5  where id=@enqid
     End
	 	if (@statementtype='Update')
	   BEGIN			
			UPDATE db_mktg.hdr_enq  set ishold = 1, holddate = @holddate, holdremark=@holdremarks,enqstatus=5 where id=@enqid
     End
  commit
END

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

CREATE PROCEDURE [db_mktg].[pr_saveIntimationto]
    @statementtype nvarchar(50),
	@enqid  bigint,
	@userid int=1,
	@coid   int=1,
	@boid   int=1,
	@fyid   int=1,
	@intimationto int
	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @error VARCHAR(100)
	BEGIN TRANSACTION 

	if (@statementtype='Insert')
     begin	   
	   update db_mktg.hdr_enq set intimationto = @intimationto ,ishold=null,holddate=null,rejectionid=null,rejectionremark=null 
	   where id=@enqid
	 end
	 if (@statementtype='Update')
     begin	   
	   update db_mktg.hdr_enq set intimationto = @intimationto ,ishold=null,holddate=null,rejectionid=null,rejectionremark=null 
	   where id=@enqid
	 end
  commit
END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_savequotation]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mktg].[pr_savequotation] 
    @statementtype nvarchar(50),
	@Quoteheader  [db_mktg].[hdrquote_tvp] readonly,
	@Quotedetail  [db_mktg].[dtl_quote_tvp] readonly,
	@Quotebseg    [db_mktg].[hdr_enqbseg_tvp] readonly,
	@Quotepaymentterm [db_mktg].[Quote_paymentterms_tvp] readonly,
	@Quotetermsandcondition [db_mktg].[quote_termsandconditions_tvp] readonly,
	@Quotedocumentsrequired [db_mktg].[quote_documentsreqd_tvp] readonly,
	@QuoteInstallationInfo  [db_mktg].[quote_installationinfo_tvp] readonly,
	@QuoteImageInfo  [db_mktg].[quote_images_tvp] readonly,
	@userid int=1,
	@coid int,
	@boid int,
	@fyid int,
	@imagepath varchar=null
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @oaid int, @rowcnt int,@suplid int, @colstring nvarchar(max),@sql nvarchar(max),@quoteid BIGINT,@quoteno BIGINT,@revisedno INT
	DECLARE @error VARCHAR(100)
	BEGIN TRANSACTION 
		If (@statementtype='Insert')
		BEGIN
	
			set @quoteid = (SELECT ISNULL(MAX(quoteid), 0) + 1 FROM [db_mktg].[hdr_quote])
			set @quoteno = (SELECT ISNULL(MAX(quoteno), 0) + 1 as quoteno from [db_mktg].hdr_quote where coid=@coid and boid=@boid and fyid=@fyid) 
		    insert into [db_mktg].[hdr_quote](quoteid,revisedno,quoteno,quotedate,enqid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,customergstno,customercontactpersonname,customercontactpersonphone,customercontactpersondesignation,customercontactpersondepartment,enqNo,enqdate,quotstage,bsegment,
			ourquoteno,ourquotedate,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,[remarks],[coid],[boid],[fyid],
			[createdby],[createdon],quotestatus,[quoteratetype],[senderinfo],country,ordertype,Currency,conversionrate,isconverttoinvoice)
			Select @quoteid,0,@quoteno,[quotedate],enqid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,customergstno,customercontactpersonname,customercontactpersonphone,customercontactpersondesignation,customercontactpersondepartment,enqNo,enqdate,quotstage,bsegment,
			ourquoteno,ourquotedate,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,[remarks],[coid],[boid],[fyid],[createdby]
			,getdate(),1,[quoteratetype],senderinfo,country,ordertype,Currency,conversionrate ,0 from @Quoteheader
		    insert into db_mktg.dtl_bsegmt_Quote(Quoteid,bsegmtid,qty,createdby,createdon)  
		    select @quoteid,id,value,@userid,getdate() from @Quotebseg     
				IF @@ERROR <> 0
					BEGIN
					-- Rollback the transaction
					ROLLBACK     
					-- Raise an error and return
					RAISERROR ('Error while adding Quote header data.', 16, 1)
					SET @error = 'Error while adding Quote header data.  error no: ' + CAST(@@error AS VARCHAR(3))
					RETURN @error 
					END
				--SELECT @oaid= SCOPE_IDENTITY()		
				insert into [db_mktg].[dtl_quote]
				(quoteid,itemid,billingdescription,isfoc,issample,specialcode,packing,uom,igstrate,sgstrate,cgstrate,cessrate,basicamount,mrp,rate,netrate,orderedquantity,itemdiscamt,netamt,igstamt,cgstamt,sgstamt,cessamt,totalamt,qtyalreadydispatched,qtytodispatch,coid,boid,fyid,focqty,itemtype,gstid,hsnid)
				select @quoteid,[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],itemtype,gstid,hsnid
				from @Quotedetail
				IF @@ERROR <> 0
					BEGIN
					-- Rollback the transaction
					ROLLBACK
					-- Raise an error and return
						RAISERROR ('Error while adding Quote detail data.', 16, 1)
					SET @error = 'Error while adding Quote detail data.  error no: ' + CAST(@@error AS VARCHAR(800))
					RETURN @error 
					END
				insert into [db_mktg].[quote_paymentterms] ([quoteid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[coid],[boid],[percent],[amount])
				select @quoteid,[srno],[paymenttermid],[paymentterm],[createdby],getdate(),[coid],[boid],[percent],[amount] from @Quotepaymentterm
					IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding po pyt data.', 16, 1)
						SET @error = 'Error while adding po pyt data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
				-- INSERT TERMS AND CONDITIONS
				insert into [db_mktg].[quote_termsandconditions] ([quoteid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon])
				select @quoteid,[srno],[termsandconditionsid],[termsandcondition],[createdby],getdate()from @Quotetermsandcondition
					IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding quote terms data.', 16, 1)
						SET @error = 'Error while adding quote terms data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
				-- INSERT DOCUMENT REQUIRED
				insert into [db_mktg].[quote_documentsreqd]([quoteid],[srno],[documentid],[documentinfo],[createdby],[createdon])
				select @quoteid,[srno],[documentid],[documentinfo],@userid,getdate() from @Quotedocumentsrequired
				 	IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding sop delivery data.', 16, 1)
						SET @error = 'Error while adding sop delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
				-- INSERT INSTALLATION INFORMATION
				insert into [db_mktg].[quote_installationinfo]
				([quoteid],[srno],[installationid],[installationinfo],[createdby],[createdon])
				select @quoteid,[srno],[installationid],[installationinfo],@userid,getdate() from @QuoteInstallationInfo
				 	IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding quote installation information.', 16, 1)
						SET @error = 'Error while adding quote installation information.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
						END
						-- INSERT Images
				insert into [db_mktg].[quote_images]([quoteid],[srno],[imageinfo],remarks,[isactive],[createdby],[createdon])
				select @quoteid,[srno],@imagepath+'\'+imageinfo,remarks,[isactive],@userid,getdate() from @QuoteImageInfo
				 	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
	else
		  Begin -- begin of update 
			-- fetching quote id from table type
			select top 1 @quoteid = [quoteid] from @Quoteheader
			select [quoteid],[quoteno],[quotedate],[enqid],[marketexecutive],[custtype], [customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
             [customercontactpersondepartment],[enqNo],[enqdate],[quotstage],[bsegment],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[cessamt],[roundoff],[userid],[quotestatus],[remarks],[coid],[boid]
            ,[fyid]
			from [db_mktg].[hdr_quote] where quoteid =@quoteid 
			EXCEPT select [quoteid],[quoteno],[quotedate],[enqid],[marketexecutive],[custtype], [customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
            [customercontactpersondepartment],[enqNo],[enqdate],[quotstage],[bsegment],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[cessamt],[roundoff],[userid],[orderstatus],[remarks],[coid]
            ,[boid],[fyid]
			from @Quoteheader
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0

			set @revisedno=(SELECT isnull(max(revisedno),0) +1 FROM [db_mktg].[hdr_quote_revised] WHERE quoteid=@quoteid)

			---Entry into quote header revised
			INSERT INTO [db_mktg].[hdr_quote_revised] (quoteid,revisedno,quoteno,quotedate,enqid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,customergstno,customercontactpersonname,customercontactpersonphone,customercontactpersondesignation,customercontactpersondepartment,enqNo,enqdate,quotstage,bsegment,
			ourquoteno,ourquotedate,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,[remarks],[coid],[boid],[fyid],
			[createdby],[createdon],quotestatus,[quoteratetype],[senderinfo],country,ordertype,Currency,conversionrate,isconverttoinvoice)
			Select @quoteid,@revisedno,quoteno,[quotedate],enqid,marketexecutive,custtype,customerid,customername,customeraddr1,customeraddr2,city,[state],pin,customergstno,customercontactpersonname,customercontactpersonphone,customercontactpersondesignation,customercontactpersondepartment,enqNo,enqdate,quotstage,bsegment,
			ourquoteno,ourquotedate,basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,cessamt,roundoff,userid,[remarks],[coid],[boid],[fyid],[createdby]
			,getdate(),1,[quoteratetype],senderinfo,country,ordertype,Currency,conversionrate ,0 FROM db_mktg.hdr_quote hdr WHERE hdr.quoteid=@quoteid
	
				BEGIN 
					UPDATE db_mktg.hdr_quote  set 
					revisedno=@revisedno,
					[quotedate]=a.[quotedate],
					[customerid]=a.[customerid],
					[custtype] = a.custtype,
					[customername]=a.[customername],
					[customeraddr1]=a.[customeraddr1],
					[customeraddr2]=a.[customeraddr2],
					[city]=a.[city],
					[state]=a.[state],
					[pin]=a.[pin],
					[marketexecutive]=a.[marketexecutive],
					[customergstno]=a.[customergstno],
					[customercontactpersonname]=a.[customercontactpersonname],
					[customercontactpersonphone]=a.[customercontactpersonphone],
					[customercontactpersondesignation]=a.[customercontactpersondesignation],
					[customercontactpersondepartment]=a.[customercontactpersondepartment],					
					[enqNo]=a.[enqno],
					[enqdate]=a.[enqdate],
					[quotstage] = a.[quotstage],
					[bsegment] = a.[bsegment],
					[ourquoteno]=a.[ourquoteno],
					[ourquotedate]=a.[ourquotedate],
					[basicamt]= a.[basicamt],
					[discamt]= a.[discamt],
					[netamt]= a.[netamt],
					[igstamt]= a.[igstamt],
					[cgstamt]= a.[cgstamt],
					[sgstamt]= a.[sgstamt],
					[orderamt]= a.[orderamt],
					[cessamt]= a.[cessamt],
					[roundoff]= a.[roundoff],
					[userid] = a.[userid],
					[remarks]=a.[remarks],
					[quotestatus]=1,
					[quoteratetype]=a.[quoteratetype],
					[senderinfo]=a.[senderinfo],
					[country]=a.[country],
					[ordertype]= a.ordertype,
					[Currency]=a.Currency,
					[conversionrate]=a.conversionrate	,
					isconverttoinvoice=0
					FROM   @Quoteheader a
					WHERE  db_mktg.hdr_quote.quoteid=a.quoteid
				End
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
			-- error in except statement and in data insertion in bkup db
			--update [db_mktg].[hdr_quote] set  isconverttoinvoice=0 where [quoteid] = @quoteid
			
			---Entry into quote detail revised
			insert into db_mktg.[dtl_quote_revised]
			([quoteid],[revisedno],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],
			[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],
			[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],itemtype,hsnid)
			SELECT @quoteid,@revisedno ,[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],
			[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],
			[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],itemtype,hsnid from db_mktg.dtl_quote where [quoteid] = @quoteid

			delete from db_mktg.dtl_quote where [quoteid] = @quoteid
			insert into db_mktg.dtl_quote
			([quoteid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],
			[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],
			[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],itemtype,hsnid)
			SELECT @quoteid,[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],
			[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],
			[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],itemtype,hsnid from @Quotedetail
			 -- 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 Quote order detail record.', 16, 1)
			 		RETURN
			 	END
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
			   
			   ---Entry into quote installation info revised
			    insert into [db_mktg].[quote_installationinfo_revised] ([quoteid],[revisedno],[srno],[installationid],[installationinfo],[createdby],[createdon],
				[modifiedby],[modifiedon])
				Select @quoteid,@revisedno,[srno],[installationid],[installationinfo],@userid,getdate(),@userid,getdate()
	            from [db_mktg].[quote_installationinfo]  where quoteid = @quoteid;
				
				delete from [db_mktg].[quote_installationinfo]  where quoteid = @quoteid;	
				-- insert installation information
			    insert into [db_mktg].[quote_installationinfo] ([quoteid],[srno],[installationid],[installationinfo],[createdby],[createdon],
				[modifiedby],[modifiedon])
				Select @quoteid,[srno],[installationid],[installationinfo],@userid,getdate(),@userid,getdate()
	            from @QuoteInstallationInfo
					--End-- end of row count
-----------------------------------------------------------------------------------------------------------------------------------------------------------
			
			---Entry into quote payment terms revised
			 insert into [db_mktg].[quote_paymentterms_revised] ([quoteid],[revisedno],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount])
			  select @quoteid,@revisedno,[srno],[paymenttermid],[paymentterm],[createdby],[createdon],@userid,getdate(),[coid],[boid],[percent],[amount] from [db_mktg].[quote_paymentterms] WHERE quoteid=@quoteid
			    -- check updates in payment terms
			  delete from [db_mktg].[quote_paymentterms] WHERE quoteid=@quoteid
			  insert into [db_mktg].[quote_paymentterms] ([quoteid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount])
			  select @quoteid,[srno],[paymenttermid],[paymentterm],[createdby],[createdon],@userid,getdate(),[coid],[boid],[percent],[amount] from @Quotepaymentterm
				IF @@ERROR <> 0
						BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
							RAISERROR ('Error while adding po pyt data.', 16, 1)
						SET @error = 'Error while adding po pyt data.  error no: ' + CAST(@@error AS VARCHAR(3))
						RETURN @error 
				 END
			  
			  ---Entry into quote terms and conditions revised
			  insert into [db_mktg].[quote_termsandconditions_revised] ([quoteid],[revisedno],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon],[modifiedby],[modifiedon])
				    select @quoteid,@revisedno,[srno],[termsandconditionsid],[termsandcondition],[createdby],getdate(),[modifiedby],[modifiedon] from db_mktg.quote_termsandconditions where [quoteid] = @quoteid

			   delete from db_mktg.quote_termsandconditions where [quoteid] = @quoteid
						 -- insert payment terms
				    insert into [db_mktg].[quote_termsandconditions] ([quoteid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon],[modifiedby],[modifiedon])
				    select @quoteid,[srno],[termsandconditionsid],[termsandcondition],[createdby],getdate(),[modifiedby],[modifiedon] from @Quotetermsandcondition
							-- 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 payment terms record.', 16, 1)
							RETURN 
					     END
					End					
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
                -- check documents Required
			    select [quoteid],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon]
				from  @Quotedocumentsrequired
				EXCEPT 
				select @quoteid,[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon] 
				from [db_mktg].[quote_documentsreqd] where [quoteid] = @quoteid	
				--EXEC sp_executesql @sql
				SELECT @rowcnt = @@ROWCOUNT
				-- data needs to update if query returns a row  
				IF @rowcnt > 0
				   BEGIN -- begin of row count	
				   
				   ---Entry into quote document required revised
				   insert into [db_mktg].[quote_documentsreqd_revised]([quoteid],[revisedno],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon])
						select @quoteid,@revisedno,[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon] from [db_mktg].[quote_documentsreqd] where [quoteid] = @quoteid
				   					
					  delete from [db_mktg].[quote_documentsreqd] where [quoteid] = @quoteid
						insert into [db_mktg].[quote_documentsreqd]([quoteid],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon])
						select @quoteid,[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon] from @Quotedocumentsrequired
						-- 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 quote termsandconditions record.', 16, 1)
								RETURN
							END
				  End
	       IF @rowcnt > 0
			 Begin	

			  ---Entry into quote document required revised
			    insert into [db_mktg].[dtl_bsegmt_quote_revised](quoteid,revisedno,bsegmtid,qty,createdby,createdon)  
		      select @quoteid,@revisedno,id,qty,@userid,getdate() FROM [db_mktg].dtl_bsegmt_quote where quoteid=@quoteid  

			  DELETE from  [db_mktg].dtl_bsegmt_quote where quoteid=@quoteid
			   -- select * from [db_mktg].dtl_bsegmt_enq where enqid=10032
		      insert into [db_mktg].dtl_bsegmt_quote(quoteid,revisedno,bsegmtid,qty,createdby,createdon)  
		      select @quoteid,@revisedno,id,value,@userid,getdate() from @Quotebseg      
	     End
   COMMIT

  SELECT @quoteno quoteno,@quoteid quoteid

END

GO
/****** Object:  StoredProcedure [db_mktg].[pr_savequote_pi]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[pr_savequote_pi] 'Insert',13,1 

CREATE PROCEDURE [db_mktg].[pr_savequote_pi]
@statementtype NVARCHAR(50),
@quoteid bigint,
@userid INT = 1
AS
BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @invid INT,@rowcnt INT,@colstring NVARCHAR(MAX),@sql NVARCHAR(MAX)
	DECLARE @invno bigint,@pinno bigint
	DECLARE @concessionaltax bit
	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN	
		set @pinno = (Select ISNULL(MAX(pino),0) + 1 from [db_mktg].[quote_hdr_sale])

		set @invno = (Select ISNULL(MAX(invno),0) + 1 from [db_mktg].[quote_hdr_sale])

		INSERT INTO [db_mktg].[quote_hdr_sale]  
	    ([quoteid],[oaids],[pino],[pidate],[invno],[invdate],[customerid],[customername],[customeraddr1],
		[customeraddr2],[city],[state],[country],[pin],[customergstno],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],
		[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],
		[remarks],[coid],[boid],[fyid],[createdby],[createdon],[modifiedby],[modifiedon],invoicetype,custtype)

	    select quoteid,0,@pinno,getdate(),@invno,quotedate,[customerid],[customername],customeraddr1,customeraddr2,city,
		[state],[country],pin,[customergstno],basicamt,discamt,netamt,igstamt,cgstamt,sgstamt,orderamt,userid,
	    approvedbymarketingheaduserid,approvedbycommercialuserid,0,remarks,coid,boid,fyid,
	    createdby,createdon,modifiedby,modifiedon,ordertype,custtype
        from  [db_mktg].[hdr_quote] where quoteid = @quoteid

		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice header data.', 16, 1)
			RETURN
		END
		 set @invid = SCOPE_IDENTITY()
		INSERT INTO [db_mktg].[quote_dtl_sale]
		([fyid],[invid],[oaid],[quoteid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],
		[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],hsnid)
		select fyid,@invid,0,quoteid,itemid,billingdescription,isfoc,issample,specialcode,packing,uom,isnull(gstid,0),igstrate,sgstrate,cgstrate,cessrate,basicamount,rate,itemdiscpercent,itemdiscamt,netrate,
		       orderedquantity,qtyalreadydispatched,qtytodispatch,netamt,igstamt,cgstamt,sgstamt,cessamt,totalamt,remarks,hsnid
	    from  [db_mktg].dtl_quote where quoteid = @quoteid
		insert into [db_mktg].[quote_dtl_sale_batches]
		([invid],[oaid],quoteid, [itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
         select @invid,0,[quoteid],[itemid],[packing],[qtytodispatch],0,0,'','' from [db_mktg].dtl_quote
		 where quoteid = @quoteid
		 --payment terms 
		 insert into [db_mktg].[quote_sale_paymentterms]
		 (invid,paymenttermid,paymentterm,createdby,createdon,coid,boid)
		 select @invid,id,name,@userid,getdate(),1,1 from db_mktg.mst_paymentterms
		 --terms condition 
		 insert into [db_mktg].[quote_sale_termsandconditions]
		 (invid,termsandconditionsid,termsandcondition,createdby,createdon)
		 select @invid,id,name,@userid,getdate() from db_mktg.mst_termsandconditions
	  END
	   Update db_mktg.hdr_quote set isconverttoinvoice = 1 where quoteid=@quoteid
   COMMIT
   select @invid as invid
  END

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

CREATE PROCEDURE [db_mktg].[pr_savequoteactions] 
    @statementtype varchar(100),	   
	@userid int,
	@coid int,
	@boid int,
	@fyid int,
	@quoteid bigint,
	@rejectionremarks varchar(100)=null,
	@rejectid int=null,
	@dealerids varchar(100),
	@deptids varchar(100),
	@status int,
	@intimationto int=null
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
   BEGIN TRANSACTION     
	if(@statementtype='Update')
	 BEGIN	   
	  Update db_mktg.hdr_quote set quotestatus=@status, rejectionid=@rejectid,rejectionremark=@rejectionremarks, intimationto=@intimationto,
	         dealerid=@dealerids,deptid=@deptids
	  where quoteid =@quoteid
	 End	 		
   commit
END

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

CREATE PROCEDURE [db_mktg].[pr_savequotefollowup] 
    @statementtype nvarchar(50),
	@Quoteheader  [db_mktg].[hdrquote_tvp] readonly,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@remarks varchar(500),
	@nextfollowupdate varchar(20),
	@escalateto bigint=1,
	@cdate varchar(20),
	@ctime varchar(20)
	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @quoteid int, @quoteno int,@error VARCHAR(100)
	BEGIN TRANSACTION 

	if (@statementtype='Insert')
	   BEGIN
			
			-- fetching quote id from table type

			select top 1 @quoteid = quoteid from @Quoteheader

			select top 1 @quoteno = quoteid from @Quoteheader

						
					UPDATE db_mktg.hdr_quote  set 
					[nextfollowupdate]= @nextfollowupdate ,quotestatus=4									
					FROM   @Quoteheader a
					WHERE  db_mktg.hdr_quote.quoteid=a.quoteid

			

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

             insert into db_mktg.followup_quot
			 (quoteid,cdate,ctime,remarks,nextfollowupdate,escalateto,coid,boid,fyid,createdby,createdon)
			 values(@quoteid,@cdate,@ctime,@remarks,@nextfollowupdate,@escalateto,@coid,@boid,@fyid,@userid,getdate())

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



GO
/****** Object:  StoredProcedure [db_mktg].[pr_savequoteuploadinfo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
 CREATE PROCEDURE [db_mktg].[pr_savequoteuploadinfo]
    @statementtype nvarchar(50),
	@userid int=1,
	@filename VARCHAR(200),
    @QuoteImageInfo VARCHAR(MAX)=NULL,
	@coid int,
	@boid int,
	@fyid INT,
	@Quoteid BIGINT,
	@Quoteno 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_mktg].[quote_images]
		  ([quoteid],[filename],[imageinfo],[isactive],[createdby],[createdon],remarks)
		  VALUES(@Quoteid,@filename,@QuoteImageInfo,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_mktg].[pr_saverejectreason]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [db_mktg].[pr_saverejectreason]
    @statementtype nvarchar(50),
	@enqid bigint,
	@userid int=1,
	@coid int=1,
	@boid int=1,
	@fyid int=1,
	@rejectionid int ,
	@reject_remark varchar(200)
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @enqno int,@error VARCHAR(100)

	BEGIN TRANSACTION 
	if (@statementtype='Insert')
	   BEGIN			
			UPDATE db_mktg.hdr_enq  set enqstatus=8, rejectionid=@rejectionid,rejectionremark=@reject_remark,ishold=0,holddate=null
			WHERE  db_mktg.hdr_enq.id=@enqid	
      End
	  if (@statementtype='Update')
	   BEGIN			
			UPDATE db_mktg.hdr_enq  set enqstatus=8, rejectionid=@rejectionid,rejectionremark=@reject_remark,ishold=0,holddate=null
			WHERE  db_mktg.hdr_enq.id=@enqid	
      End
  commit
END

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

CREATE PROCEDURE [db_mktg].[pr_savetenderitemmaster]
@statementtype NVARCHAR(50),
@fyid int,
@tenderitem_tvp [db_masters].[tenderitems_tvp] READONLY
AS

 BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @itemid bigint
	
	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN
		-- add sale header information
		
		INSERT INTO [db_mktg].mst_tenderItemMaster(catid,name,[description],brandid,units,technical_specs,remarks,code,coid,boid,createdby,createdon)		
		SELECT catid,name,[description],brandid,units,[technicalspecs],[remarks],'Temp',[coid],[boid],[userid],getdate() from @tenderitem_tvp
				
		update [db_mktg].mst_tenderItemMaster set  code=code+ltrim(id) where id=@@IDENTITY
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding items', 16, 1)
			RETURN
		END

    SELECT	@itemid = SCOPE_IDENTITY()

	select * from [db_mktg].mst_tenderItemMaster where id=@itemid
		
   END
	--ELSE

 --   BEGIN
	--Update db_mktg.mst_tenderItemMaster set 
	--catid = a.catid,
	--name = a.name,
	--[description]= a.[description],
	--brandid = a.brandid,
	--units = a.units,
	--technical_specs= a.[technicalspecs],
	--remarks = a.[remarks],
	--code = a.[code],
	--coid = a.coid,
	--boid = a.boid
	--FROM @tenderitem_tvp a
	--WHERE  db_mktg.mst_tenderItemMaster.id= a.id

	--   IF @@error <> 0
	--		BEGIN
	--			-- Rollback the transaction
	--			ROLLBACK
	--			-- Raise an error and return
	--			RAISERROR ('Error while updating existing item', 16, 1)
	--			RETURN
	--   END
	-- END  

  COMMIT
END

GO
/****** Object:  StoredProcedure [db_mktg].[reports_enquiryregister]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--  exec [db_mktg].[reports_enquiryregister] 1,1,1,1,'2019-04-01','2019-11-01',1,0,0,0

CREATE PROCEDURE [db_mktg].[reports_enquiryregister] 
    @coid int,
	@boid int,
	@fyid int,
	@userid int=1,
	@fromdate date,
	@todate date,
	@bsegmt int=0,
	@status int=0,
	@zone   int=0,
	@region int =0,
	@mktgexec int =0
AS

BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);
	begin
	set @sql= 'select * from (select ROW_NUMBER() OVER(order by hdr.id) sr,hdr.enqno,format(hdr.enqdate ,''dd/MM/yyyy'') enqdate,   
    case when hdr.custtype=''C'' then cust.name +'' '' + isnull(cust.address1,'''')+ isnull(cust.address2,'''')   
	else pcust.name +'' '' + isnull(pcust.address1,'''')+ isnull(pcust.address2,'''')  end as Custname , 
	hdr.city,hdr.state,
	usr.firstname as mktg_Exec,	coalesce(itm.itemname,titm.name) as firstproduct,
	mstg.name as enqstage
    from [db_mktg].[hdr_enq] hdr
	inner join (select enqid,min(id) id from db_mktg.dtl_enq group by enqid) mindtl on hdr.id=mindtl.enqid
	join db_mktg.dtl_enq dtl on mindtl.id = dtl.id
	left join db_mktg.mst_tenderItemMaster titm on dtl.itemid = titm.id
	left join db_mm.mst_item itm on dtl.itemid = itm.id
    left join db_masters.customer cust on hdr.customerid=cust.id
    left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
    left join db_masters.users usr on hdr.marketexecutive = usr.userid
	left join db_mktg.mst_enqstatus st on hdr.enqstatus =  st.id
	left join db_mktg.mst_quotestage mstg on mstg.id= hdr.enqstage
	left join db_mktg.mst_enquirytype enqtype on hdr.enqtype= enqtype.id 	
	where  hdr.enqdate >='''+ cast(@fromdate as varchar(20))+'''  and  hdr.enqdate <='''+ cast(@todate as varchar(20))+''' and hdr.coid ='+ cast(@coid as varchar(5)) +'and hdr.boid='+ cast(@boid as varchar(5))+' 
	and hdr.userid in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))'
	if(@mktgexec >0)
	begin
	 set @sql +='and hdr.marketexecutive='+cast(@mktgexec as varchar(10)) +''
	end
	if(@bsegmt >0)
	begin
	 set @sql +='and hdr.businesssegment='+cast(@bsegmt as varchar(10)) +''
	end
    if(@status >0)
	begin
	 set @sql +='and hdr.enqstatus='+cast(@status as varchar(10)) +''
	end
	set @sql +=') as enqlist '

	-- if(@zoneid<>'')
	-- begin 
	-- set @sql +=' and enqlist.zone  ='+''''+cast(@zoneid as VARCHAR(10))+''''
	-- END
	-- if(@regionid<>'')
	-- begin 
	-- set @sql +=' and enqlist.region  ='+''''+cast(@regionid as VARCHAR(10))+''''
	-- end

	end

	print @SQL
	
	EXEC sp_executesql @SQL

	--  SELECT ROWCOUNT_BIG() records
	

END
GO
/****** Object:  StoredProcedure [db_mktg].[reports_marketingregister]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mktg].[reports_marketingregister] 1,1,1,1,'04/01/2019','07/28/2019',null,null,null,null,null,7

CREATE PROCEDURE [db_mktg].[reports_marketingregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@userid  int,
	@fromdate date=null,
	@todate date=null,
	@bsegmt int=0,
	@status int=0,
	@zone   int=0,
	@region int =0,
	@mktgexec int =0,
	@reportid int =0	
AS
BEGIN 

   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

   declare @sql nvarchar(max)=(select querylogic FROM db_mm.hdr_reportcolumn_definition where reportid=@reportid)

   print @sql
   --  exec [db_mm].[reports_grnregister] 1,1,1,'04/01/2019','07/28/2019','A','',7
   if @reportid=7
    EXEC [db_mktg].[reports_enquiryregister]  @coid,@boid,@fyid,@userid, @fromdate,@todate,@bsegmt,@status,@zone,@region,@mktgexec
   ELSE
    EXEC @sql  @coid,@boid,@fyid,@userid,@fromdate,@todate,@bsegmt,@status,@zone,@region,@mktgexec
END

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

--  exec [db_mktg].[reports_quoteregister]  1,1,1,1,'2019-04-01','2019-11-22',1,1,1

CREATE PROCEDURE [db_mktg].[reports_quoteregister] 
    @coid int,
	@boid int,
	@fyid int,
	@userid int=1,
	@fromdate date,
	@todate date,
	@bsegmt int=0,
	@status int=0,
	@zone   int=0,
	@region int =0,
	@mktgexec int =0
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@totalcount nvarchar(max);
begin

  set @sql= 'select row,quoteno,format(quotedate,''dd/MM/yyyy'') quotedate,Custname,city,state,mktg_Exec,zone.zonename,region.regionname ,firstproduct,orderamt from 
  (select  ROW_NUMBER() over( order by hdr.id) row , hdr.quoteno,hdr.quotedate,case 
  when hdr.custtype=''C'' then cust.name 
  when hdr.custtype=''P'' then pcust.name 
  else '''' end as Custname,hdr.city,hdr.state,   
  CASE WHEN hdr.custtype=''C'' THEN cust.zone 
       WHEN hdr.custtype=''P'' THEN pcust.zone
  ELSE 0 END AS zone,
  CASE WHEN hdr.custtype=''C'' THEN cust.region
       WHEN hdr.custtype=''P'' THEN pcust.region
  ELSE 0 END AS region,
  usr.firstname as mktg_Exec,
  isnull(st.status,'''') status,COALESCE(itm.itemname,titm.name) as firstproduct,hdr.orderamt
  from [db_mktg].[hdr_quote] hdr
  inner join (select quoteid,min(id) id from db_mktg.dtl_quote group by quoteid) mindtl on hdr.quoteid = mindtl.quoteid
  join db_mktg.dtl_quote dtl on mindtl.id=dtl.id
  left join db_mktg.mst_tenderItemMaster titm on dtl.itemid = titm.id
  left join db_mm.mst_item itm on dtl.itemid = itm.id
  left join db_masters.customer cust on hdr.customerid=cust.id
  left join db_masters.prospectcustomers pcust on hdr.customerid = pcust.id
  left join db_masters.users usr on hdr.marketexecutive = usr.userid
  left join [db_mktg].[mst_enqstatus] st on hdr.quotestatus=st.id 
  where  hdr.quotedate >='''+ cast(@fromdate as varchar(20)) +''' and hdr.quotedate <='''+ cast(@todate as varchar(20)) +''' 
  and   hdr.coid ='+ cast(@coid as varchar(5)) +'and hdr.boid='+ cast(@boid as varchar(5))+''
  if(@mktgexec >0)
   begin
	 set @sql +='and hdr.marketexecutive='+cast(@mktgexec as varchar(10)) +''
   end
   if(@bsegmt >0)
   begin
	 set @sql +='and hdr.bsegment='+cast(@bsegmt as varchar(10)) +''
   end
   if(@status >0)
   begin
	 set @sql +='and hdr.quotestatus='+cast(@status as varchar(10)) +''
   end
  set @sql += ') as quotelist
  left join db_masters.zonemaster zone on quotelist.zone = zone.id 
  left join db_masters.regionmaster region on quotelist.region = region.id'
  --where  hdr.coid ='+ cast(@coid as varchar(5)) +'and hdr.boid='+ cast(@boid as varchar(5))+' and hdr.userid in (select * from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))) as enqlist'
end

print @SQL

  EXEC sp_executesql @SQL
  --  SELECT ROWCOUNT_BIG() records
END
GO
/****** Object:  StoredProcedure [db_mm].[pogrossrequirement]    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 items information>
--[db_mm].[pogrossrequirement] 1,1,1,3066
-- =============================================
CREATE procedure [db_mm].[pogrossrequirement]
@coid int,
@boid int,
@fyid int,
@poid bigint,
@rgpid int=0,
@userid int = 0,
@accesstoken varchar(200) = null

as 
Begin
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#podetails') IS NOT NULL DROP TABLE #podetails
