	create table #podetails 
	(
		itemid			bigint,
		bomid			bigint,
		itemname		varchar(300),
		itemcode		varchar(20),
		oldcode			varchar(20),
		quantity		decimal(10,2),
		bombatchsize	decimal(10,2),
		mfactor			decimal(10,2),
		chk				int,
		rowno			int,
		issuingunitid   int,
		itemuom		    varchar(20),
		itemspecification varchar(250)
	)

	declare @itemid int, @bomid int,@level int;
	declare @kitquantity decimal (13,2);
	set @level = 0;
	--insert data for the product from po detail
	insert into #podetails (itemid,bomid,quantity,bombatchsize,mfactor,rowno)
	select itemid , 0, sum(isnull(orderedquantity,1)),1, 1, 
	ROW_NUMBER() OVER(ORDER BY itemid) rownum from db_mm.dtl_purchaseorder where orderid = @poid
	group by itemid
	
	--update bom ids in #podetails
	update #podetails set bomid = a.bomid 
	from (select productid, max(bomid) bomid from  db_mm.hdr_bom group by productid) a 
	where #podetails.itemid = a.productid and isnull(#podetails.bomid,0)=0

	-- update bom batch size from bom table and mfactor 
	update #podetails set bombatchsize = isnull(a.[batchsize],1) , mfactor = quantity/isnull(a.[batchsize],1) 
	from db_mm.hdr_bom a where #podetails.itemid = a.productid and #podetails.bomid = a.bomid

	--update itemname, itemcode, old code in #podetails
	update #podetails set itemname = a.itemname, itemcode = a.itemcode, oldcode = a.oldcode, issuingunitid=a.issuingunitid
	from db_mm.mst_item a where #podetails.itemid = a.id

	update #podetails set itemuom = a.uom
	from [db_mm].[mst_itemuom] a where #podetails.issuingunitid = a.id
	
	update #podetails set itemspecification = a.itemspecification
	from (Select * from [db_mm].[dtl_rgp_returnitems] Where  rgpid=@rgpid)a where #podetails.itemid = a.itemid

	select * from #podetails

	IF OBJECT_ID('tempdb..#grossrequirement') IS NOT NULL DROP TABLE #grossrequirement
	create table #grossrequirement 
	(
		itemid			bigint,
		itemname		varchar(500),
		itemcode		varchar(25),
		oldcode			varchar(20),
		itemtype		varchar(30),
		itemtypeid		int,
		rate			decimal(13,2),
		hsncode			varchar(18),
		gstid			int,
		gst				varchar(10),
		quantity			decimal(15,3),
		stockinhand			decimal(15,3),
		minimumStk			decimal(15,3),
		pendingcustorder	decimal(15,3),
		onPO				decimal(15,3),
		atRect				decimal(15,3),
		underIQC			decimal(15,3),
		netReqd				decimal(15,3),
		allreadysent		decimal(15,3),
		qtysent		decimal(15,3),
		qtyrecdunused		decimal(15,3),
		issuingunitid   int,
		itemuom		    varchar(20),
		itemspecification varchar(250)
	)
	

	--insert items into grossrequirement table where bomid = 0
	insert into #grossrequirement (itemid,quantity,stockinhand,minimumStk,pendingcustorder,onPO,atRect,underIQC,netReqd,rate,gstid) 
	select itemid , quantity,0,0,0,0,0,0,quantity,0,0 from #podetails where bomid = 0;

	update #podetails set chk = 1 where bomid = 0


	--select * from #grossrequirement

	declare @minrowid int, @maxrowid int;
	declare @txt varchar(200);
	declare @mfactor decimal(5,2);

	select @minrowid = min(rowno), @maxrowid = max(rowno) from #podetails where bomid >0

	IF OBJECT_ID('tempdb..#tempbom') IS NOT NULL DROP TABLE #tempbom
	create table #tempbom 
	(
		id			int,
		parentid	int,
		parentname  varchar(200),
		parentcode  varchar(20),
		childid     int,
		childname	varchar(200),
		childcode	varchar(20),
		quantity	decimal(15,3),
		tolerance   decimal(5,2),
		wastagequantity decimal(15,3),
		wastagepercent decimal(5,2),
        [LEVEL]   INT,
		rowno	int default 0

	)
			
	 -- explode bom of work order items
		while (@minrowid <= @maxrowid)
		begin
                    
			if exists (select 1 from #podetails where rowno = @minrowid and bomid > 0)
			begin
				select @itemid = itemid, @mfactor=mfactor  from #podetails where rowno = @minrowid

                insert into #tempbom (id,parentid,parentname,parentcode,childid,childname,childcode,
				quantity,tolerance,wastagequantity,wastagepercent,[LEVEL])
				EXEC [db_mm].[pr_explodeBOM] @coid,@boid,@itemid,@level


				update #tempbom set quantity = quantity * @mfactor, 
                rowno = @minrowid where isnull(rowno,0)=0

			end
			set @minrowid = @minrowid + 1
		end			
		
		--select * from #tempbom 

-- inserting records into gross requirement table 
		insert into #grossrequirement (itemid,quantity) 
		select childid,sum(quantity + isnull(tolerance,0) + isnull(wastagequantity,0)) quantity 
		from #tempbom group by childid

		-- updating itemname, itemcode, oldcode from item master
		update #grossrequirement set itemname = a.itemname, itemcode = a.itemcode,hsncode = a.hsncode, gstid = isnull(a.gstid,1),
		oldcode= a.oldcode, issuingunitid=a.issuingunitid from db_mm.mst_item a where #grossrequirement.itemid = a.id


		update #grossrequirement set itemuom = a.uom
	    from [db_mm].[mst_itemuom] a where #grossrequirement.issuingunitid = a.id

		-- update latest rate 
		update #grossrequirement set rate = isnull(a.itemrate,0) 
		from (select dtl.itemid, itemrate from db_mm.dtl_grn dtl join 
		(select itemid,max(id) id from db_mm.dtl_grn group by  itemid) a on dtl.itemid = a.itemid and dtl.id = a.id) a 
		where #grossrequirement.itemid = a.itemid 

		--update rate from items with rate = 0 
		update #grossrequirement set rate = isnull(a.rate,0) 
		from (select id,coalesce(openingrate, lastpurchaserate) rate from db_mm.mst_item) a 
		where #grossrequirement.itemid = a.id and isnull(#grossrequirement.rate,0) = 0


		-- update itemtypeid from db_mm.item_types
		update #grossrequirement set itemtypeid = a.typeid from
		(select itemid, min(typeid) typeid from db_mm.item_types where typeid > 0  group by itemid) a 
		where #grossrequirement.itemid = a.itemid 

		-- update itemtype from db_mm.mst_itemtypes
		update #grossrequirement set itemtype = isnull(a.name,'') 
		from db_mm.mst_itemtypes a where #grossrequirement.itemtypeid = a.id
				
		-- update gst from gst master
		update #grossrequirement set gst = a.description 
		from db_mm.mst_gst a where #grossrequirement.gstid= a.gstid

		--update stockinhand from db_mm.item_stk_trn
		update #grossrequirement set stockinhand = isnull(stk.stock,0)
		from (select itemid,sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn
		where boid=@boid and coid =@coid  and fyid=@fyid group by itemid) stk where #grossrequirement.itemid = stk.itemid

		--update minimumStk from db_mm.item_stk_trn
		update #grossrequirement set minimumStk = isnull(a.moq,0)
		from db_mm.mst_item a where #grossrequirement.itemid = a.id

				
		--update onPO from db_mm.item_stk_trn
		update #grossrequirement set onPO = isnull(a.stk,0)
		from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0)-isnull(writeoffquantity,0)) stk 
		from db_mm.dtl_purchaseorder dt join db_mm.hdr_purchaseorder hd on  dt.orderid = hd.orderid
		and DATEDIFF(day, getdate(), hd.orderdate)  <= 90 group by itemid) a where #grossrequirement.itemid = a.itemid

		-- pending customer order
		update #grossrequirement set pendingcustorder = isnull(a.pendingqty,0)
		from (select itemid, sum(isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0)) pendingqty 
		from db_sop.dtl_saleorder group by itemid)  a where #grossrequirement.itemid = a.itemid
				
		-- atrect, at iqc
		update #grossrequirement set atRect = isnull(a.grnqty,0)
		from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) grnqty 
		from db_mm.dtl_grn dtl where isnull(arnumber,0)!=0 group by itemid) a where #grossrequirement.itemid = a.itemid

		--update AlreadySent from db_mm.item_stk_trn
		update #grossrequirement set allreadysent = isnull(stk.qtysent,0)+isnull(stk.qtyrecdunused,0)
		from (select d.itemid, sum(isnull(qtysent,0)) qtysent, sum(isnull(qtyrecdunused,0)) qtyrecdunused from [db_mm].[hdr_rgp] h, [db_mm].[dtl_rgp] d
			  Where h.id=d.rgpid
			  and   h.id<>@rgpid
			  And   h.[orderid]= @poid
			  group by itemid) stk where #grossrequirement.itemid = stk.itemid

		---------- this is used in olny getrgpdata procedure because i called this procedure from gerrgpdata ------- 
		update #grossrequirement set qtysent = isnull(stk.qtysent,0), qtyrecdunused=isnull(stk.qtyrecdunused,0)
		from (select d.itemid, sum(isnull(qtysent,0)) qtysent, sum(isnull(qtyrecdunused,0)) qtyrecdunused from [db_mm].[hdr_rgp] h, [db_mm].[dtl_rgp] d
			  Where h.id=d.rgpid
			  and   h.id=@rgpid
			  And   h.[orderid]= @poid
			  group by itemid) stk where #grossrequirement.itemid = stk.itemid

		--update net 
		update #grossrequirement set netReqd	= pendingcustorder + minimumStk - onPO - stockinhand - atRect - underIQC

		update #grossrequirement set itemspecification = a.itemspecification
	    from (Select * from [db_mm].[dtl_rgp] Where  rgpid=@rgpid)a where #grossrequirement.itemid = a.itemid

		--select itemid,itemname,itemcode,oldcode,quantity,rate,hsncode,gstid,gst, quantity-isnull(allreadysent,0) as pendingqty
		-- from #grossrequirement p order by itemcode

		select p.*, quantity-isnull(allreadysent,0) as pendingqty, isnull([rate],0)*isnull([qtysent],0) as approxvalue
		 from #grossrequirement p order by itemcode
		
				
End








GO
/****** Object:  StoredProcedure [db_mm].[pr_advicegenerationratediffdr]    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_mm].[pr_advicegenerationratediffdr]1075,1,1,1,1
-- =============================================

CREATE PROCEDURE [db_mm].[pr_advicegenerationratediffdr]
@grnid int,
@coid int,
@boid int,
@fyid int,
@userid int
---@itemid bigint=null
AS
BEGIN
	SET NOCOUNT ON;
	
	declare @sql nvarchar(max), @adviceno int, @adviceid int,@itemid int
-- check and insert stock 
set @adviceno = (SELECT ISNULL(MAX(adviceno), 0) + 1 FROM [db_mm].[hdr_inwardadvice] )
insert into [db_mm].[hdr_inwardadvice]([adviceno],[advicedate],[advicetype],[advicetypeid],[noteid],partyid,inwardid,
[amount],[reference],[coid],[boid],[createdby],[createdon],[fyid])
select @adviceno,getdate(),'R',1,0,suplid,@grnid,(select sum((dt.itemrate -pd.itemrate) * quantityreceived) from [db_mm].[dtl_grn] dt
join db_mm.dtl_purchaseorder pd on dt.orderid=pd.orderid and dt.itemid =pd.itemid where dt.grnid =@grnid) ,
'N',@coid,@boid,@userid,getdate(),@fyid
from [db_mm].[hdr_grn] h
where h.grnid=@grnid
SELECT @adviceid = SCOPE_IDENTITY()

insert into [db_mm].[dtl_inwardadvice](adviceid,itemid,rate,quantity,amount,orderid,porate,igstamount,cgstamount,sgstamount)
select @adviceid,dt.itemid,dt.itemrate,quantityreceived,(dt.itemrate -pd.itemrate)  * (quantityreceived-isnull(quantityrejected,0)-isnull(quantityshortage,0)),dt.orderid,pd.itemrate,iif(dt.igstamount>0, (g.igst * (dt.itemrate -pd.itemrate) /100) *quantityreceived,0) as igst,
	       iif(dt.cgstamount>0, (g.cgst * (dt.itemrate -pd.itemrate) /100) *quantityreceived,0) as cgst, iif(dt.sgstamount>0, (g.sgst *  (dt.itemrate -pd.itemrate) /100) *quantityreceived,0) as sgst from db_mm.dtl_grn dt
 left join [db_mm].[mst_gst] g on dt.gstid=g.gstid
 join db_mm.dtl_purchaseorder pd on  dt.orderid=pd.orderid and dt.itemid=pd.itemid
 where grnid=@grnid
 and (dt.itemrate -pd.itemrate)>0

	
END









GO
/****** Object:  StoredProcedure [db_mm].[pr_advicegenerationrejection]    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_mm].[pr_advicegenerationrejection]1079,1,1,1,1
-- =============================================

CREATE PROCEDURE [db_mm].[pr_advicegenerationrejection]
@grnid int,
@coid int,
@boid int,
@fyid int,
@userid int
---@itemid bigint=null
AS
BEGIN
	
	declare @sql nvarchar(max), @adviceno int, @adviceid int,@itemid int


set @adviceno = (SELECT ISNULL(MAX(adviceno), 0) + 1 FROM [db_mm].[hdr_inwardadvice] )
insert into [db_mm].[hdr_inwardadvice]([adviceno],[advicedate],[advicetype],[advicetypeid],partyid,inwardid,
[amount],[reference],[coid],[boid],[createdby],[createdon],[fyid])
select @adviceno,getdate(),'J',1,h.suplid,@grnid,(select sum((b.quantityrejected) * (d.itemrate))),
'N',1,1,1,getdate(),1
from [db_mm].[hdr_grn] h 
join [db_mm].[dtl_grn] d on h.grnid=d.grnid
join [db_mm].[grnbatchwise] b on b.grnid=d.grnid and b.itemid=d.itemid
where b.grnid=@grnid group by h.suplid

SELECT @adviceid = SCOPE_IDENTITY()

insert into [db_mm].[dtl_inwardadvice](adviceid,itemid,rate,quantity,amount,orderid,porate,igstamount,cgstamount,sgstamount)
select @adviceid,dt.itemid,dtg.itemrate,dt.quantityrejected,(isnull(dt.quantityrejected,0) * isnull(itemrate,0)),dtg.orderid,itemrate,iif(dtg.igstamount>0, (g.igst * itemrate/100) *dt.quantityrejected,0) as igst,
	       iif(dtg.cgstamount>0, (g.cgst * itemrate/100) * dt.quantityrejected,0) as cgst, iif(dtg.sgstamount>0, (g.sgst * itemrate/100)* dt.quantityrejected,0) as sgst from db_mm.grnbatchwise dt
		   join db_mm.dtl_grn dtg on dt.grnid=dtg.grnid and dt.itemid=dtg.itemid
 left join [db_mm].[mst_gst] g on dtg.gstid=g.gstid
 where dt.grnid=@grnid
 and dt.quantityrejected>0

	
END









GO
/****** Object:  StoredProcedure [db_mm].[pr_advicegenerationshortage]    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_mm].[pr_advicegenerationshortage]1079,1,1,1,1
-- =============================================

CREATE PROCEDURE [db_mm].[pr_advicegenerationshortage]
@grnid int,
@coid int,
@boid int,
@fyid int,
@userid int
---@itemid bigint=null
AS
BEGIN

	declare @sql nvarchar(max), @adviceno int, @adviceid int,@itemid int
set @adviceno = (SELECT ISNULL(MAX(adviceno), 0) + 1 FROM [db_mm].[hdr_inwardadvice] )
insert into [db_mm].[hdr_inwardadvice]([adviceno],[advicedate],[advicetype],[advicetypeid],[noteid],partyid,inwardid,
[amount],[reference],[coid],[boid],[createdby],[createdon],[fyid])
select @adviceno,getdate(),'S',1,0,suplid,@grnid,(select sum(isnull(dt.quantityshortage,0) * isnull(dt.itemrate,0)) from [db_mm].[dtl_grn] dt where grnid =@grnid) ,
'N',@coid,@boid,@userid,getdate(),@fyid
from [db_mm].[hdr_grn] h
where h.grnid=@grnid
SELECT @adviceid = SCOPE_IDENTITY()

insert into [db_mm].[dtl_inwardadvice](adviceid,itemid,rate,quantity,amount,orderid,porate,igstamount,cgstamount,sgstamount)
select @adviceid,itemid,itemrate,quantityshortage,(isnull(quantityshortage,0) * isnull(itemrate,0)),orderid,itemrate,iif(dt.igstamount>0, (g.igst * itemrate/100) *quantityshortage,0) as igst,
	       iif(dt.cgstamount>0, (g.cgst * itemrate/100) * quantityrejected,0) as cgst, iif(dt.sgstamount>0, (g.sgst * itemrate/100)* quantityshortage,0) as sgst from db_mm.dtl_grn dt
 left join [db_mm].[mst_gst] g on dt.gstid=g.gstid
 where grnid=@grnid
 and quantitybilled-quantityreceived>0

	
END









GO
/****** Object:  StoredProcedure [db_mm].[pr_cancelpendingreqn]    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_mm].[pr_getrequisitiondata] 1,1,1027,'N'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_cancelpendingreqn] 
	@coid int,
	@boid int,
	@reqnid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	update db_mm.hdr_requisition set iscancelled=1 where reqnid
	=@reqnid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.




GO
/****** Object:  StoredProcedure [db_mm].[pr_checksupplierbillno]    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_mm].[pr_checksupplierbillno]'2',181
-- =============================================
CREATE PROCEDURE [db_mm].[pr_checksupplierbillno]
    @billno varchar(25), 
	@suplid int
AS
Begin
	
	declare @msg varchar(300);
	declare @grno int
	if exists(select billno,grnnumber=@grno,billdate  from db_mm.hdr_grn   where billno = @billno and suplid = @suplid)
	
	--if (@chk=1)
	Begin
		--set @msg = 'Supplier Billno already settled vide mrirn'
		--print @msg
		--Return 
		select 1 as billnoexists,@grno 
		end 
		else
		begin
		select 0 as billnoexists
	End
	


	
	


End

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

CREATE PROCEDURE [db_mm].[pr_commonapibom]
	@coid int,
	@boid int,
	@fyid int = null
	as
BEGIN
	SET NOCOUNT ON;
     -- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1
	 -- get isendproduct dropdown
	 select  [name] from [db_mm].[mst_itemtypes] where isendproduct= 1


	 
	end
	

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

CREATE PROCEDURE [db_mm].[pr_commonapidpr]
	@coid int,
	@boid int,
	@fyid int = null
	as
BEGIN
	SET NOCOUNT ON;
    select max(dprnumber) from db_mm.hdr_dpr where coid=@coid and boid=@boid
    -- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid
     -- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1
	 -- get isendproduct dropdown
	 select  [name] from [db_mm].[mst_itemtypes] where isendproduct= 1


	 
	end
	



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

--exec [db_mm].[pr_commonapigrn] 1,1,1

CREATE PROCEDURE [db_mm].[pr_commonapigrn]
	@coid int,
	@boid int,
	@fyid int = null,
	@search varchar(50)=''
	as
BEGIN
declare @sql nvarchar(max);
	SET NOCOUNT ON;


---get stores
    select [id],[name],[parentid],case when checksexempted=1 then 0 else 1 end porequired  from [db_mm].[mst_store] where  coid=@coid  and boid=@boid


--get purchase account
	select * from db_accounts.accountHeads where groupid in (select * from [dbo].[fn_getchild_ac_group](4))

--get Supplier List
	SELECT sp.[id],name  name,spc.categoryname as categoryname,[gsTin],[pan],[address1],[address2],[cityname] city
      ,[statename] state,[countryname] country,[pin],[mobile_number] as mobile,[phone_number] as phone,[fax],[email],[website],[tds_applicable] tdsapplicable,[tds_rate] as tdsrate,
	  [tcs_applicable] tscapplicable,[tcs_rate] tscrate  
	from [db_masters].[supplier] sp 
	join [db_masters].[supplier_category] spc on sp.categoryid=spc.id 
	join [db_masters].[country] co on sp.country = co.id 
	join [db_masters].[statemaster] s on sp.state = s.id 
	join [db_masters].[city] c on sp.city = c.id
	where sp.id in  (select suplid from  [db_mm].[hdr_purchaseorder])
    and sp.coid = @coid and sp.boid = @boid

--get Grn No

    SELECT ISNULL(MAX(grnnumber), 0) + 1 as grnnumber from [db_mm].[hdr_grn] where coid=@coid and boid=@boid 
   -- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1


	---get grn category
	select id,[grncategoryname],case when porequired=1 then 0 else 1 end porequired from [db_mm].[mst_grncategory] 
    
	----get grn levies
	
	select m.id,levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from   db_masters.levies m 
 	join  [db_mm].[mst_gst] g on m.gstid=g.gstid where isinwardlevy=1

end
	

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

CREATE PROCEDURE [db_mm].[pr_commonapiindent]
	@coid int,
	@boid int,
	@fyid int = null,
	@itemid int=null
AS
BEGIN
	SET NOCOUNT ON;
	-- get max indentno
		Select max(isnull(indentnumber,0)) as indentnumber from [db_mm].[hdr_indent] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid


	-- get indentors
	select userid,firstname  from db_masters.users where  coid=@coid  and boid=@boid

	-- get costcentres
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid

	-- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get item uom
	 SELECT [id],[uom] from [db_mm].[mst_itemuom] where coid =  @coid  and boid=@boid


	


	end
	

GO
/****** Object:  StoredProcedure [db_mm].[pr_commonapiitemcategoryrights]    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_mm].[pr_commonapiitemcategoryrights]  1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_commonapiitemcategoryrights] 
	@coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	
	exec [db_masters].[pr_getAllUsers] 1,100,@coid,@boid,'firstname','asc'

	---get item category list
	create table #tempcategorylist(
	id int,
	name	varchar(200),
	code	varchar(20),
	parentgroupid	int,
	categcode varchar(20),
	categname varchar(500),
	level int,
	lastitemcode	varchar(20),
	childcnt	int
	)
	insert into #tempcategorylist
	exec [db_masters].[pr_getitemcategorylist] @coid

	SELECT * FROM #tempcategorylist where parentgroupid=0

	
end
	



GO
/****** Object:  StoredProcedure [db_mm].[pr_commonapiitemlist]    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].[pr_commonapiitemlist] 1,1,1,5,'32,34,40,39,33,37,35,36,38,104','',1,'afdasdfas','',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_commonapiitemlist] 
	@fyid INT,
	@coid int = 1,
	@boid int = 1,
	@categoryid int= null,
	@subcategoryid varchar(100)=null,
	@itemtypeids varchar(100)=null,
	@userid bigint= null,
	@accesstoken varchar(200)=null,
	@search nvarchar(100)=null,
	@searchtype nvarchar(20)=''

AS
BEGIN
	SET NOCOUNT ON;
	select * from db_mm.mst_itemcategory where parentid = 0 order by name

	IF OBJECT_ID('tempdb..#tempitemcategories') IS NOT NULL DROP TABLE #tempitemcategories
	create table #tempitemcategories (
		id bigint,
		name varchar(200),
		code varchar(20),
		parentgroupid int,
		categcode varchar(6),
		categname varchar(500),
		level int,
		lastitemcode varchar(20),
		childcnt int
	)
	-- Insert into Temp Table
	if (@categoryid!=null or @categoryid !='') insert INTO #tempitemcategories	exec [db_masters].[pr_getitemcategorylist] @coid, @categoryid
	
	select * from #tempitemcategories where level <>0;

	declare @subcategoryids varchar(100);
	set @subcategoryids = @subcategoryid;
	print @subcategoryids;
	if (@subcategoryid = '' or @subcategoryid = null) 
		begin
			select @subcategoryids = stuff((SELECT ', ' + cast(t2.id as varchar(5)) FROM #tempitemcategories t2 where t1.level = t2.level or t1.level = t2.level+1 FOR XML PATH ('')), 1, 1, '') from #tempitemcategories t1
		end
	exec [db_mm].[pr_itemenquiry] 1,20,@fyid,@coid,@boid,'Itemname','asc','',@subcategoryids,@itemtypeids,'',@userid,@accesstoken,@search,@searchtype
END

--select stuff((SELECT ',' + cast(t2.id as varchar(5)) FROM db_mm.mst_itemtypes t2 where t1.id = t2.id FOR XML PATH ('')), 1, 1, '') as ids from db_mm.mst_itemtypes t1

GO
/****** Object:  StoredProcedure [db_mm].[pr_commonapiitemmaster]    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_mm].[pr_commonapiitemmaster] 1,1,2
-- =============================================

CREATE PROCEDURE [db_mm].[pr_commonapiitemmaster] 
	@coid int,
	@boid int,
	@fyid int = null,
	@userid int = null,
	@itemid int=null
AS
BEGIN
	SET NOCOUNT ON;
	-- get gst list 
	--Select [description],(LTRIM([hsncode])) hsncode,[igst],[sgst],[cgst],h.[createdby],u.username,gstid,[concessionaligst],
	--[concessionalcgst],[concessionalsgst] 
	--from [db_mm].[mst_gst] h 
	--join [db_masters].[users] u on h.createdby = u.userid 
	--where h.coid = @coid and h.boid = @boid and isActive = 1 
	--order by hsncode asc

	--change by mohit (13-06-2019)	
	Select g.id hsnid, h.gstid, h.[description],(LTRIM(g.[hsncode])) 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 all suppliers
	select id, (isnull(name,'') + ' ' + isnull(address1,'') + ' ' + isnull(address2,'')) name 
	from db_masters.supplier where coid=@coid and boid=@boid and isActive = 1

	-- get item types
	select id,name from db_mm.mst_itemtypes where coid=@coid and boid = @boid and isActive = 1

	-- get item uom
	select id,uom from db_mm.mst_itemuom where coid=@coid and boid = @boid and isActive = 1

	-- get item brands
	select id ,name brandname from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get item category list
	create table #tempcategorylist(
	id int,
	name	varchar(200),
	code	varchar(20),
	parentgroupid	int,
	categcode varchar(20),
	categname varchar(500),
	level int,
	lastitemcode	varchar(20),
	childcnt	int
	)
	insert into #tempcategorylist
	exec [db_masters].[pr_getitemcategorylist] @coid,@userid

	SELECT * FROM #tempcategorylist 

	SELECT * FROM  #tempcategorylist  WHERE parentgroupid > 0

	exec  [db_mm].[pr_getstore] @coid, @boid

	SELECT * FROM #tempcategorylist where childcnt=0

	select * from [db_masters].[Make]

	select * from [db_masters].[Model]

	select id, name, description, technical_specs from db_mktg.mst_tenderItemMaster

	select c.id,categoryid,dimensionid,name from db_mm.dtl_categorywise_dimension_mapping c 
	join db_mm.mst_dimension m on c.dimensionid=m.id
	--where categoryid=(select itemcategoryid from db_mm.mst_item where id =@itemid )	
	end
	



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

CREATE PROCEDURE [db_mm].[pr_commonapinrgp]
	@coid int,
	@boid int,
	@fyid int = null
	as
BEGIN
	SET NOCOUNT ON;
	-- get max nrgpno
	Select max(nrgpno) as nrgpno from [db_mm].[hdr_nrgp] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

	---get store
	 select id, name  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -- get employee
	select userid,firstname  from db_masters.users where  coid=@coid  and boid=@boid

	 ---get transport
	 SELECT [id],name from  [db_masters].[transport] where coid =  @coid  and boid=@boid

	end
	

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

--exec [db_mm].[pr_commonapipurchaseorder] 1,1,1
CREATE PROCEDURE [db_mm].[pr_commonapipurchaseorder]

	@coid int,
	@boid int,
	@fyid int = null
	
AS
BEGIN
	SET NOCOUNT ON;
	-- get max pono
		Select max(isnull(ordernumber,0)) as ordernumber from [db_mm].[hdr_purchaseorder] where coid=@coid and boid=@boid 

	
	-- get ship to bill to branches
	SELECT unitname,boid,[address1],[address2], [city],[state], [country],[pin],[taxationno] FROM [db_general].[company_branches] b where coid= cast(@coid as varchar(2))

	-- get paymentterms for ist time without supplier id check 
	SELECT id,name FROM [db_mm].[mst_paymentterms] where coid= cast(@coid as varchar(2)) and boid=cast(@boid as varchar(2))

	-- get item brands
	select id ,name  from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get item terms and conditions
	SELECT id,name FROM [db_mm].[mst_termsandconditions] where coid= @coid and boid=@boid 
	--get supplier category list
	select id, categoryname from db_masters.supplier_category 	where coid= @coid and boid=@boid  
		-- get costcentres
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid

	SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid,'R' as type,im.gstid,g.igst,g.cgst,g.sgst
	 from [db_mm].[hdr_bom] b
	 join  [db_mm].[mst_item] im on b.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	 left join db_mm.mst_gst g on im.gstid=g.gstid
	 union all select  DISTINCT (productid),im.[itemname],im.itemcode,U.uom,p.pbomid,'P' as type,im.gstid,g.igst,g.cgst,g.sgst
	from  [db_mm].[hdr_pbom] p
	join  [db_mm].[mst_item] im on p.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	 left join db_mm.mst_gst g on im.gstid=g.gstid

	 select gstid,description,igst,cgst,sgst from db_mm.mst_gst
	 declare @sql nvarchar(max)
	--set @sql='  select 1  id,''UN-CONFIRMED'' as STATUS ' 
	--set @sql+=   '  select 2  id,''CONFIRMED'' as STATUS '
	--set @sql+=  'select 3  id,''CONFIRMED'' as status '

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

	 Select id, potype, potypedesc from db_mm.mst_potype  where  coid= @coid and boid=@boid


	print  @sql
	EXEC sp_executesql @SQL
end 
	

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

CREATE PROCEDURE [db_mm].[pr_commonapirequisition]
	@coid int,
	@boid int,
	@fyid int = null
	as
BEGIN
	SET NOCOUNT ON;
	-- get max indentno
	Select max(reqnno) as reqnno from [db_mm].[hdr_requisition] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

    -- get costcentres
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid

	-- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get store
	 select id, name, case when checksexempted=1 then 0 else 1 end porequired  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -----
	-- SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid
	-- from [db_mm].[hdr_bom] b
	--join  [db_mm].[mst_item] im on b.productid=im.id
	--join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid

	SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid,'R' as type
	 from [db_mm].[hdr_bom] b
	 join  [db_mm].[mst_item] im on b.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	 union all select  DISTINCT (productid),im.[itemname],im.itemcode,U.uom,p.pbomid,'P' as type
	from  [db_mm].[hdr_pbom] p
	join  [db_mm].[mst_item] im on p.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid

	end
	

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

create PROCEDURE [db_mm].[pr_commonapirgp]
	@coid int,
	@boid int,
	@fyid int = null
	as
BEGIN
	SET NOCOUNT ON;
	-- get max rgpno
	Select max(rgpno) as rgpno from [db_mm].[hdr_rgp] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

	---get store
	 select id, name  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -- get employee
	select userid,firstname  from db_masters.users where  coid=@coid  and boid=@boid

	 ---get transport
	 SELECT [id],name from  [db_masters].[transport] where coid =  @coid  and boid=@boid

	end
	

GO
/****** Object:  StoredProcedure [db_mm].[pr_confirmvendorallocationlist]    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_mm].[pr_confirmvendorallocationlist] 1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_confirmvendorallocationlist]
    @userid int,
	@listid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @coid int,@boid int, @fyid int

	update db_mm.hdr_vendor_allocation_list set confirmedby = @userid, confirmedon = getdate() where listid = @listid
	and createdby = @userid
	
	select @coid=coid,@boid=boid,@fyid=1 from db_mm.hdr_vendor_allocation_list

	exec [db_mm].[pr_getvendorallocationlistitems] @coid,@boid,@fyid,@listid
END
GO
/****** Object:  StoredProcedure [db_mm].[pr_copybom]    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_mm].[pr_copybom] 1,1,1028,'S',1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_copybom] 
@coid int,
@boid int,
@bomid bigint,
@type char(1)=null,
@userid int=1,
@productid INT=NULL

AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	IF OBJECT_ID('tempdb..#tree2') IS NOT NULL DROP TABLE #tree2
	create table #tree 
	(
		ID INT,
		parentid bigint,
		childid bigint,
		bomid bigint
	);
	create table #tree2 
	(
		ID INT,
		parentid bigint,
		childid bigint,
		bomid bigint,
		level int
	);
	
	--declare @date  date=(select todaydate from fn_get_todaydate())
	declare @datetime datetime=(SELECT  SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30'))
	
INSERT into #tree (bomid,id,parentid,childid ) 
SELECT bomid,id,pid,cid
from db_mm.dtl_bom  where coid=@coid and boid = @boid  

declare @sql varchar(max);

WITH x AS
(
    -- anchor:
    SELECT ID, parentid, childid,	[level] = 0 ,bomid
    FROM #tree WHERE bomid=@bomid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.parentid, t.childid, 	[level] = x.[level] + 1 ,t.bomid
    FROM x INNER JOIN #tree AS t 
    ON t.parentid = x.childid where x.[level]+1 <= x.[level]+1 
		
)
insert into #tree2 (ID, parentid, childid ,level,bomid)
SELECT ID, parentid, childid,level,bomid
FROM x order by [level]

DROP TABLE #tree;
select  distinct(bomid) from  db_mm.dtl_BOM where id in(select id from #tree2)


DECLARE @myCursor cursor;
DECLARE @bomidno char(100);
DECLARE @myCursor1 cursor;
DECLARE @bomidno1 char(100);
declare @newbomid bigint;
declare @version int;
declare @levelno int
BEGIN
  SET @myCursor = CURSOR FOR
 select  distinct(bomid) from  db_mm.dtl_BOM where id in(select id from #tree2)

  OPEN @myCursor
  FETCH NEXT FROM @myCursor
  INTO @bomidno

  WHILE @@FETCH_STATUS = 0
        BEGIN
		set @levelno =(select top(1) [level] from #tree2 where bomid=@bomidno)
		if (@levelno=0) 
		begin
		set @version =( select isnull(max([version]),0)+1 from [db_mm].hdr_customizedbom where productid =@productid)
            insert into [db_mm].hdr_bom ([productid],[version],[createdby],[createdon],[remarks],[coid],[boid],[drawingno],[batchsize])
			Select @productid,@version,@userid,@datetime,[remarks],[coid],[boid],[drawingno],[batchsize] 
			from [db_mm].hdr_bom where bomid =@bomidno			
		end
		else
		begin
	       set @version =( select isnull(max([version]),0)+1 from [db_mm].hdr_customizedbom where productid =(Select [productid] from [db_mm].hdr_bom where bomid =@bomidno))
            insert into [db_mm].hdr_bom ([productid],[version],[createdby],[createdon],[remarks],[coid],[boid],[drawingno],[batchsize])
			Select [productid],@version,@userid,@datetime,[remarks],[coid],[boid],[drawingno],[batchsize] 
			from [db_mm].hdr_bom where bomid =@bomidno			
	  end
	
	  SELECT @newbomid= SCOPE_IDENTITY()
		    BEGIN
  SET @myCursor1 = CURSOR FOR
 select  id from  db_mm.dtl_BOM where bomid =@bomidno

  OPEN @myCursor1
  FETCH NEXT FROM @myCursor1
  INTO @bomidno1

  WHILE @@FETCH_STATUS = 0
        BEGIN
		if (@levelno=0) 
		begin
			insert into [db_mm].[dtl_bom] ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width])
				select @newbomid,@productid,[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width]
				from [db_mm].[dtl_bom]	where id =@bomidno1		  
		  end
		  else
		  begin
		  	insert into [db_mm].[dtl_bom] ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width])
				select @newbomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width]
				from [db_mm].[dtl_bom]	where id =@bomidno1	
		  end
FETCH NEXT FROM @myCursor1 INTO @bomidno1 
			              
        END   
  CLOSE @myCursor1
  DEALLOCATE @myCursor1
END
FETCH NEXT FROM @myCursor INTO @bomidno 
			              
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END
END














GO
/****** Object:  StoredProcedure [db_mm].[pr_copycustbom]    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_mm].[pr_copycustbom] 1,1,1028,'S',1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_copycustbom] 
@coid int,
@boid int,
@bomid bigint,
@type char(1)=null,
@userid int=1,
@productid INT=NULL

AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	IF OBJECT_ID('tempdb..#tree2') IS NOT NULL DROP TABLE #tree2
	create table #tree 
	(
		ID INT,
		parentid bigint,
		childid bigint,
		bomid bigint
	);
	create table #tree2 
	(
		ID INT,
		parentid bigint,
		childid bigint,
		bomid bigint
	);
	
	--declare @date  date=(select todaydate from fn_get_todaydate())
	declare @datetime datetime=(SELECT  SWITCHOFFSET(SYSDATETIMEOFFSET(), '+05:30'))
	
INSERT into #tree (bomid,id,parentid,childid ) 
SELECT bomid,id,pid,cid
from db_mm.dtl_bom  where coid=@coid and boid = @boid  

declare @sql varchar(max);

WITH x AS
(
    -- anchor:
    SELECT ID, parentid, childid,	[level] = 0 
    FROM #tree WHERE bomid=@bomid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.parentid, t.childid, 	[level] = x.[level] + 1 
    FROM x INNER JOIN #tree AS t 
    ON t.parentid = x.childid where x.[level]+1 <= x.[level]+1 
		
)
insert into #tree2 (ID, parentid, childid )
SELECT ID, parentid, childid
FROM x order by [level]

DROP TABLE #tree;
select  distinct(bomid) from  db_mm.dtl_BOM where id in(select id from #tree2)

DECLARE @myCursor cursor;
DECLARE @tableName char(100);
DECLARE @myCursor1 cursor;
DECLARE @tableName1 char(100);
declare @newbomid bigint
declare @version int
BEGIN
  SET @myCursor = CURSOR FOR
 select  distinct(bomid) from  db_mm.dtl_BOM where id in(select id from #tree2)

  OPEN @myCursor
  FETCH NEXT FROM @myCursor
  INTO @tableName

  WHILE @@FETCH_STATUS = 0
        BEGIN
		
		if (@type='S')
	begin
	set @version =( select isnull(max([version]),0)+1 from [db_mm].hdr_customizedbom where productid =(Select [productid] from [db_mm].hdr_bom where bomid =@tableName))
            insert into [db_mm].hdr_customizedbom ([productid],[version],[createdby],[createdon],[remarks],[coid],[boid],[drawingno],[batchsize])
			                                Select @productid,@version,@userid,@datetime,[remarks],[coid],[boid],[drawingno],[batchsize] 
			from [db_mm].hdr_bom where bomid =@tableName			
	  end
	  if (@type='C')
	begin
		set @version =( select isnull(max([version]),0)+1 from [db_mm].hdr_customizedbom where productid =(Select [productid] from [db_mm].hdr_customizedbom where bomid =@tableName))
            insert into [db_mm].hdr_customizedbom ([productid],[version],[createdby],[createdon],[remarks],[coid],[boid],[drawingno],[batchsize])
			Select @productid,@version,@userid,convert(varchar(20),@datetime,20),[remarks],[coid],[boid],[drawingno],[batchsize] 
			from [db_mm].hdr_customizedbom where bomid =@tableName
			
	  end
	  SELECT @newbomid= SCOPE_IDENTITY()
		    BEGIN
  SET @myCursor1 = CURSOR FOR
 select  id from  db_mm.dtl_BOM where bomid =@tableName

  OPEN @myCursor1
  FETCH NEXT FROM @myCursor1
  INTO @tableName1

  WHILE @@FETCH_STATUS = 0
        BEGIN
		if (@type='S')
	begin
			insert into [db_mm].[dtl_customizedbom] ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width])
				select @newbomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width]
				from [db_mm].[dtl_bom]	where id =@tableName1		  
		    end
			if (@type='C')
	begin
			insert into [db_mm].[dtl_customizedbom] ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width])
				select @newbomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width]
				from [db_mm].dtl_customizedbom	where id =@tableName1		  
		    end
FETCH NEXT FROM @myCursor1 INTO @tableName1 
			              
        END   
  CLOSE @myCursor1
  DEALLOCATE @myCursor1
END
FETCH NEXT FROM @myCursor INTO @tableName 
			              
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END
END














GO
/****** Object:  StoredProcedure [db_mm].[pr_explod_bom_only_subassbly]    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_mm].[pr_explod_bom_only_subassbly]  1,1,1028,'5'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_explod_bom_only_subassbly] 
@coid int,
@boid int,
@bomid int

AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	create table #tree 
	(
		ID INT,
		parentname VARCHAR(500),
		parentcode varchar(50),
		childname varchar(500),
		parentid bigint,
		childid bigint,
		unitid int,
		unit varchar(50),
		itemcode varchar(50), 
		oldcode	varchar(50),
		quantity decimal(10,3),
		tolerance decimal(10,3),
		brandid	int,
		wastagequantity decimal(10,3),
		wastagepercent decimal(10,3),
        toexplode bit,
		bomid bigint,
		rmtype bigint,
		rm_item varchar(500),
		length	decimal(10,3),
		width decimal(10,3)
	);
	create table #tree2 
	(
		ID INT,
		parentid bigint,
		childid bigint,
		bomid bigint,
		parentname VARCHAR(500),
		parentcode varchar(50),
		[level] int
	);

INSERT into #tree (bomid,id,parentid,childid, quantity,tolerance,brandid,wastagequantity,wastagepercent,unitid,toexplode,rmtype,length,width) 
SELECT bomid,id,pid,cid,quantity,tolerance,brandid,wastagequantity,wastagepercent,unit ,toexplode ,rmtype,length,width
from db_mm.dtl_bom  where  coid=@coid and boid = @boid  

update #tree set childname = a.itemname, itemcode = a.itemcode, oldcode = a.oldcode 
from db_mm.mst_item a where #tree.childid = a.id ;

update #tree set rm_item = a.itemname+ ' '+ isnull(a.itemcode,'') +' '+ isnull(a.oldcode,'')
from db_mm.mst_item a where #tree.rmtype = a.id ;

update #tree set parentname = a.itemname, parentcode = a.oldcode
from db_mm.mst_item a where #tree.parentid = a.id;

declare @sql varchar(max);

WITH x AS
(
    -- anchor:
    SELECT ID, parentid, childid, parentname,parentcode,childname,oldcode childcode, cast(quantity as decimal(13,2)) quantity, tolerance,
	cast(wastagequantity as decimal(13,2)) wastagequantity,wastagepercent, toexplode,[level] = 0 ,rm_item,length,width,bomid
    FROM #tree WHERE bomid=@bomid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.parentid, t.childid, t.parentname,t.parentcode,t.childname,t.oldcode childcode, cast(x.quantity*t.quantity as decimal(13,2)) quantity, t.tolerance,
	cast(x.quantity*t.wastagequantity as decimal(13,2)) wastagequantity,t.wastagepercent,t.toexplode,  
	[level] = x.[level] + 1 ,t.rm_item,t.length,t.width,t.bomid
    FROM x INNER JOIN #tree AS t 
    ON t.parentid = x.childid where x.[level]+1 <= (x.[level]+1) and x.[level]+1 <= (x.[level]+1)
	
)
insert into #tree2 (ID, parentid ,bomid,parentname,parentcode,[level])
SELECT ID, parentid ,bomid,parentname,parentcode,[level]
FROM x order by [level]


DROP TABLE #tree;
WITH cts AS
(
select * ,ROW_NUMBER() OVER(Partition by parentid ORDER BY [level]) AS Row_Number from #tree2
)	
select * from  cts where Row_Number=1
END














GO
/****** Object:  StoredProcedure [db_mm].[pr_explodeBOM]    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_mm].[pr_explodeBOM] 1,1,1,''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_explodeBOM] 
@coid int,
@boid int,
@itemid bigint,
@level int=null
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	create table #tree 
	(
		ID INT,
		parentname VARCHAR(200),
		parentcode varchar(50),
		childname varchar(200),
		parentid bigint,
		childid bigint,
		unitid int,
		unit varchar(50),
		itemcode varchar(50), 
		oldcode	varchar(50),
		quantity decimal(10,3),
		tolerance decimal(10,3),
		brandid	int,
		wastagequantity decimal(10,3),
		wastagepercent decimal(10,3),
        toexplode bit
	);


/*insert into #tree (id,parentid,childid, quantity,tolerance,brandid,wastagequantity,wastagepercent,unitid,toexplode) 
select bomid,0,productid,batchsize, 0,0,0,0,0,1 from db_mm.hdr_bom 
where coid = @coid and boid = @boid */

INSERT into #tree (id,parentid,childid, quantity,tolerance,brandid,wastagequantity,wastagepercent,unitid,toexplode) 
SELECT id,pid,cid,quantity,tolerance,brandid,wastagequantity,wastagepercent,unit ,toexplode 
from db_mm.dtl_bom  where coid=@coid and boid = @boid  


-- update childname,oldcode, itemcode from itemmaster
update #tree set childname = a.itemname, itemcode = a.itemcode, oldcode = a.oldcode 
from db_mm.mst_item a where #tree.childid = a.id ;

-- update parentname,parentcode itemmaster
update #tree set parentname = a.itemname, parentcode = a.oldcode
from db_mm.mst_item a where #tree.parentid = a.id;

--select * from #tree

declare @sql varchar(max);

WITH x AS
(
    -- anchor:
    SELECT ID, parentid, childid, parentname,parentcode,childname,oldcode childcode, cast(quantity as decimal(13,2)) quantity, tolerance,
	cast(wastagequantity as decimal(13,2)) wastagequantity,wastagepercent, toexplode,[level] = 0 
    FROM #tree WHERE parentid=@itemid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.parentid, t.childid, t.parentname,t.parentcode,t.childname,t.oldcode childcode, cast(x.quantity*t.quantity as decimal(13,2)) quantity, t.tolerance,
	cast(x.quantity*t.wastagequantity as decimal(13,2)) wastagequantity,t.wastagepercent,t.toexplode,  
	[level] = x.[level] + 1 
    FROM x INNER JOIN #tree AS t 
    ON t.parentid = x.childid where x.[level]+1 <= coalesce(@level,x.[level]+1) and x.[level]+1 <= coalesce(@level,x.[level]+1)
	
)
SELECT ID, parentid,parentname, parentcode, childid,
case when quantity>0 then childname + '    Qty:' + cast(quantity as varchar(20)) + '    Tolerance:' + cast(tolerance as varchar(20)) else childname end as childname,
childcode, quantity,tolerance,wastagequantity,wastagepercent, [level]
 FROM x 
ORDER BY [level]
OPTION (MAXRECURSION 100);
DROP TABLE #tree;
	
--select itemname from db_mm.mst_item where id =@itemid

END














GO
/****** Object:  StoredProcedure [db_mm].[pr_explodeBOM_bomid_wise]    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_mm].[pr_explodeBOM_bomid_wise] 1,1,1028,'5'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_explodeBOM_bomid_wise] 
@coid int,
@boid int,
@bomid bigint,
@level int=null
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	create table #tree 
	(
		ID INT,
		parentname VARCHAR(500),
		parentcode varchar(50),
		childname varchar(500),
		parentid bigint,
		childid bigint,
		unitid int,
		unit varchar(50),
		itemcode varchar(50), 
		oldcode	varchar(50),
		quantity decimal(10,3),
		tolerance decimal(10,3),
		brandid	int,
		wastagequantity decimal(10,3),
		wastagepercent decimal(10,3),
        toexplode bit,
		bomid bigint,
		rmtype bigint,
		rm_item varchar(500),
		length	decimal(10,3),
		width decimal(10,3)
	);


INSERT into #tree (bomid,id,parentid,childid, quantity,tolerance,brandid,wastagequantity,wastagepercent,unitid,toexplode,rmtype,length,width) 
SELECT bomid,id,pid,cid,quantity,tolerance,brandid,wastagequantity,wastagepercent,unit ,toexplode ,rmtype,length,width
from db_mm.dtl_bom  where coid=@coid and boid = @boid  

update #tree set childname = a.itemname, itemcode = a.itemcode, oldcode = a.oldcode 
from db_mm.mst_item a where #tree.childid = a.id ;

update #tree set rm_item = a.itemname+ ' '+ isnull(a.itemcode,'') +' '+ isnull(a.oldcode,'')
from db_mm.mst_item a where #tree.rmtype = a.id ;

update #tree set parentname = a.itemname, parentcode = a.oldcode
from db_mm.mst_item a where #tree.parentid = a.id;

declare @sql varchar(max);

WITH x AS
(
    -- anchor:
    SELECT ID, parentid, childid, parentname,parentcode,childname,oldcode childcode, cast(quantity as decimal(13,2)) quantity, tolerance,
	cast(wastagequantity as decimal(13,2)) wastagequantity,wastagepercent, toexplode,[level] = 0 ,rm_item,length,width
    FROM #tree WHERE bomid=@bomid
    UNION ALL
    -- recursive:
    SELECT t.ID, t.parentid, t.childid, t.parentname,t.parentcode,t.childname,t.oldcode childcode, cast(x.quantity*t.quantity as decimal(13,2)) quantity, t.tolerance,
	cast(x.quantity*t.wastagequantity as decimal(13,2)) wastagequantity,t.wastagepercent,t.toexplode,  
	[level] = x.[level] + 1 ,t.rm_item,t.length,t.width
    FROM x INNER JOIN #tree AS t 
    ON t.parentid = x.childid where x.[level]+1 <= coalesce(@level,x.[level]+1) and x.[level]+1 <= coalesce(@level,x.[level]+1)
	
)
--SELECT * FROM x 
SELECT parentcode Product_Code ,parentname Parent_Item_Product_Name_Sub_Assy_Component,childcode Item_Code, childname Child_Item_Name_Sub_Assy,
 isnull(quantity,0) Quantity,isnull(tolerance,0) Tolerance,isnull(wastagequantity,0) Wastage_Qty,isnull(wastagepercent,0) WastagePercent,isnull(rm_item,'') RM_Item,isnull(length,0) Length,isnull(width,0) Width, [level]
 FROM x 
ORDER BY [level]
OPTION (MAXRECURSION 100);

DROP TABLE #tree;
	

END














GO
/****** Object:  StoredProcedure [db_mm].[pr_generatepoforVAL]    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_mm].[pr_generatepoforVAL] 1,1,1,1,28
-- =============================================
CREATE PROCEDURE [db_mm].[pr_generatepoforVAL]
    @coid int,
	@boid int,
	@fyid int,
	@userid int,
	@listid int
AS
Begin
	--select top 1 * from db_mm.hdr_vendor_allocation_list
	

	DECLARE @suplid int, @suplstateid int, @compstateid int
	DECLARE @poamount decimal(15,3)

	select @compstateid = homestateid from db_general.company_branches

	DECLARE cur CURSOR FOR select distinct suplid, sum(isnull(itemrate,1)*isnull(qtyapproved,1)) poamount, sp.state
	from db_mm.dtl_vendor_allocation_list lt join db_masters.supplier sp on lt.suplid = sp.id 
	where listid = @listid group by suplid, sp.state

	OPEN cur

	FETCH NEXT FROM cur INTO @suplid, @poamount, @suplstateid

	WHILE @@FETCH_STATUS = 0 BEGIN
		declare @poheader [db_mm].[hdr_purchaseorder_tvp]
		declare @podetail [db_mm].[dtl_purchaseorder_tvp]
		declare @popaymentterms [db_mm].[purchase_paymentterms_tvp]
		declare @potermsandconditions [db_mm].[purchase_termsandconditions_tvp]
		declare @podeliveryschedule [db_mm].[purchase_deliveryschedule_tvp] 
		declare @pofollowup [db_mm].[purchase_followup_tvp] 
		

		if (@suplstateid = @compstateid) begin set @compstateid =  1 end else begin set @compstateid = 0 end

		insert into @poheader (orderid,orderdate,ordernumber,ordertype,suplid,suplname,supladdress1,supladdress2, suplcity,suplstate,
		suplpincode,suplphoneNo,suplcontactperson,supltaxregistrationnumber,billingaddress,billingcity,billingstate,billingpincode,
		billinggstin,shippingaddress,shippingcity,shippingstate,shippingpincode,shippinggstin,quotationid,poamount,potaxamount,podiscount,
		pofrieghtamount,amendmentnumber,frieghttype,customduty,clgfwdcharges,taxonclgfwdcharges,currency,currencyrate,postatus,
		boid,coid,remarks,isactive,createdby,createdon,modifiedby,modifiedon,deactivatedby,deactivatedon,shiptoid,billtoid,fyid,
		quotationref,costcentreid,isjobwork) 
		select @listid orderid, getdate() orderdate, 0 ordernumber,1 ordertype, @suplid, mstsup.name suplname,mstsup.address1 supladdress1, mstsup.address2 supladdress2,
		ct.cityname suplcity,st.statename suplstate, mstsup.pin suplpincode,
		mstsup.phone_number suplphoneNo, '' suplcontactperson, mstsup.vat_number supltaxregistrationnumber, 
		mstsup.address1  billingaddress,
		ct.cityname billingcity,st.statename billingstate, mstsup.pin billingpincode, mstsup.vat_number billinggstin,
		mstsup.address1 shippingaddress,
		ct.cityname shippingcity,st.statename shippingstate, mstsup.pin shippingpincode, mstsup.vat_number shippinggstin,
		0 quotationid, @poamount, 0 potaxamount, 0 podiscount, 0 pofreightamount,
		0 amendmentnumber, '' freighttype, 0 customduty, 0 clgfwdcharges, 0 taxonclgfwdcharges, 'IN' currency, 1 currencyrate, '1' postatus, @boid, @coid, 
		'PO generated through Vendor Allcoation' remarks, 1 isactive, @userid createdby,getdate() createdon, 0 modifiedby,getdate() modifiedon, 0 deactivedby,
		getdate() deactivatedon,@suplid shiptoid, @suplid billtoid, @fyid fyid, '' quotationref, 1 costcenterid, 0 isjobwork 
		from db_masters.supplier mstsup 
		left join db_masters.statemaster st on mstsup.[state] = st.id 
		left join db_masters.city ct on mstsup.city= ct.id 
		where mstsup.id = @suplid
		group by mstsup.id,mstsup.name,mstsup.address1,mstsup.address2,ct.cityname,st.statename,mstsup.pin,
		mstsup.phone_number,mstsup.vat_number 

		insert into @podetail
		select 0 id, 0 orderid, itemid,itemquantity,0,mst.itemname itemname, itemrate, um.uom itemuom, 0 itemdiscount, 
		(itemrate*(isnull(gst.igst,0)/100)) itemtax, (itemrate*(1+(isnull(gst.igst,0)/100))) netrate,
		indentid, lst.remarks, brandid, mst.gstid gstid, case when @compstateid = 1 then 0 else (itemrate*(isnull(gst.igst,0)/100)) end igstamount, 
		case when @compstateid = 0 then 0 else itemrate*(isnull(gst.cgst,0)/100)  end cgstamount, 
		case when @compstateid = 0 then 0 else itemrate*(isnull(gst.sgst,0)/100)  end sgstamount, brandid, 0 bomversion,0 discpercent from 
		db_mm.dtl_vendor_allocation_list lst join db_mm.mst_item mst on lst.itemid = mst.id 
		left join db_mm.mst_itemuom um on mst.receivingunitid = um.id join db_mm.mst_gst gst on mst.gstid = gst.gstid 
		where listid = @listid and suplid =@suplid
		
		if exists (select orderid from db_mm.hdr_purchaseorder where suplid = @suplid)
			begin
				insert into @popaymentterms
				select 0 id, 0 orderid, 0 paymenttermid,@coid,@boid,1 isactive,@userid createdby,getdate() createdon,
				null,null,null,null,paymentterm from db_mm.purchase_paymentterms 
				where orderid = (select max(orderid) from db_mm.hdr_purchaseorder where suplid = @suplid)

				insert into @potermsandconditions
				select 0 id, 0 orderid, termsandconditionsid, @coid, @boid,1 isactive,@userid createdby, getdate() createdon,
				null,null,null,null, termsandcondition from db_mm.purchase_termsandconditions 
				where orderid = (select max(orderid) from db_mm.hdr_purchaseorder where suplid = @suplid)
			end
		else
			begin
				insert into @popaymentterms
				select 0 id, 0 orderid, id paymenttermid,@coid,@boid,1 isactive,@userid createdby,getdate() createdon,
				null,null,null,null,name paymentterms from db_mm.mst_paymentterms where isactive = 1 

				insert into @potermsandconditions
				select 0 id, 0 orderid,id termsandconditionid, @coid, @boid,1 isactive,@userid createdby, getdate() createdon,
				null,null,null,null, name termsandcondition from db_mm.mst_termsandconditions where isactive =1 
			end

		
		exec db_mm.pr_savepo 'Insert', @poheader,@podetail,@popaymentterms,@potermsandconditions,@podeliveryschedule,@pofollowup,@userid,'V'

		FETCH NEXT FROM cur INTO @suplid, @poamount, @suplstateid
	END

	CLOSE cur    
	DEALLOCATE cur
	
	select * from @poheader
	select * from @podetail
End


GO
/****** Object:  StoredProcedure [db_mm].[pr_get_standard_customized_bomlist]    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].[pr_getstandardbomlist] 1,600,1,1,1,'Itemname','asc',null,1,1,null,null,1,'',''
-- =============================================

CREATE PROCEDURE [db_mm].[pr_get_standard_customized_bomlist] 	
	@coid int = 1,
	@boid int = 1,
	@search nvarchar(100)=NULL,
	@userid int=1,
	@CHECKBOMTYPE VARCHAR =NULL

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

	BEGIN
	IF(@CHECKBOMTYPE='S')
	
	BEGIN

	set @sql = '
	SELECT hdr.bomid,hdr.productid,hdr.version,hdr.remarks,hdr.coid,hdr.boid,hdr.drawingno,hdr.batchsize,
	im.itemname,im.itemdescription,im.id,im.itemcode,im.hsncode,im.oldcode,im.remarks,im.receivingunitid,um.uom
	FROM [db_mm].[hdr_bom] hdr
	join [db_mm].[mst_item] im on hdr.productid=im.id
	join [db_mm].[mst_itemuom] um on im.issuingunitid=um.id '

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

	if(@search!='')
		begin
		 set @sql += ' and im.itemname like '+'''%'+cast(@search as varchar(50)) + '%'''
		end 	
		set @sql +=' order by im.itemname'
	EXEC sp_executesql @SQL
	
	END

	ELSE
	BEGIN

	
	set @sql = 'SELECT hdr.bomid,hdr.productid,hdr.version,hdr.remarks,hdr.coid,hdr.boid,hdr.drawingno,hdr.batchsize,
	so.oano,so.oadate,so.customerid,so.customername,so.customeraddr1,so.customeraddr2, sod.itemid,im.itemname,im.itemcode
	FROM [db_mm].[hdr_customizedbom] hdr
	JOIN [db_sop].[dtl_saleorder] sod ON hdr.bomid=sod.bomid
	JOIN [db_sop].[hdr_saleorder] so ON sod.oaid=so.oaid 
	join [db_mm].[mst_item] im on hdr.productid=im.id'

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

	if(@search!='')
		begin
		 set @sql += ' and im.itemname like '+'''%'+cast(@search as varchar(50)) + '%'' or customername like '+'''%'+cast(@search as varchar(50)) + '%'''
		end 
		set @sql +=' order by customername,im.itemname'
	
	EXEC sp_executesql @SQL

	END
	end
END










GO
/****** Object:  StoredProcedure [db_mm].[pr_getbomdata]    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_mm].[pr_getbomdata] 1,1,7,'p'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getbomdata] 
	@coid int,
	@boid int,
	@bomid int,
	@type varchar(1)

AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @tablename varchar(100)
	declare @tablename1 varchar(100)
	declare @columnname varchar(100)
	
	set @tablename=(select CASE when lower(@type)='P' then   '[db_mm].[hdr_pbom]' when lower(@type)='C' THEN 'db_mm.hdr_customizedbom' else '[db_mm].[hdr_bom]' end)
	set @columnname=(select CASE when lower(@type)='P' then   'Pbomid' else 'bomid' end)
	set @tablename1=(select CASE when lower(@type)='p' then   '[db_mm].[dtl_pbom]' else '[db_mm].[dtl_bom]' end)
	set @sql = 'SELECT  '+ @columnname +' bomid,im.itemname,im.itemcode,im.itemdescription,ih.productid,ih.version,ih.drawingno,batchsize from '+ @tablename +' ih
     JOIN [db_mm].[mst_item] im ON ih.productid=im.id 
	 LEFT  JOIN [db_mm].[mst_itemuom] u ON im.receivingunitid=u.id
	 where ih.'+ @columnname +' = ' + cast(@bomid as varchar(5))
	 EXEC sp_executesql @SQL

	 if (lower(@type)='p')
	 begin
	set @sql ='select im.oldcode, d.pid productid,d.cid,im.itemname,im.itemcode,im.itemdescription,b.id brandid,b.name 
	brand,d.unit,u.uom unitdescription,[quantity],[wastagequantity],[wastagepercent],tolerance,length,width 
	from '+ @tablename1 +'  d
	JOIN [db_mm].[mst_item] im ON d.cid=im.id
	LEFT JOIN [db_mm].[mst_brand] b ON d.brandid=b.id
	LEFT  JOIN [db_mm].[mst_itemuom] u ON d.unit=u.id	
	where D.'+ @columnname +' =' + cast(@bomid as varchar(5))
	end 
	else 
	begin
	set @sql ='select im.oldcode,im.id as itemid, d.pid productid,d.cid,im.itemname,im.itemcode,im.itemdescription,b.id brandid,b.name 
	brand,d.unit,u.uom unitdescription,[quantity],[wastagequantity],[wastagepercent],tolerance,length,width ,d.bomid,
	case when  lower('''+@type+''')=''i'' then componentweight end componentweight,
	case when  lower('''+@type+''')=''i'' then rmtype end rmtype
	from '+ @tablename1 +'  d
	JOIN [db_mm].[mst_item] im ON d.cid=im.id
	LEFT JOIN [db_mm].[mst_brand] b ON d.brandid=b.id
	LEFT  JOIN [db_mm].[mst_itemuom] u ON d.unit=u.id	
	where D.'+ @columnname +' =' + cast(@bomid as varchar(5))

	end

	--case when  lower('''+@type+''')=''i'' then componentweight end componentweight,
	--case when  lower('''+@type+''')=''i'' then rmtype end rmtype
	print @sql

	--select cid from db_mm.dtl_bom where bomid=2037
	--select id from db_mm.mst_item where id in (select cid from db_mm.dtl_bom where bomid=2038)
	--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 in (select itemcategoryid from db_mm.mst_item where id in (select cid from db_mm.dtl_bom where bomid=2038)  ) 
	end
	EXEC sp_executesql @SQL
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getbomlist]    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_mm].[pr_getbomlist] 1,10,1,1,'bomid','desc','P','Y'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getbomlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='itemname',
	@sortorder nvarchar(100)='desc',
	@type varchar(1),
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @tablename varchar(100)
	declare @columnname varchar(100)
	set @tablename=(select 
	CASE when lower(@type)='P' then   '[db_mm].[hdr_pbom]' when lower(@type)='O' then '[db_mm].[hdr_customizedbom]'  else '[db_mm].[hdr_bom]' end)
	
	set @columnname=(select CASE when lower(@type)='P' then   'Pbomid' else 'bomid' end)
	set @sort=(select CASE when lower(@type)='P' then   'Pbomid' else 'bomid' end)
	set @sql = 'Select '+ @columnname +' bomid,[productid],im.[itemname],im.oldcode oldcode,im.itemcode itemcode, h.version,h.[confirmedby],h.drawingno,h.[createdby],h.[createdon],h.[confirmedon],u.username from '+ @tablename +'  h
	join [db_masters].[users] u on h.createdby = u.userid 
	join[db_mm].[mst_item] im on h.productid=im.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql +=' and im.itemname like ''%' + cast(@search as varchar(50)) + '%'''
		end
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	 set @sql= 'select count(h.'+ @columnname +')records from   '+ @tablename +' h
     join [db_masters].[users] u on h.createdby = u.userid
	 join[db_mm].[mst_item] im on h.productid=im.id  '
	 EXEC sp_executesql @SQL
				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getbomversion]    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_mm].[pr_getbomversion] 1,1,2638,'R'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getbomversion] 
	@coid int = 1,
	@boid int = 1,
	@productid INT,
	@type char(1)= null

AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max)
	 if lower(@type)='r'
		begin
	set @sql = 'SELECT str( b.version) version,b.bomid,b.batchsize
	 from [db_mm].[hdr_bom] b
	WHERE b.productid=' + cast(@productid as varchar(5)) +  ' '
	end 
	else
	begin
	set @sql = 'SELECT str( b.version) version,b.pbomid bomid,b.batchsize
	 from [db_mm].[hdr_pbom]  b
	WHERE b.productid=' + cast(@productid as varchar(5)) +  ' '
	end 
	print @SQL
	EXEC sp_executesql @SQL
	 END
	--AND b.version!=0 
	--union
	--select 'N/A' as version,0 as bomid



GO
/****** Object:  StoredProcedure [db_mm].[pr_getbrandlist]    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_mm].[pr_getbrandlist]2,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getbrandlist] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id,name  from db_mm.mst_brand where  coid=@coid and boid=@boid
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getcommanapireport]    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_sop].[pr_getlastoano] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getcommanapireport] 
 @coid int,
 @boid int,
 @fyid int,
 @userid int
AS
BEGIN
	
select id,name from db_mm.mst_itemcategory im where im.id in (select itemcategoryid from db_mm.[itemcategories_userrights] where userid =cast(@userid as varchar(6))) order by ltrim(name)
select id,itemname name from db_mm.mst_item im where im.itemcategoryid in (select itemcategoryid from db_mm.[itemcategories_userrights] where userid =cast(@userid as varchar(6))) order by ltrim(itemname) 
select id,(name+' '+address1+' '+address2) name from db_masters.supplier order by name

	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getcompanybranches]    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_mm].[pr_getcompanybranches]2
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getcompanybranches] 
@coid INT = 2
AS
BEGIN
	SET NOCOUNT ON;
SELECT unitname,boid,[address1],[address2], [city],[state], [country],[pin],[taxationno] FROM [db_general].[company_branches] b where coid= cast(@coid as varchar(2))
END

--- to check the field of gstin in companybranches

GO
/****** Object:  StoredProcedure [db_mm].[pr_getcostcentre]    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_mm].[pr_getcostcentre]1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getcostcentre] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getdepartment]    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_mm].[pr_getdepartment]2,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getdepartment] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getdeptwisereservedstock]    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_mm].[pr_getuserwisereservedstock]  1,1,54067
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getdeptwisereservedstock] 
	@coid int,
	@boid int,
	@itemid int

AS
BEGIN
	SET NOCOUNT ON;
	
	 select dt.deptname, u.firstname username,h.createdon reqndate,sum(isnull(d.requestedquantity,0)-isnull(d.issuedquantity,0)-isnull(d.woffquantity,0)) rsvqty,h.remarks
         from db_mm.dtl_requisition d 
		 join db_mm.hdr_requisition h on d.reqnid=h.reqnid
		left  join [db_masters].[department]dt on h.deptid=dt.id
		left join db_masters.users u on h.createdon=u.userid
		  where d.itemid=@itemid   group by h.deptid, d.itemid,dt.deptname,h.createdon,h.remarks,u.firstname
         
	end





GO
/****** Object:  StoredProcedure [db_mm].[pr_getdestructiondata]    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_mm].[pr_getdestructiondata]  1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getdestructiondata] 
	@coid int,
	@boid int,
	@destructionid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [destructionid],[destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[totalamt]-[igstamt]-[cgstamt]-[sgstamt] netamt,[remarks],
	[othercharges],createdon
  from [db_mm].[hdr_destruction] ih
	 where ih.[destructionid] = @destructionid

	 select im.[itemcode],im.[itemname],id.itemid,[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
	 from [db_mm].[dtl_destruction] id
	   join [db_mm].[mst_item] im  on id.itemid= im.id
	   where id.[destructionid] = @destructionid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getdestructionList]    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_mm].[pr_getdestructionlist] 1,10,1,1,'1','asc',''
-- =============================================

CREATE PROCEDURE [db_mm].[pr_getdestructionList] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='destructionno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [destructionid],[destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt] ,h.[remarks],h.createdon from [db_mm].[hdr_destruction] h
	left  join [db_mm].[mst_store] s on h.presenceofuserid1=s.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.destructionno = ' + 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

	 select count(h.[destructionid])records from [db_mm].[hdr_destruction] h


				
	
	
	
END



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

-- =============================================
--[db_mm].[pr_getdprdata] 1,1,2
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getdprdata] 
	@coid int,
	@boid int,
	@dprid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [dprid],[dprnumber],[dprdate],[departmentid],d.[deptname],[manualslipno],ih.remarks from [db_mm].[hdr_dpr] ih
	 join [db_masters].[department] d on ih.departmentid = d.id
	 where ih.dprid = @dprid

	 select im.[itemcode],im.[itemname],im.id itemid ,b.[name],b.id brandid,id.quantity,[batchno],[mfgdate],[expirydate],[retestdate],id.brandid,id.arnumber from [db_mm].[dtl_dpr] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	  join [db_mm].[mst_item] im  on id.itemid= im.id
	   
	   where id.dprid = @dprid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getdprlist]    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_mm].[pr_getdprlist] 1,10,1,1,'dprnumber','asc'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getdprlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='dprnumber',
	@sortorder nvarchar(100)='asc',
	 @search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [dprid],[dprnumber],[dprdate],u.username,h.[departmentid],d.[deptname],[manualslipno] from [db_mm].[hdr_dpr] h
	join [db_masters].[department] d on h.departmentid= d.id
	join [db_masters].[users] u on h.createdby = u.userid '
		set @sql += ' where 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

	 select count(h.[dprid])records from [db_mm].[hdr_dpr] h
	 join [db_masters].[department] d on h.departmentid= d.id
	join [db_masters].[users] u on h.createdby = u.userid 
				
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getdrcrnoteforbillpassing]    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_mm].[pr_getdrcrnoteforbillpassing]1,1,1079
-- =============================================
CREATE   PROCEDURE [db_mm].[pr_getdrcrnoteforbillpassing] 
	@coid INT,
	@boid INT,
	@grnid INT
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	  Select d.adviceid,[adviceno],[advicedate], 'D' as [advicetype],[rate],[quantity],d.[amount],[orderid],[porate],[billquantity],[recdquantity],
	  d.[igstamount],d.[cgstamount],d.[sgstamount],d.itemid ,m.itemname,d.[amount]+d.[igstamount]+d.[cgstamount]+d.[sgstamount]  totalamount from [db_mm].[hdr_inwardadvice] h
	  join [db_mm].[dtl_inwardadvice] d  on h.adviceid=d.adviceid
	  join [db_mm].[mst_item] m on d.itemid=m.id
	  where h.inwardid=@grnid
	  

		

	--print @sql
	EXEC sp_executesql @SQL



				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getenqstatus]    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_mm].[pr_getdepartment]2,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getenqstatus]
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id,name  from db_mktg.mst_enqstatus where  coid= @coid and boid=@boid
	
	END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getgrncategory]    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_mm].[pr_getgrncategory]1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getgrncategory] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;

	select [id],[name],[parentid] from [db_mm].[mst_store] where  coid=@coid  and boid=@boid
	
	END



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

--EXEC [db_mm].[pr_getgrndata] 1,1,1064
CREATE PROCEDURE [db_mm].[pr_getgrndata] 
	@coid int,
	@boid int,
	@grnid int
	
AS
BEGIN
	SET NOCOUNT ON;
	declare @suplid varchar(10) set @suplid=(Select [suplid] FROM  [db_mm].[hdr_grn] where grnid = @grnid)
	declare @companystate int, @supplierstate int;
    declare @sameState bit = 0;

    set  @companystate = (select homestateid  from db_general.company_branches where boid =@boid)
    
    select @supplierstate = s.state from db_masters.supplier s JOIN db_mm.hdr_grn ih on s.id = ih.suplid and ih.grnid = @grnid

	 Select [grnid],[grnnumber],[grndate],[ih].[grncategoryid],[suplid],[poid],[billamount],[storeid],
	 [billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate],
	 [purchaseaccount],[grno],[grdate],[billpassamount],s.name,(s.address1+'  '+s.address2) address
	 ,s.[state],s.gsTin,s.city,s.pin,s.pan,ih.[status],isnull(freightandoctroi,0) freightandoctroi, othercharges, customduty customdutycharges, otherdiscount, jobworkamount, 
	 currency,billamount, totaltaxamount, billdiscount, billroundoff,billpassamount,igstamount, cgstamount, sgstamount
	 FROM  [db_mm].[hdr_grn] ih 
	  inner join db_masters.supplier s on ih.suplid=s.id 
	 where ih.grnid = @grnid
	 --select igstamount, cgstamount, sgstamount, freightandoctroi, othercharges, customduty, otherdiscount, jobworkamount, 
	 --currency,billamount, totaltaxamount, billdiscount, billroundoff,billpassamount  FROM  [db_mm].[hdr_grn]
     if (@companystate=@supplierstate) 
     BEGIN
        set @sameState=1
     END

	 select id.id,id.grnid,im.[itemname] itemdetail,im.itemcode,im.oldcode ,im.id itemid , b.[name],b.id brandid,[quantitybilled],[quantityreceived],[quantityrejected],
	 [quantityshortage],[quantitysurplus],[itemrate],[itemdiscount],id.[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty],id.batchno,id.mfgdate,
	 id.expirydate,case when @samestate = 1 then 0 else g.igst end igst,case when @sameState=1 then g.cgst else 0 end cgst,
     case when @sameState=1 then g.sgst else 0 end sgst,quantitybroken,im.itemcode,im.itemname,id.receiptuom,id.ratediff,id.orderid
	  --,round(id.[quantitybilled]*(id.itemrate-id.itemdiscount),2)+ 
	  --case when @samestate = 1 then id.sgstamount+id.cgstamount else id.igstamount end totalamount 
  --id.sgstamount+id.cgstamount + id.igstamount totalamount
  from [db_mm].[dtl_grn] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	 join [db_mm].[mst_item] im  on id.itemid= im.id
	left  join [db_mm].[mst_gst] g  on id.gstid= g.gstid	   
	 where id.grnid = @grnid

	 select [grnid],[itemid],[quantity],[brandid],[arnumber], CASE WHEN CONVERT(DATE, expirydate) = '1900-01-01 00:00:00.000' 
  THEN '' else expirydate end [expirydate], [mfgdate],[orderid],[batchno],[sampleqty],supplierretestdate from [db_mm].[grnbatchwise]
	 where grnid = @grnid

	select  h.orderid,[ordernumber], h.orderdate from [db_mm].[hdr_purchaseorder] h
	join  [db_mm].[dtl_purchaseorder] d on h.orderid= d.orderid
	where ((d.orderedquantity)-(isnull(d.receivedquantity,0) + isnull(d.writeoffquantity,0))) > 0
	and h.suplid = cast(@suplid as int) and h.orderdate < getdate();

	select * from db_mm.dtl_grn_levies where grnid=@grnid

	select m.id,levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from   db_masters.levies m 
 	join  [db_mm].[mst_gst] g on m.gstid=g.gstid where isinwardlevy=1

	end







GO
/****** Object:  StoredProcedure [db_mm].[pr_getgrnlist]    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_mm].[pr_getgrnlist] 1,20,1,1,'grnnumber','desc','','','','billno','',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getgrnlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid INT,
	@boid INT,
	@sort nvarchar(100)='grnnumber',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@status varchar(1) = '',
    @storeid int =null,
	@searchtype varchar(20) = '',
	@itemid int=null,
	@forqcreleased char(1)=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select  distinct (h.grnid),s.[name] suppliername ,st.name storename,[chalanno],[billno],[billamount],[gateentryno],[grnnumber],[grndate],h.status,case when h.status not like ''%E%'' then 0  else 1 end  canedit from [db_mm].[hdr_grn] h
	 join [db_masters].[supplier] s on h.suplid= s.id 
	 join [db_mm].[mst_store] st on h.storeid=st.id
	 join db_mm.grnbatchwise dtl on h.grnid=dtl.grnid
	 join db_mm.mst_item im on dtl.itemid=im.id'
	 	if   (@forqcreleased='Y')  
	BEGIN
		set @sql += ' where  dtl.qcby is not null  '
		 
	END
	 --	else 
	--begin
		--SET @sql += ' and dtl.qcby is  null '
		 
	--END
	if   (@itemid>0)  
	BEGIN
		set @sql += '   and dtl.itemid=' + cast(@itemid as varchar(5)) + '  '
		 
	END

		set @sql +=  ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if (@searchtype = 'grno' and @search!='') 
	begin
		set @sql += ' and h.grnnumber = '  + cast(@search as varchar(50)) + ' '
	end

	else if (@searchtype = 'suppliername' and @search!='')
	begin
		set @sql += ' and  s.name like ''%' + cast(@search as varchar(50)) + '%'''
	end

		if (@searchtype = 'billno' and @search!='') 
	begin
		set @sql += ' and h.billno like ''%' + cast(@search as varchar(50)) + '%'''
	end
		if(@status!='')
		begin
		 set @sql += ' and H.status like ''' + cast(@status as varchar(50)) + '%'''
		end
		if(@storeid!='')
		begin
		 set @sql += ' and H.storeid =  ' + cast(@storeid as varchar(2))
		end
		
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql=' select count(distinct(h.grnid))records from [db_mm].[hdr_grn] h
	join [db_masters].[supplier] s on h.suplid= s.id
	join [db_mm].[mst_store] st on h.storeid=st.id 
	 join db_mm.grnbatchwise dtl on h.grnid=dtl.grnid
	 join db_mm.mst_item im on dtl.itemid=im.id'
	 	if   (@forqcreleased='Y')  
	BEGIN
		set @sql += ' where  dtl.qcby is not null  '
		 
	END
	 	--else 
	--begin
		--set @sql += ' and dtl.qcby is  null '
		 
	--END
	if   (@itemid>0)  
	BEGIN
		set @sql += '   and dtl.itemid=' + cast(@itemid as varchar(5)) + '  '
		 
	END

		set @sql +=  ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if (@searchtype = 'grno' and @search!='') 
	begin
		set @sql += ' and h.grnnumber = '  + cast(@search as varchar(50)) + ' '
	end

	else if (@searchtype = 'suppliername' and @search!='')
	begin
		set @sql += ' and  s.name like ''%' + cast(@search as varchar(50)) + '%'''
	end

		if (@searchtype = 'billno' and @search!='') 
	begin
		set @sql += ' and h.billno like ''%' + cast(@search as varchar(50)) + '%'''
	end
		if(@status!='')
		begin
		 set @sql += ' and H.status like ''' + cast(@status as varchar(50)) + '%'''
		end
		if(@storeid!='')
		begin
		 set @sql += ' and H.storeid =  ' + cast(@storeid as varchar(2))
		end
		
		
	EXEC sp_executesql @SQL

				
	
	
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getgrnlistforbillpassing]    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_mm].[pr_getgrnlistforbillpassing] 1,1,181
-- =============================================
CREATE  PROCEDURE [db_mm].[pr_getgrnlistforbillpassing] 
	@coid INT,
	@boid INT,
	@partyid INT
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select st.[name],[chalanno],[billno],[billdate],[chalandate],[billamount],[gateentryno], [grnid],[grnnumber],[grndate],p.name from [db_mm].[hdr_grn] h
	left join [db_mm].[mst_store] st on h.storeid=st.id
	left join [db_accounts].[accountGroups] p
	on h.purchaseaccount=p.parentgroupid where billno!='''' and   h.suplid=' + cast(@partyid as varchar(5)) 

		set @sql += ' and  h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))

	--print @sql
	EXEC sp_executesql @SQL

	 select count(h.[grnid])records from [db_mm].[hdr_grn] h
	join [db_masters].[supplier] s on h.suplid= s.id

				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getgrnlistforconfirmation]    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_mm].[pr_getgrnlistforconfirmation]  1,100,1,1,'grnid','asc',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getgrnlistforconfirmation] 
	@PageNumber INT,
	@PageSize INT,
	@coid INT,
	@boid INT,
	@sort nvarchar(100)='grnnumber',
	@sortorder nvarchar(100)='asc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select  distinct(h.grnid),s.[name] suppliername ,st.name storename,[chalanno],[billno],[billamount],[gateentryno],[grnnumber],[grndate] from [db_mm].[hdr_grn] h
	 join [db_masters].[supplier] s on h.suplid= s.id 
	join [db_mm].[mst_store] st on h.storeid=st.id
	join [db_mm].[grnbatchwise] b on h.grnid = b.grnid
	where b.qcby is not null and h.status not  like ''%C%'''
	print @sql
		set @sql += ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.grnnumber = ' + cast(@search as varchar(5)) 
		end
		print @sql
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL

	set @sql = 'Select  count(h.grnid) from [db_mm].[hdr_grn] h
	 join [db_masters].[supplier] s on h.suplid= s.id 
	join [db_mm].[mst_store] st on h.storeid=st.id
	join [db_mm].[grnbatchwise] b on h.grnid = b.grnid
	where b.qcby is not null and h.status not  like ''%C%'''

		set @sql += ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.grnnumber = ' + cast(@search as varchar(5)) 
		end
		print @sql
		
		EXEC sp_executesql @SQL
				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getgstdata]    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_mm].[pr_getrequisitiondata] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getgstdata] 
	@coid int,
	@boid int,
	@gstid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [description],[hsncode],[code],[igst],[cgst],[sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],
    [igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],[concessionaligst],[concessionalcgst],[concessionalsgst],saleacid,purchaseacid from [db_mm].[mst_gst] where gstid=@gstid
	end



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <alter Date,23/05/2019 5:49:41>
-- Description:	<Description,Get supplier data>
--[db_mm].[pr_getrequisitiondata] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_gethsndata] 
	@coid int,
	@boid int,
	@hsnid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [hsncode],[gstid],[Concessionaltaxid],id from [db_mm].[mst_hsn] where id=@hsnid and coid=@coid and boid =@boid
	end



GO
/****** Object:  StoredProcedure [db_mm].[pr_getindentdata]    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_mm].[pr_getindentdata] 1,1,16
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getindentdata] 
	@coid int,
	@boid int,
	@indentid bigint

AS
BEGIN
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#tempindentdetail') IS NOT NULL DROP TABLE #tempindentdetail
	create table #tempindentdetail 
	(
		id					bigint,
		itemid				bigint,
		itemcode			VARCHAR(11),
		oldcode			    VARCHAR(11),
		itemname			varchar(200),
		issuingunitid		int,
		issuingunit			varchar(20),
		brandid				int,
		brand				varchar(20),
		stockinhand			decimal(15,3),
		pendingpoqty		decimal(15,3),
		pendingindentqty	decimal(15,3),
		lastpurchaseqty		decimal(15,3),
		lastpurchaserate	decimal(15,2),
		lastpurchasedate	varchar(20),
		quantityrequired	decimal(15,3),
		remarks				varchar(500),
		requiredby			date,
		suplname			varchar(200)
	);

	declare @fyid int 
	select @fyid=fyid from [db_mm].[hdr_indent] where indentid = @indentid
	Select [indentid],[indentnumber],[indentdate],[departmentid],d.[deptname],[manualslipno],[indentorid],
	[costcentreid],c.[name] from [db_mm].[hdr_indent] ih
	 join [db_masters].[costcentre] c on ih.costcentreid =c.id
	 join [db_masters].[department] d on ih.departmentid = d.id
	 where ih.indentid = @indentid and ih.coid=@coid and ih.boid=@boid 
	 
	 -- insert item details from dtl_indent
	 insert into #tempindentdetail (
		id,itemid,brandid,quantityrequired,remarks,requiredby,suplname,stockinhand,pendingindentqty,pendingpoqty,
		lastpurchaseqty,lastpurchaserate)
		(select id,itemid,brandid,quantityrequired,remarks,requiredby,suplname,0,0,0,0,0  
	from [db_mm].[dtl_indent] id where indentid = @indentid)

	 --update item data from item master
	 update #tempindentdetail set itemcode = im.itemcode,oldcode = im.oldcode, itemname = im.itemname, issuingunitid = im.issuingunitid,
	 lastpurchaserate = im.lastpurchaserate, lastpurchasedate = isnull(cast(im.lastreceiptdate as varchar(20)),'')
	 from db_mm.mst_item im where itemid = im.id

	 --update unit name from unit master
	 update #tempindentdetail set issuingunit = um.uom 
	 from db_mm.mst_itemuom um where issuingunitid = um.id 
	
	 -- update item brand from db_mm.mst_brand
	 update #tempindentdetail set brand = br.name
	 from db_mm.mst_brand br where br.id = brandid 
	
	-- update stock from db_mm.item_stk_trn table, trytype = 16 for opening stock
	update #tempindentdetail set stockinhand =  isnull(stk.itemquantity,0) from 
	db_mm.item_stk_trn stk where #tempindentdetail.itemid = stk.itemid and stk.boid=@boid  and stk.trntypeid = 16 and 
	stk.coid =@coid and stk.fyid=@fyid 

	-- calculate stock in hand 
	update #tempindentdetail set stockinhand = stockinhand + isnull(stk.stock,0) 
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+'1') as int)) stock 
	from db_mm.item_stk_trn where boid=@boid and coid =@coid and fyid=@fyid group by itemid) stk
	where #tempindentdetail.itemid = stk.itemid 

	-- update pending po qty from db_mm.dtl_purchaseorder
	update #tempindentdetail set pendingpoqty = dt.poqty
	from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0)-isnull(writeoffquantity,0)) poqty
	from db_mm.dtl_purchaseorder group by itemid) dt where #tempindentdetail.itemid = dt.itemid 

	-- update last po qty from db_mm.dtl_purchaseorder
	update #tempindentdetail set lastpurchaseqty = dt.poqty
	from (select itemid, isnull(receivedquantity,0) poqty from db_mm.dtl_purchaseorder d
	where id = (select max(id) from db_mm.dtl_purchaseorder b where d.itemid=b.itemid 
	group by itemid)) dt where #tempindentdetail.itemid = dt.itemid 


	-- update pending indent qty from db_mm.db_mm.dtl_indent
	update #tempindentdetail set pendingindentqty = dt.qty 
	from (	select a.itemid,sum(isnull(a.quantityapproved,0)-isnull(a.quantitywoff,0)) qty from db_mm.dtl_indent a
	where a.indentid not in (select distinct(indentid)  from db_mm.dtl_purchaseorder where itemid = a.itemid)
	group by a.itemid) dt where #tempindentdetail.itemid = dt.itemid 
	
	select * from #tempindentdetail


	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.
	

GO
/****** Object:  StoredProcedure [db_mm].[pr_getindentdeptandindenter]    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,14-05-2018>
-- Description:	<Description,Get indenter and dept. data>
--[db_mm].[pr_getindentdeptandindenter] 1,1,2
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getindentdeptandindenter] 	
	@coid int,
	@boid int ,
	@fyid int
	
as
BEGIN
	SET NOCOUNT ON;
	
	Select distinct d.id, d.[deptname] name
	from [db_mm].[hdr_indent] h
	join [db_masters].[department] d on h.departmentid= d.id where h.coid=@coid and h.boid=@boid and h.fyid=@fyid 
	
	Select distinct u.userid id, u.username name
	from [db_mm].[hdr_indent] h
	join  [db_masters].[users] u on h.indentorid = u.userid where h.coid=@coid and h.boid=@boid and h.fyid=@fyid 
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getindentdetailforpassing]    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_mm].[pr_getindentdetailforpassing] 1,100,1,1,1,'indentnumber','asc','',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getindentdetailforpassing] 
	@PageNumber INT=0,
	@PageSize INT=0,
	@coid int = 1,
	@boid int = 1,
	@fyid int = 1,
	@sort nvarchar(100)='indentnumber',
	@sortorder nvarchar(100)='asc',
	@fromdate date=null,
	@todate date=null,
	@deptid int=null,
	@indenterid int=null,
	@search varchar=null
as
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select distinct id.[itemid],[indentnumber],h.indentid, d.[deptname],[indentdate],[itemname],b.name brandname,[itemcode],
	quantityrequired,quantityapproved,isnull(quantityrequired,0)-isnull(quantityapproved,0)-isnull(quantitywoff,0) pendingquantity, 
	im.[oldcode],u.username indenter,iu.uom,im.minlevel,im.maxlevel,isnull(rol,0) reorderlevel,im.leadtimesurface,
     ((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator=''+''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator=''-''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   im.id = itemid))stockinhand
	from [db_mm].[hdr_indent] h
	join [db_masters].[department] d on h.departmentid= d.id
	join  [db_masters].[users] u on h.indentorid = u.userid 
	join [db_mm].[dtl_indent] id on h.indentid=id.indentid
	join  [db_mm].[mst_item] im on id.itemid=im.id
	join  [db_mm].[mst_itemuom] iu on im.receivingunitid=iu.id
	join [db_mm].[mst_brand] b on b.id=id.brandid'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5)) +' and h.fyid = ' + cast(@fyid as varchar(5))
		set @sql += ' and  isnull(quantityrequired,0)-isnull(quantityapproved,0)+isnull(quantitywoff,0) > 0 '

		IF (@deptid != '')
		begin
			set @sql+= ' and h.departmentid = ' + cast(@deptid as varchar(6)) 
		end
		IF (@indenterid != '')
		begin
			set @sql+=  ' and h.indentorid in (select * from dbo.fngetchilduserids( '+ cast(@indenterid as varchar(5))+' )) ' 
				
		end
		IF (@fromdate != '')
		begin
			set @sql+=  ' and  convert(Date,h.indentdate) >= ''' + cast(@fromdate as varchar(20)) + ''''
		end
       IF (@todate != '')
		begin
			set @sql+=   ' and  convert(Date,h.indentdate) <= ''' + cast(@todate as varchar(20)) + ''''
		end
		 IF (@search != '')
		begin
			begin
						set @sql += ' and  im.itemname like ''' + cast(@search as varchar(50)) + '%''  or  im.itemcode like ''' + cast(@search as varchar(50)) + '%''  or  im.oldcode like ''' + cast(@search as varchar(50)) + '%'''
					end
		end
		set @sql +=' order by '  + cast(@sort as varchar(100)) + ' ' + @sortorder + ' ' 
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql = 'Select count(id.[itemid]) records
	from [db_mm].[hdr_indent] h
	join [db_masters].[department] d on h.departmentid= d.id
	join  [db_masters].[users] u on h.indentorid = u.userid 
	join [db_mm].[dtl_indent] id on h.indentid=id.indentid
	join  [db_mm].[mst_item] im on id.itemid=im.id
	join  [db_mm].[mst_itemuom] iu on im.receivingunitid=iu.id
	join [db_mm].[mst_brand] b on b.id=id.brandid'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5)) +' and h.fyid = ' + cast(@fyid as varchar(5))
		set @sql += ' and  isnull(quantityrequired,0)-isnull(quantityapproved,0)+isnull(quantitywoff,0) > 0 '

		IF (@deptid != '')
		begin
			set @sql+= ' and h.departmentid = ' + cast(@deptid as varchar(6)) 
		end
		IF (@indenterid != '')
		begin
			set @sql+=  ' and h.indentorid =in (select * from dbo.fngetchilduserids( '+ cast(@indenterid as varchar(5))+' )) ' 
				
		end
		IF (@fromdate != '')
		begin
			set @sql+=  ' and  convert(Date,h.indentdate) >= ''' + cast(@fromdate as varchar(20)) + ''''
		end
       IF (@todate != '')
		begin
			set @sql+=   ' and  convert(Date,h.indentdate) <= ''' + cast(@todate as varchar(20)) + ''''
		end
		 IF (@search != '')
		begin
			begin
						set @sql += ' and  im.itemname like ''' + cast(@search as varchar(50)) + '%''  or  im.itemcode like ''' + cast(@search as varchar(50)) + '%''  or  im.oldcode like ''' + cast(@search as varchar(50)) + '%'''
					end
		end
	--print @sql
	EXEC sp_executesql @SQL

				
	
	
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getindentitems]    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_mm].[pr_getindentitems] 1,1,1,'2019-04-01','2020-03-31',0,null,null,0
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getindentitems] 
    @coid int,
	@boid int,
	@userid int,
	@fromdate varchar(20),
	@todate varchar(20) ,
	@itemid int = 0,
	@batchno varchar(20) = null,
	@jobno varchar(20) = null,
	@indentno bigint = 0
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql = 'select dtl.itemid,itemname,itemcode, oldcode,isnull(mst.gstid,0) gstid,isnull(gst.description,'''') gstname,mst.hsncode,sum(isnull(dtl.quantityrequired,0)) quantityrequired,
	sum(isnull(dtl.quantityapproved,0)-isnull(list.qty,0)) quantityapproved
	from db_mm.dtl_indent dtl 
	join db_mm.hdr_indent hdr on dtl.indentid = hdr.indentid 
	join db_mm.mst_item mst on dtl.itemid = mst.id 
	left join db_mm.mst_gst gst on mst.gstid = gst.gstid 
	left join (select indentid,itemid, sum(isnull(itemquantity,0)) qty from db_mm.dtl_vendor_allocation_list list group by indentid,itemid) list on dtl.indentid = list.indentid and dtl.itemid = list.itemid '
	if (@batchno !=null) begin set @sql +=' left join db_production.hdr_batch hbatch on hdr.refid = hbatch.batchid and hdr.srctypeid = 5 
	and hbatch.batchno = coalesce(' + cast(@batchno as varchar(20)) + ',hbatch.batchno) ' end
	if (@jobno !=null) begin set @sql +='  left join db_production.hdr_jobcard hcard on hdr.refid = hcard.jobid and hdr.srctypeid = 3 
	and hcard.jobno = COALESCE(' + cast(@jobno as varchar(20)) + ',hcard.jobno)  ' end
	set @sql += ' where hdr.coid = ' + cast(@coid as VARCHAR(2)) + ' and hdr.boid = ' + cast(@boid as VARCHAR(2)) 
	if (@indentno >0) begin set @sql += ' and hdr.indentnumber = ' + cast(@indentno as varchar(20))  end
	if (@itemid>0) begin set @sql += ' and dtl.itemid = ' + cast(@itemid as varchar(20)) end
	set @sql += ' and (hdr.createdby = ' + cast(@userid as varchar(20)) + ' or hdr.indentorid = ' + cast(@userid as varchar(20)) + ')
	and hdr.indentdate >= ''' + @fromdate  + '''  and hdr.indentdate <=''' + @todate + ''' 
	and isnull(dtl.quantityapproved,0)>0 and isnull(dtl.quantityrequired,0) >0 and isnull(dtl.quantityapproved,0)<=isnull(dtl.quantityrequired,0) 
	and isnull(dtl.quantityapproved,0)-isnull(list.qty,0)>0  
	 group by dtl.itemid,itemname,itemcode,oldcode,mst.gstid,gst.description, mst.hsncode  order by itemid'
	
	
	print @sql

	EXEC sp_executesql @sql

	exec [db_mm].[pr_getitemindents] @coid,@boid,@userid,@itemid, @fromdate,@todate
	exec [db_mm].[pr_getitemsuppliers] @coid,@boid,@userid,@itemid
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getindentlist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [db_mm].[pr_getindentlist] 1,20,1,1,1,2,'p'
CREATE PROCEDURE [db_mm].[pr_getindentlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@userid int,
	@fyid int,
	@type varchar(1),
	@accesstoken  varchar(100)=null,
	@sort nvarchar(100)='indentnumber',
	@sortorder nvarchar(100)='desc',
   @search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	
	set @sql = 'Select distinct(h.[indentid]),[indentnumber],[indentdate],[indentorid],u.username,[isjobwork],u.[username],
	h.[departmentid],d.[deptname],[manualslipno],(select case when id.approvedby>0 then 0 else 1 end) canedit,
	''status'' = 
	 case when id.approvedby=0 or approvedby is null  then ''Pending For Approval''
	  when id.approvedby>0 and quantityordered is null then ''Approved''
	  when   (id.poid)>0 and id.approvedby>0  and quantityordered is  not null then ''Order Placed''  
	  when quantityordered<quantityapproved  then ''Partially Settled''
	  when quantityordered>=quantityapproved  then ''Fully Settled'' end 
	 from [db_mm].[hdr_indent] h
  	join [db_mm].[dtl_indent] id on h.indentid=id.indentid
	join  [db_mm].[mst_item] im on id.itemid=im.id
	join [db_masters].[department] d on h.departmentid= d.id
	join [db_masters].[users] u on h.indentorid = u.userid	
	left join  [db_mm].[mst_itemuom] iu on im.receivingunitid=iu.id
	left join [db_mm].[mst_brand] b on b.id=id.brandid'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		set @sql += ' and h.createdby in (select distinct(splitdata) from dbo.fngetchilduserids( '+ cast(@userid as varchar(5))+' ))'
		if(@search!='')
		begin
		 set @sql += ' and H.indentnumber = ' + cast(@search as varchar(5)) 
		end
		--print @sql
		--- @type='s' for passed indent (mohit 14-05-2019)
		if(@type='s')
		begin
		set @sql += ' and  isnull(quantityrequired,0)-isnull(quantityapproved,0)+isnull(quantitywoff,0) = 0 '
		 end
		 else  
		 begin
		set @sql += ' and  isnull(quantityrequired,0)-isnull(quantityapproved,0)+isnull(quantitywoff,0) > 0 '
		 end
		 print @sql
		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_mm].[pr_getindentor]    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_getindentor]1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getindentor] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getinwardnotedata]    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_mm].[pr_getinwardnotedata] 1,1,3
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getinwardnotedata] 
	@coid int,
	@boid int,
	@noteid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [noteno],[notedate],[notetype],[billno],[billdate],[partyacid],[purchaseacid],[inwardid],[drcrvoucherno],[amount],[coid],[boid],[remarks],[fyid]
	from db_mm.hdr_inwardnote h
	
	 where h.noteid = @noteid

	 select [noteid],[itemid],[adviceid],[rate],[quantity],[amount],[igstamount],[cgstamount],[sgstamount],[reference]
	 from  db_mm.dtl_inwardnote D
	   
	    where d.noteid = @noteid


	   ---get issuance batchwise
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getinwardnotelist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--exec [db_mm].[pr_getinwardnotelist] 1,20,1,1,'noteno','desc','',''
CREATE PROCEDURE [db_mm].[pr_getinwardnotelist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='noteno',
	@sortorder nvarchar(100)='desc',
    @search varchar(50)='',
    @searchtype varchar(25)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select noteid, s.name,[noteno],[notedate],[notetype],[billno],[billdate],[inwardid],[amount] from [db_mm].[hdr_inwardnote] h
	join db_masters.supplier s on h.[partyacid]=s.id'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.noteno = ' + cast(@search as varchar(5)) 
		end
		--- @type='s' for passed indent (mohit 14-05-2019)
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql ='Select distinct count(*)indentid from [db_mm].[hdr_inwardnote] h'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		EXEC sp_executesql @SQL		
	
	
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getissuancedata]    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_mm].[pr_getissuancedata] 1,1,42
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getissuancedata] 
	@coid int,
	@boid int,
	@issuanceid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [issuanceid],[issuanceno],isu.reqnid, isu.reqnno,isu.[createdon],c.name costcentre,s.name store,d.deptname,isu.batchno, 
	isu.[manualslipno],isu.deptid,isu.[costcentreid],s.id storeid,isu.batchexpirydate,isu.batchmfgdate,ISNULL([lotsize],0),
	itm.itemname productname,[collectedby]
	 from [db_mm].[hdr_issuance] isu
	left join [db_masters].[costcentre] c on isu.costcentreid =c.id
	LEFT join [db_masters].[department] d on isu.deptid = d.id
	left join [db_mm].[mst_store] s on s.id=isu.storeid
	left join [db_mm].[hdr_requisition] ih on isu.reqnid=ih.reqnid
	left join db_mm.mst_item itm on ih.productid=itm.id
    where isu.issuanceid = @issuanceid

	 select im.[itemcode],im.[oldcode],im.[itemname],id.itemid,id.brandid, b.[name] brandname,um.uom,[requestedquantity],
	 [issuedquantity] ,id.[remarks], 0 stockinhand from [db_mm].[dtl_issuance] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	 join [db_mm].[mst_item] im  on id.itemid= im.id
	 JOIN [db_mm].[mst_itemuom] um ON im.issuingunitid  = um.id
	 where id.issuanceid = @issuanceid

	   ---get issuance batchwise
	   select itemid,issuedquantity,brandid,arno,batchno,expirydate,mfgdate,storeid,assay,lod  from db_mm.issuancebatchwise
	   where
	   issuanceid=@issuanceid
	    
	
	 select im.[itemcode],im.[oldcode],im.[itemname],id.itemid,id.brandid,id.arno,id.batchno, b.[name] brandname,um.uom,[issuedquantity] 
	  from db_mm.issuancebatchwise id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	 join [db_mm].[mst_item] im  on id.itemid= im.id
	 JOIN [db_mm].[mst_itemuom] um ON im.issuingunitid  = um.id
	 where id.issuanceid = @issuanceid

    SELECT distinct (h.reqnid),h.[reqnno],h.reqndate [createdon],s.id [deptid],s.name deptname,h.reqndate,u.username from
    [db_mm].[hdr_requisition] h
	join [db_masters].[department] d on h.deptid=d.id 
    join db_mm.mst_store s on h.storeid = s.id
	join [db_mm].[dtl_requisition] dt on h.reqnid = dt.reqnid
	join [db_masters].[users] u on h.createdby=u.userid
	where  iscancelled is null
	group by dt.itemid,(h.reqnid),h.[reqnno],h.reqndate,s.id,s.name,h.reqndate,u.username
	having  (sum(isnull(dt.requestedquantity,0)-isnull(dt.issuedquantity,0)-isnull(dt.woffquantity,0))) > 0
	order by h.reqndate,s.name
	create table #tempcategorylist(
	id int,
	name	varchar(200),
	code	varchar(20),
	parentgroupid	int,
	categcode varchar(20),
	categname varchar(500),
	level int,
	lastitemcode	varchar(20),
	childcnt	int
	)
	insert into #tempcategorylist
	exec [db_masters].[pr_getitemcategorylist] @coid,1

	SELECT * FROM #tempcategorylist where parentgroupid=0

	SELECT * FROM  #tempcategorylist  WHERE parentgroupid > 0
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getissuancelist]    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_mm].[pr_getissuancelist] 1,10,1,1,'issuanceno','asc',14,2
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getissuancelist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='issuanceno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@storeid int =null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [issuanceid],[issuanceno] ,c.name costcentre,s.name store,h.[createdon], u.username,d.[deptname],h.[manualslipno],h.[batchno],
	[lotsize],m.itemname productname from [db_mm].[hdr_issuance] h
	left join [db_masters].[department] d on h.deptid= d.id
	  left join [db_masters].[users] u on h.createdby = u.userid
	left  join [db_masters].[costcentre] c on h.costcentreid=c.id 
	left  join [db_mm].[mst_store] s on h.storeid=s.id
	left join [db_mm].[hdr_requisition] reqn on h.[reqnid]=reqn.[reqnid]
	left join [db_mm].[mst_item] m on  reqn.productid=m.id  '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.issuanceno = ' + cast(@search as varchar(5)) 
		end
		if(@storeid!='')
		begin
		 set @sql += ' and H.storeid =  ' + cast(@storeid as varchar(2))
		end
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	--print @sql
	EXEC sp_executesql @SQL

	 select count(h.[issuanceid])records from [db_mm].[hdr_issuance] h
	 join [db_masters].[department] d on h.deptid= d.id
	join [db_masters].[users] u on h.createdby = u.userid 
				
	
	
	
END





GO
/****** Object:  StoredProcedure [db_mm].[pr_getissuereturndata]    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_mm].[pr_getissuereturndata]  1,1,8
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getissuereturndata] 
	@coid int,
	@boid int,
	@issuereturnid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [issuereturnid],[issuereturnno],[ih].[issuanceid],ih.[createdon],c.name costcentre,s.name store,d.deptname,[ih].[departmentid],[costcentreid],
	s.id storeid  from [db_mm].[hdr_issuereturn] ih
	left  join [db_masters].[costcentre] c on ih.costcentreid =c.id
	 left join [db_masters].[department] d on ih.departmentid = d.id
	 left join [db_mm].[mst_store] s on s.id=ih.storeid
	 where ih.[issuereturnid] = @issuereturnid

	 select im.[itemcode],im.[oldcode],im.[itemname],id.itemid,[id].[quantityreturned],[arno],
	[batch],id.returnreason from [db_mm].[dtl_issuereturn] id
	   join [db_mm].[mst_item] im  on id.itemid= im.id
	   where id.[issuereturnid] = @issuereturnid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getissuereturnlist]    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_mm].[pr_getissuereturnlist] 1,10,1,1,'1','asc',''
-- =============================================

CREATE PROCEDURE [db_mm].[pr_getissuereturnlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='issuereturnno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [issuereturnid],[issuereturnno] ,c.name costcentre,s.name store, u.username,d.[deptname],h.[remarks],h.createdon from [db_mm].[hdr_issuereturn] h
	 join [db_masters].[department] d on h.departmentid= d.id
	  join [db_masters].[users] u on h.createdby = u.userid
	  join [db_masters].[costcentre] c on h.costcentreid=c.id 
	  join [db_mm].[mst_store] s on h.storeid=s.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.issuereturnno = ' + 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

	 select count(h.[issuereturnid])records from [db_mm].[hdr_issuereturn] h
	 join [db_masters].[department] d on h.departmentid= d.id
	join [db_masters].[users] u on h.createdby = u.userid 
				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemcategorydata]    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_mm].[pr_getitemcategorydata]  1,1,247
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemcategorydata] 
	@coid int = 1,
	@boid int = 1,
	@id Int
AS
BEGIN
	SET NOCOUNT ON;
	
	select id,name,categorycode,isnull(parentid,0) parentid,isnull(isactive,'false') isactive, boid,coid,isnull(issaleitem,'false') issaleitem,
	isnull(ispurchaseitem,'false') ispurchaseitem from db_mm.mst_itemcategory where id = @id and coid=@coid and boid = @boid
	
	select m.id,categoryid,dimensionid,name from db_mm.dtl_categorywise_dimension_mapping c 
	join db_mm.mst_dimension m on c.dimensionid=m.id
	where categoryid=@id
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemcategorylist]    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,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getitemcategorylist] 1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemcategorylist] 
@coid int,
@userid int = null,
@categoryid int=null
AS
BEGIN
SET NOCOUNT ON;
IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
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_mm].[pr_getitemcategoryuserrights]    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_mm].[pr_getitemcategoryuserrights] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemcategoryuserrights] 
	@coid int,
	@boid int,
	@userid int,
	@categoryid int
AS
BEGIN
	SET NOCOUNT ON;
	----change by mohit (22-05-19) (in declare @selected bit =1, @deselected bit =0)
	declare @selected bit =1, @deselected bit =0
	select mst.id,mst.name, case when rights.id>0 then @selected else @deselected end selected 
	-- select mst.id,mst.name, case when rights.id>0 then 1 else 0 end selected     by mohit
	from db_mm.mst_itemcategory mst 
	left join db_mm.itemcategories_userrights rights on mst.id = rights.itemcategoryid and rights.userid = @userid and rights.coid = @coid and rights.boid = @boid 
	where mst.id in (select * from dbo.fngetchilditemcategoryids(@categoryid)) and mst.id <> @categoryid
	

end
	

GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemindents]    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_mm].[pr_getitemindents] 1,1,1,29
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemindents] 
    @coid int,
	@boid int,
	@userid int,
	@itemid int=0,
	@fromdate varchar(20),
	@todate varchar(20) 
AS
BEGIN
	SET NOCOUNT ON;

	select dtl.itemid, hdr.indentid,hdr.indentnumber,hdr.indentdate, dtl.quantityrequired,isnull(dtl.quantityapproved,0)-isnull(list.qty,0) quantityapproved,
	isnull(bt.batchno,1) batchno , isnull(job.jobno,1) jobno 
	from db_mm.dtl_indent dtl join db_mm.hdr_indent hdr on dtl.indentid= hdr.indentid 
	join db_mm.mst_item mst on dtl.itemid = mst.id 
	left join db_production.hdr_batch bt on hdr.refid = bt.batchid and hdr.srctypeid = 5 
	left join db_production.hdr_jobcard job on hdr.refid = job.jobid and hdr.srctypeid = 3 
	left join (select indentid,itemid, sum(isnull(itemquantity,0)) qty from db_mm.dtl_vendor_allocation_list list group by indentid,itemid) list on dtl.indentid = list.indentid and dtl.itemid = list.itemid  
	where dtl.itemid = case when @itemid > 0 then @itemid else dtl.itemid end and (hdr.createdby = @userid or hdr.indentorid = @userid) and hdr.coid = @coid and hdr.boid = @boid 
	and hdr.indentdate >= @fromdate  and hdr.indentdate <= @todate and isnull(dtl.quantityapproved,0)<=isnull(dtl.quantityrequired,0) 
	and isnull(dtl.quantityrequired,0)>0 and isnull(dtl.quantityapproved,0)>0 and isnull(dtl.quantityapproved,0)-isnull(list.qty,0)>0 order by dtl.itemid

	

	
	

	
	END



GO
/****** Object:  StoredProcedure [db_mm].[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_mm].[pr_getitemlist] 1,10,1,1,'itemname','asc','digital'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='ITEMNAME',
	@sortorder nvarchar(100)='asc',
	@search nvarchar(100)=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	-- get item's general information

	set @sql = 'SELECT im.[id],[itemcategoryid],[name] as itemcategoryname,[itemcode],[oldcode],[itemname],[itemalias],[billingdescription]
				,[itemspecification],[oldcode],[specialcode],[hsncode],[taxrate],[receivingunitid] ,[UOM],[issuingunitid] ,[UOM],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],im.[coid],im.[boid],im.[isactive],im.[createdby]				
	from [db_mm].[mst_item]  im 
				join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id
				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))
				if (@search !=null or @search !='')
				begin
				set @sql += ' and  im.itemname like ''' + cast(@search as varchar(50)) + '%''  or  im.itemcode 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(6))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(6)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @search
	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  where im.coid=@coid and im.boid=@boid 
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemlistforbombasedrequisition]    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] 1,10,1,1,'itemname','asc'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemlistforbombasedrequisition] 
	@PageNumber INT,
	@PageSize INT,
	@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],[hsncode],[taxrate],[receivingunitid] ,[UOM],[issuingunitid] ,[UOM],[unitconversionfactor],[itemimage],[itemdrawing],[openingstock]
				,[openingvalue],[landedrate],[lastpurchaserate],[eoq],[moq],[itemclassabc],[minlevel],[maxlevel]
				,[rol],im.[coid],im.[boid],im.[isactive],im.[createdby],bd.[name],bd.id brandid
				from [db_mm].[mst_item]  im 
				join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id
				join  [db_mm].[mst_itemcategory] ic on im.itemcategoryid= ic.id
				left JOIN [db_mm].[mst_brand] bd ON d.brandid=bd.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(4))  + ' 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
 join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id 
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemlistforbomindent]    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_mm].[pr_getitemlistforbomindent]1,1,27,10,1,'R'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemlistforbomindent] 
	@coid int = 1,
	@boid int = 1,
	@bomid int,
	@lotsize decimal(10,3),
	@fyid int=null,
	@type char(1) = null
	
AS
BEGIN
	SET NOCOUNT ON;

	declare @sql nvarchar(max)
	 --SELECT  [itemcode],[itemname],bom.quantity*@lotsize indentqty,
		--		[receivingunitid] ,[UOM],[issuingunitid] ,[UOM],bom.brandid
		--       from  [db_mm].[dtl_bom] bom 
		--		join [db_mm].[mst_item] im on im.id=bom.cid
		--		left join [db_mm].[mst_itemuom] uom on im.receivingunitid=uom.id
		--		where bom.bomid=@bomid

 
		  if lower(@type)='R'
		begin
	set @sql = 'SELECT (b.productid),(D.quantity) + wastagequantity requestedquantity,  im.itemname, 
			im.itemcode,D.cid,im.issuingunitid, uom.uom, bd.[name] brandname,bd.id brandid, d.cid itemid, b.batchsize,
			 isnull(sum(isnull(stk.itemquantity,0)*cast((stk.trnoperator+1) as int)),0) stock ,im.oldcode,im.gstid,g.igst,g.cgst,g.sgst, ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0)) from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty
			FROM [db_mm].[hdr_bom] b 
			JOIN [db_mm].[dtl_bom] d ON b.bomid=d.bomid
			left join db_mm.item_stk_trn stk on d.cid = stk.itemid and stk.coid = ' + cast(@coid as varchar(5)) + ' and stk.boid = ' + cast(@boid as varchar(5)) + ' and stk.fyid=coalesce(' + cast(@coid as varchar(5)) + ',stk.fyid) 
			JOIN [db_mm].[mst_item] im on d.cid=im.id
			left JOIN [db_mm].[mst_brand] bd ON d.brandid=bd.id
			 left join [db_mm].[mst_itemuom] uom on d.unit=uom.id
			 left join db_mm.mst_gst g on im.gstid=g.gstid
	WHERE  b.bomid=' + cast(@bomid as varchar(5)) + '		
			group by b.productid,D.quantity,  im.itemname, im.itemcode,im.oldcode,D.cid,im.issuingunitid, uom.uom, bd.[name],bd.id, d.cid , b.batchsize,d.wastagequantity,im.gstid,g.igst,g.cgst,g.sgst,im.id '
	end 
	else 
	begin 
	set @sql = 'SELECT (b.productid),(D.quantity) + wastagequantity requestedquantity,  im.itemname, 
			im.itemcode,D.cid,im.issuingunitid, uom.uom, bd.[name] brandname,bd.id brandid, d.cid itemid, b.batchsize,
			 isnull(sum(isnull(stk.itemquantity,0)*cast((stk.trnoperator+1) as int)),0) stock ,im.oldcode,im.gstid,g.igst,g.cgst,g.sgst, ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0)) from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty
			FROM [db_mm].[hdr_pbom] b 
			JOIN [db_mm].[dtl_pbom] d ON b.pbomid=d.pbomid
			left join db_mm.item_stk_trn stk on d.cid = stk.itemid and stk.coid = ' + cast(@coid as varchar(5)) + ' and stk.boid = ' + cast(@boid as varchar(5)) + ' and stk.fyid=coalesce(' + cast(@coid as varchar(5)) + ',stk.fyid) 
			JOIN [db_mm].[mst_item] im on d.cid=im.id
			left JOIN [db_mm].[mst_brand] bd ON d.brandid=bd.id
			 left join [db_mm].[mst_itemuom] uom on d.unit=uom.id
			  left join db_mm.mst_gst g on im.gstid=g.gstid
	WHERE  b.pbomid=' + cast(@bomid as varchar(5)) + '	
			group by b.productid,D.quantity,  im.itemname, im.itemcode,im.oldcode,D.cid,im.issuingunitid, uom.uom, bd.[name],bd.id, d.cid , b.batchsize,d.wastagequantity ,im.gstid,g.igst,g.cgst,g.sgst,im.id'
		
			end 
				EXEC sp_executesql @SQL
				print @sql
	
END





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

--EXEC [db_mm].[pr_getitemlistforgrnconfirmation]1,1,41
CREATE PROCEDURE [db_mm].[pr_getitemlistforgrnconfirmation] 
	@coid int,
	@boid int,
	@grnid int

AS
BEGIN
	SET NOCOUNT ON;
 select  itm.id itemid,bch.id,dtl.orderid,itm.itemname,isnull(bch.quantity,dtl.quantityreceived) quantityreceived,bch.batchno,bch.expirydate,bch.mfgdate,isnull(bch.sampleqty,0) sampleqty,
isnull(bch.brandid,0) brandid,hdr.grnnumber,uom.uom,itm.oldcode, itm.itemcode,bch.sampleqty,bch.arnumber,bch.expirydate,bch.qcdate,bch.nextqcdate,bch.assay,bch.lod,isnull(bch.quantityrejected,0) quantityrejected
from [db_mm].[hdr_grn] hdr
inner  join [db_mm].[dtl_grn] dtl on hdr.grnid=dtl.grnid
inner join [db_mm].[mst_item] itm on dtl.itemid = itm.id
left join [db_mm].[grnbatchwise] bch on dtl.grnid= bch.grnid and dtl.itemid=bch.itemid  and dtl.brandid=bch.brandid
inner join [db_masters].[supplier] sup on hdr.suplid = sup.id
left join [db_mm].[mst_brand] brnd on dtl.brandid = brnd.id
left join [db_mm].mst_itemuom uom on itm.receivingunitid=uom.id
where hdr.boid=@boid and  hdr.grnid=@grnid and bch.confirmedby is null

--select id,rejectionreason from [db_mm].[mst_rejectionreason] 

end



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

-- EXEC [db_mm].[pr_getitemlistforiqc]1,1,0,'Y',0,'','','','','nickle','itemname'
CREATE PROCEDURE [db_mm].[pr_getitemlistforiqc] 
	@coid int,
	@boid int,
	@grnid int,
	@forqcreleased char(1),
	@itemid int = 0,
	@sort nvarchar(100)='grnnumber',
	@sortorder nvarchar(100)='desc',
	@fromdate date='',
	@todate date='',
	@search varchar(25)='',
	@searchtype varchar(25)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
 set @sql = 'select  itm.id itemid,bch.id,dtl.orderid,itm.itemname,isnull(bch.quantity,dtl.quantityreceived) quantityreceived,bch.batchno,bch.expirydate,bch.mfgdate,isnull(bch.sampleqty,0) sampleqty,
isnull(bch.brandid,0) brandid,hdr.grnnumber,uom.uom,itm.oldcode, itm.itemcode,bch.arnumber,bch.expirydate,bch.nextqcdate,bch.assay,bch.lod,
bch.quantityrejected,(bch.quantity-bch.sampleqty) qtyapproved, ''QC/''+ cast(bch.arnumber as varchar(5))  +'''' [releaseorderno],bch.qcdate
from [db_mm].[hdr_grn] hdr
inner  join [db_mm].[dtl_grn] dtl on hdr.grnid=dtl.grnid
inner join [db_mm].[mst_item] itm on dtl.itemid = itm.id
left join [db_mm].[grnbatchwise] bch on dtl.grnid= bch.grnid and dtl.itemid=bch.itemid  and dtl.brandid=bch.brandid
inner join [db_masters].[supplier] sup on hdr.suplid = sup.id
left join [db_mm].[mst_brand] brnd on dtl.brandid = brnd.id
left join [db_mm].mst_itemuom uom on itm.receivingunitid=uom.id
where hdr.boid= ' + cast(@coid as varchar(5)) + ''
if(@grnid>0)
		begin 
		 set @sql +=  ' and hdr.grnid = ' + cast(@grnid as varchar(15))  +  ' '
		end 
		if(@itemid>0)
		begin 
		 set @sql +=  ' and bch.id = ' + cast(@itemid as varchar(5))  +  ' '
		end 
if(@forqcreleased='Y')
		begin 
		 set @sql +=  ' and bch.qcby is not  null '
		end 
		else
		begin
		set @sql +=  ' and bch.qcby is null '
		end
		if(@fromdate!='' )
		begin 
		set @sql +=  ' and bch.qcdate >= ''' + cast(@fromdate as varchar(10)) + '''
                 AND bch.qcdate <=  ''' + cast(@todate as varchar(10)) + ''''
				 END
				 if (@search !=null or @search !='')

				begin

				if (@searchtype = 'itemname')

					begin

						set @sql += ' and   itm.itemname like  ''' + cast(@search as varchar(50)) + '%'''

					end

				else if (@searchtype = 'arnumber')

					begin

						set @sql += ' and  bch.arnumber like ''' + cast(@search as varchar(50)) + '%'''

					end

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

select ROWCOUNT_BIG() as records
print @sql
		   



select  1 id, 'NOT AS PER  QC PARAMETERS'rejectionreason 
union all select 2 id,'DIMENSIONS NOT AS PER DRAWING'rejectionreason 
union all select 3 id,'SHEET/TUBE THICKNESS NOT PROPER'rejectionreason 
union all select 4 id,'INNER DIA NOT OK'rejectionreason 
union all select 5 id,'BENDING NOT OK'rejectionreason 
union all select 6 id,'BREAKEGE/ DAMAGE FOUND'rejectionreason 
union all select 7 id,'HARDNESS NOT PROPER'rejectionreason 
end



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemlistplan]    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_mm].[pr_getitemlistplan] 1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemlistplan]
	@coid int = 1,
	@boid int = 1

AS
BEGIN
	SET NOCOUNT ON;
	
	
	SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid
	 from [db_mm].[hdr_bom] b
	join  [db_mm].[mst_item] im on b.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemlistpo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 ---[db_mm].[pr_getitemlistpo]1,1,'',''
CREATE PROCEDURE [db_mm].[pr_getitemlistpo]
	@coid int = 1,
	@boid int = 1,
	@search nvarchar(100)=null,
	@searchtype nvarchar(20)=''

AS
BEGIN
	SET NOCOUNT ON;
	
	
	--Select [indentnumber],ih.[indentid],im.gstid,g.igst,g.cgst,g.sgst, (id.[itemid]), [itemname],im.taxrate,im.hsncode,[itemcode],b.id brandid,b.name brandname,u.id unitid,u.uom unit,
	--(isnull([quantityapproved],0)-isnull([quantitywoff],0)-isnull(iva.[itemquantity],0)) qtyapproved 
	-- from [db_mm].[dtl_indent] id 
	--join  [db_mm].[mst_item] im on im.id=id.itemid
	--join [db_mm].[hdr_indent] ih on id.indentid = ih.indentid
 --   join [db_mm].[mst_brand] b on b.id=id.brandid
	--join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	--left join db_mm.mst_gst g on im.gstid=g.gstid
	--left join [db_mm].[indent_vendor_allocation] iva on id.indentid = iva.indentid and id.itemid = iva.itemid
	--where (isnull([quantityapproved],0)-isnull([quantitywoff],0)-isnull(iva.[itemquantity],0)) > 0

	declare @sql nvarchar(max);
	set @sql ='Select [indentnumber],ih.[indentid],im.gstid,g.igst,g.cgst,g.sgst, (id.[itemid]), [itemname], g.igst taxrate,im.hsncode,[itemcode],[oldcode],b.id brandid,b.name brandname,u.id unitid,u.uom unit,
	isnull([quantityapproved],0)-(isnull([quantityordered],0)-isnull([quantitywoff],0)) qtyapproved 
	 from [db_mm].[dtl_indent] id 
	join  [db_mm].[mst_item] im on im.id=id.itemid
	join [db_mm].[hdr_indent] ih on id.indentid = ih.indentid
    join [db_mm].[mst_brand] b on b.id=id.brandid
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	left join db_mm.mst_gst g on im.gstid=g.gstid
	where isnull([quantityapproved],0)-(isnull([quantityordered],0)-isnull([quantitywoff],0))>0' 
	--print @sql
	if (@search !=null or @search !='')
				begin
				if (@searchtype = null or @searchtype ='')
					begin
						set @sql += ' and  im.itemname like ''' + cast(@search as varchar(50)) + '%''  or  im.itemcode like ''' + cast(@search as varchar(50)) + '%'''
					end
				else if (@searchtype = 'name')
					begin
						set @sql += ' and  im.itemname like ''' + cast(@search as varchar(50)) + '%'''
					end
				else if (@searchtype = 'oldcode')
					begin
						set @sql += ' and  im.oldcode like ''' + cast(@search as varchar(50)) + '%'''
					end
				else if (@searchtype = 'itemcode')
					begin
						set @sql += ' and  im.itemcode like ''' + cast(@search as varchar(50)) + '%'''
					end					
				end
				EXEC sp_executesql @SQL
    END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemsforbombasereqn]    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_mm].[pr_getitemsforbombasereqn] 19,1,10
-- =============================================
--ALTER PROCEDURE [db_mm].[pr_getitemsforbombasereqn] 
--	@productid INT,
--	@bomid INT,
--	@lotsize int,
--	@coid int,
--	@boid int
	
--AS
--BEGIN
--SET NOCOUNT ON;
--SELECT (b.productid),(D.quantity)* @lotsize requestedquantity,im.itemname,D.cid FROM [db_mm].[hdr_bom]b 
--JOIN [db_mm].[dtl_bom] d ON b.bomid=d.bomid
--JOIN [db_mm].[mst_item] im on d.cid=im.id
--left JOIN [db_mm].[mst_brand] bd ON d.brandid=bd.id
--WHERE b.productid=@productid AND b.bomid=@bomid
	
--END


CREATE PROCEDURE [db_mm].[pr_getitemsforbombasereqn] 
	
	@bomid INT,
	@lotsize int,
	@coid int,
	@boid int
	
AS
BEGIN
SET NOCOUNT ON;
SELECT (b.productid),(D.quantity)* @lotsize requestedquantity,  im.itemname, 
		im.itemcode,D.cid,im.issuingunitid, uom.uom, bd.[name],bd.id brandid, d.cid itemid  FROM [db_mm].[hdr_bom]b 
JOIN [db_mm].[dtl_bom] d ON b.bomid=d.bomid
JOIN [db_mm].[mst_item] im on d.cid=im.id
left JOIN [db_mm].[mst_brand] bd ON d.brandid=bd.id
 left join [db_mm].[mst_itemuom]uom on im.issuingunitid=uom.id
WHERE  b.bomid=@bomid
	
END


 

GO
/****** Object:  StoredProcedure [db_mm].[pr_getitemsuppliers]    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_mm].[pr_getitemsuppliers]  1,1,1,29
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getitemsuppliers] 
    @coid int,
	@boid int,
	@userid int,
	@itemid int=0
AS
BEGIN
	SET NOCOUNT ON;

	select grndate ldate,dtl.grnid grnid,grnnumber,isnull(hdr.suplid,0) suplid,isnull(suplname,'') supplier,  'Address: ' + isnull(supladdress1,'') +',' + isnull(suplcity,'') supplieraddress, 
	isnull(smast.gsTin,'') gsTin,
	dtl.itemid,itemname,itemcode,mst.oldcode, 
	sum(isnull(quantityreceived,0)) quanityreceived,sum(isnull(quantityrejected,0)) quantityrejected, itemrate,dtl.id from db_mm.dtl_grn dtl
	join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid
	join (select dtl.itemid,suplid,max(hdr.grnid) grnid from db_mm.hdr_grn hdr 
	join db_mm.dtl_grn dtl on hdr.grnid = dtl.grnid group by dtl.itemid,hdr.suplid) as a
	on hdr.grnid = a.grnid and dtl.grnid = a.grnid and dtl.itemid = a.itemid 
	join (select itemid,grnid,max(id) id from db_mm.dtl_grn group by itemid,grnid) b 
	on dtl.itemid = b.itemid and dtl.grnid = b.grnid and dtl.id = b.id
	join db_mm.mst_item mst on dtl.itemid = mst.id
	join db_masters.supplier smast on hdr.suplid = smast.id
	where dtl.itemid = case when @itemid>0 then @itemid else dtl.itemid end and hdr.coid=@coid and hdr.boid = @boid
	group by grndate,dtl.grnid,grnnumber,hdr.suplid,suplname,supladdress1,suplcity,dtl.itemid,itemname,itemcode,mst.oldcode,itemrate ,smast.gsTin,dtl.id
	UNION
	select lastpurchasedate ldate,lastgrnid grnid,hdr.grnnumber,isnull(dtl.suplid,0) suplid, isnull(sup.name,'') supplier, 'Address: ' + isnull(sup.address1,'') +',' + cast(isnull(sup.city,'') as varchar(50)) supplieraddress,isnull(sup.gsTin,'') gsTin,
	dtl.itemid,itemname,itemcode,sup.oldcode,
	0 quanityreceived,0 quantityrejected, coalesce(dtl.lastpurchaserate,dtl.suplitemrate) itemrate , dtl.id
	from db_mm.supplier_items dtl left join db_mm.hdr_grn hdr on dtl.lastgrnid = hdr.grnid
	join db_masters.supplier sup on dtl.suplid = sup.id
	join db_mm.mst_item mst on dtl.itemid = mst.id
	where dtl.itemid = case when @itemid>0 then @itemid else dtl.itemid end and dtl.coid=@coid 
	
	
	END


	--select * from db_mm.dtl_grn where id in ( 1089,1073)
GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastdestructionno]    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_mm].[pr_getlastdestructionno] 1,1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getlastdestructionno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select ISNULL(MAX(destructionno), 0) as destructionnono from [db_mm].[hdr_destruction] where coid=@coid and boid=@boid and fyid=@fyid
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastdprno]    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_getdprmaxno] 1,1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getlastdprno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(dprnumber) as dprnumber from [db_mm].[hdr_dpr] where coid=@coid and boid=@boid and fyid=@fyid
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastgrnno]    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_mm].[pr_getlastgrnno]  1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlastgrnno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(grnnumber) as grnnumber from [db_mm].[hdr_grn] where coid=@coid and boid=@boid 
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastindentno]    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_mm].[pr_getlastindentno] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlastindentno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(isnull(indentnumber,0)) as indentnumber from [db_mm].[hdr_indent] where coid=@coid and boid=@boid
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastissuanceno]    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_mm].[pr_getlastissuanceno] 1,1,1  
-- =============================================  

CREATE PROCEDURE [db_mm].[pr_getlastissuanceno]   
 @coid int,  
 @boid int,  
 @fyid int  
AS  
BEGIN  
 SET NOCOUNT ON;  
   
   
 Select max(issuanceno) as reqnno from [db_mm].[hdr_issuance] where coid=@coid and boid=@boid and fyid=@fyid  
   
 SELECT distinct (h.reqnid),h.[reqnno],h.reqndate [createdon],s.id [deptid],s.name deptname,h.reqndate,u.username  
 from [db_mm].[hdr_requisition] h  
 join [db_masters].[department] d on h.deptid=d.id   
    join db_mm.mst_store s on h.storeid = s.id  
 join [db_mm].[dtl_requisition] dt on h.reqnid = dt.reqnid  
 join [db_masters].[users] u on h.createdby=u.userid  
 where  iscancelled is null  
 group by dt.itemid,(h.reqnid),h.[reqnno],h.reqndate,s.id,s.name,h.reqndate,u.username  
 having  (sum(isnull(dt.requestedquantity,0)-isnull(dt.issuedquantity,0)-isnull(dt.woffquantity,0))) > 0  
 create table #tempcategorylist(  
 id int,  
 name varchar(200),  
 code varchar(20),  
 parentgroupid int,  
 categcode varchar(20),  
 categname varchar(500),  
 level int,  
 lastitemcode varchar(20),  
 childcnt int  
 )  
 insert into #tempcategorylist  
 exec [db_masters].[pr_getitemcategorylist] @coid,1  
  
 SELECT * FROM #tempcategorylist where parentgroupid=0  
  
 SELECT * FROM  #tempcategorylist  WHERE parentgroupid > 0  
 end  
 ---- suplid check yet to be done.  
 ------- whether to use left join on brand or make it mandatory in ui.  
  
GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastissuereturnno]    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_getindentmaxno] 1,1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getlastissuereturnno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(issuereturnno) as issuereturnno from [db_mm].[hdr_issuereturn] where coid=@coid and boid=@boid and fyid=@fyid
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastnrgpno]    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_mm].[pr_getlastnrgpno]1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlastnrgpno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(nrgpno) as nrgpno from [db_mm].[hdr_nrgp] where coid=@coid and boid=@boid 
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastpono]    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_mm].[pr_getlastpono]1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlastpono] 
    @coid int,
	@boid int,
	@fyid int
AS
BEGIN
	Select max(ordernumber) as ordernumber from [db_mm].[hdr_purchaseorder] where coid=@coid and boid=@boid 
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getlastreqnno]    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_getindentmaxno] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlastreqnno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select max(reqnno) as reqnno from [db_mm].[hdr_requisition] where coid=@coid and boid=@boid and fyid=@fyid
	
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getlaststktransferno]    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_mm].[pr_getlaststktransferno] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getlaststktransferno] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select ISNULL(MAX(stktransferno), 0) as stktransferno from [db_mm].[hdr_stktransfer] where coid=@coid and boid=@boid and fyid=@fyid
	
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getletterbanklist]    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_mm].[pr_getletterbanklist]2,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getletterbanklist] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	 select  db.id, dcat.category,dept.deptname,sub.subject,tit.title,db.createdon 
	 ,db.documenttext
	 from [db_general].document_bank  db
     left join db_masters.department dept on db.deptid= dept.id 
	 left join db_masters.document_titles tit on tit.id= db.title
	 left join db_masters.document_subjects sub on sub.id = db.subject
	 left join db_masters.document_category dcat on dcat.id=db.documenttype
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getnrgpdata]    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_mm].[pr_getnrgpdata]  1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getnrgpdata] 
	@coid int,
	@boid int,
	@nrgpid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	SELECT [nrgpid],[nrgpno],[partyid],c.name partyname,cn.countryname country,ct.cityname city,st.statename state,c.gstin,[outtime],[vehiclename],[vehicleno],[deptid],[storeid],[deliveryaddress],p.createdon,p.remarks,p.transportid from [db_mm].[hdr_nrgp] p
	join db_masters.customer c on p.partyid=c.id
	left join db_masters.city ct on c.city=ct.id
	left join db_masters.country cn on c.country=cn.id
	left join [db_masters].[statemaster] st on c.state=st.id
   WHERE p.nrgpid=@nrgpid


	 SELECT [itemid],[quantity],[amount],[itemuom],[rate],[brandid], im.itemname,im.itemcode,im.oldcode,im.itemdescription from [db_mm].[dtl_nrgp] p
	 JOIN [db_mm].[mst_item] im ON P.itemid=im.id
    where P.nrgpid = @nrgpid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getnrgplist]    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_mm].[pr_getnrgplist] 1,10,1,1,'nrgpid','desc',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getnrgplist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='nrgpid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select [nrgpid],[nrgpno],[name],h.[createdon],u.username,deptname from [db_mm].[hdr_nrgp] h
	left join [db_masters].[users] u on h.createdby = u.userid
	left join  [db_masters].[department] d on h.deptid=d.id
	join [db_masters].[customer] c on h.partyid=c.id'
	 
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.nrgpno = ' + 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

	 select count(h.[nrgpid])records from [db_mm].[hdr_nrgp] h
    
 
				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getpaymentterms]    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_companybranches]2
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getpaymentterms]
@coid int,
@boid INT,
@suplid int
AS
BEGIN
DECLARE @orderid int
	SET NOCOUNT ON;
	SET @orderid = (SELECT MAX(orderid) FROM [db_mm].[hdr_purchaseorder] WHERE suplid=@suplid)
	IF (@orderid) IS NOT NULL
	BEGIN
SELECT pt.id,name FROM [db_mm].[mst_paymentterms] pt
JOIN [db_mm].[purchase_paymentterms]pty ON pt.id=pty.paymenttermid
WHERE pty.orderid=@orderid
END 
ELSE
SELECT id,name FROM [db_mm].[mst_paymentterms] where coid= cast(@coid as varchar(2)) and boid=cast(@boid as varchar(2))
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getpendingreqn]    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_mm].[pr_getpendingreqn] 1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getpendingreqn] 
	@coid int = 1,
	@boid int = 1
	

AS
BEGIN
	SET NOCOUNT ON;
	 
	SELECT distinct (h.reqnid),h.[reqnno],h.reqndate [createdon],s.id [deptid],s.name deptname,h.reqndate,u.username from [db_mm].[hdr_requisition] h
	join [db_masters].[department] d on h.deptid=d.id 
    join db_mm.mst_store s on h.storeid = s.id
	join [db_mm].[dtl_requisition] dt on h.reqnid = dt.reqnid
	join [db_masters].[users] u on h.createdby=u.userid
	where  iscancelled is null
	group by dt.itemid,(h.reqnid),h.[reqnno],h.reqndate,s.id,s.name,h.reqndate,u.username
	having  (sum(isnull(dt.requestedquantity,0)-isnull(dt.issuedquantity,0)-isnull(dt.woffquantity,0))) > 0
	order by h.reqndate,s.name

	END

	





GO
/****** Object:  StoredProcedure [db_mm].[pr_getplandata]    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_mm].[pr_getplandata] 1,1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getplandata] 
	@coid int,
	@boid int,
	@planid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	SELECT [planid],[planno],[plandate] from [db_mm].[hdr_plan] p
   WHERE p.planid=@planid

	 SELECT [productid],[batchid],isnull([bomid],0) bomid, im.itemname,im.itemcode,im.oldcode,im.itemdescription, 
	 [orderquantity],[samplequantity],[inventoryquantity],[totalquantity],uom.uom from [db_mm].[dtl_plan] p
	 JOIN [db_mm].[mst_item] im ON P.productid=im.id
	 join [db_mm].[mst_itemuom] uom on im.issuingunitid = uom.id
    where P.planid = @planid
end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getplanlist]    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_mm].[pr_getplanlist] 1,10,1,1,'planid','desc',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getplanlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='planid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select [planid],[planno],h.[createdby],[plandate],h.[confirmedby],[remarks],u.username from [db_mm].[hdr_plan] h
	join [db_masters].[users] u on h.createdby = u.userid '
	 
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.planno = ' + 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

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



GO
/****** Object:  StoredProcedure [db_mm].[pr_getpodata]    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_mm].[pr_getpodata] 1,1,5174
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getpodata] 
	@coid int,
	@boid int,
	@orderid int
AS
BEGIN
	SET NOCOUNT ON;
	Select [ordernumber],[orderdate],[suplname],[supladdress1],[supladdress2],[suplcity],[supltaxregistrationnumber], ih.suplid, ih.suplstate,
		 ih.suplpincode, ih.suplcontactperson,ih.quotationref, billtoid, ih.shiptoid,(b.name+' '+isnull(b.address1,'')) billtoname	
		 ,c.name+' '+c.address1 shiptoname ,m.countryname as country
		 ,db_general.NumberToWords(ih.poamount+ih.potaxamount,'') amountinword,(ih.poamount+ih.potaxamount) as poamount,ih.costcentreid, ih.ordertypeid ,potype.potype as ordertype
	from [db_mm].[hdr_purchaseorder] ih  left JOIN
    db_masters.supplier c  on ih.shiptoid=c.id  left JOIN
      db_masters.supplier b on ih.billtoid=b.id left JOIN
      db_masters.supplier a on ih.suplid=a.id left JOIN
      db_masters.country m on a.country=m.id left join 
	  db_mm.mst_potype potype on ih.ordertypeid = potype.id
	---- db_general.company_ branches a  on ih.shiptoid=a.boid inner join 
	 --  db_general.company_branches b  on ih.billtoid=b.boid
	 --  db_accounts.accountHeads a  on ih.shiptoid=a.id inner join 
	 --  db_accounts.accountHeads b  on ih.billtoid=b.id
	where ih.orderid = @orderid
	 select [itemcode],[oldcode],im.[itemname],id.itemrate,id.itemuom,id.netrate,id.orderedquantity,id.[remarks], g.hsncode as hsn,iif(id.igstamount>0, g.igst,0) as igst,
	       iif(id.cgstamount>0, g.cgst,0) as cgst, iif(id.sgstamount>0, g.sgst,0) as sgst, id.igstamount, id.sgstamount, id.cgstamount, id.selectedbrandid, 
		   id.itemdiscount, id.netrate*id.orderedquantity as netamt, ( id.netrate*id.orderedquantity)+id.igstamount+id.sgstamount+id.cgstamount total_amt,
		   b.name as brandname, id.brandid, sb.name as selectedbrandname, id.selectedbrandid, row_number() over(order by id.id asc) as id, id.itemid,
		   id.gstid,id.itemrate*id.orderedquantity as  basicamount,id.discpercent discount1
	 from [db_mm].[dtl_purchaseorder] 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_gst] g on id.gstid=g.gstid
	   left join [db_mm].[mst_brand] b on id.brandid=b.id
	   left join [db_mm].[mst_brand] sb on id.selectedbrandid=sb.id
	   where id.orderid = @orderid	  
	  select termsandconditionsid id,termsandcondition name from [db_mm].[purchase_termsandconditions]
	  where orderid=@orderid	  
	  select paymenttermid id,paymentterm  name from [db_mm].[purchase_paymentterms]
	  where orderid=@orderid
	  select d.itemid, im.itemcode,im.itemname, d.requiredqty as orderedquantity, d.deliverydate as date, row_number() over(order by d.id asc) as id, u.uom as itemuom
	  from [db_mm].[purchase_deliveryschedule] d
	  join [db_mm].[mst_item] im  on im.id= d.itemid
	  left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	   where d.orderid = @orderid
	   -- get ship to bill to branches
	SELECT unitname,boid,[address1],[address2], [city],[state], [country],[pin],[taxationno] FROM [db_general].[company_branches] b where coid= cast(@coid as varchar(2))
	----get list
	--get supplier category list
	select id, categoryname from db_masters.supplier_category 	where coid= @coid and boid=@boid 
		-- get item brands
	select id ,name  from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid
	select gstid,description,hsncode,igst,cgst,sgst from db_mm.mst_gst where  coid= @coid and boid=@boid
	select [remarks],[date],[contactperson],[contactphone],[settled] from db_mm.purchase_followup where orderid=@orderid
	 Select id, potype, potypedesc from db_mm.mst_potype  where  coid= @coid and boid=@boid
	end
	 Select id, potype, potypedesc from db_mm.mst_potype

	---- suplid check yet to be done.
	---- whether to use left join on brand or make it mandatory in ui.

GO
/****** Object:  StoredProcedure [db_mm].[pr_getpolist]    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_mm].[pr_getpolist] 1,1000,1,1,'ordernumber','asc','','','','','','','',0



CREATE PROCEDURE [db_mm].[pr_getpolist] 

	@PageNumber INT,

	@PageSize INT,

	@coid int = 1,

	@boid int = 1,

	@sort nvarchar(100)='ordernumber',

	@sortorder nvarchar(100)='desc',

	@search varchar(50)='',

	@searchtype nvarchar(20)='' ,

	@fromdate date=null,

	@todate date=null,

	@deptid int=null,

	@suplid bigint=null,

	@preparedby int=null,

	@isjobwork int = null

AS

BEGIN

	SET NOCOUNT ON;

	declare @sql nvarchar(max);

	

	set @sql = 'Select distinct(h.orderid),[ordernumber],[orderdate],h.[createdby],u.username,[suplname],isnull(t.potypedesc,''Purchase'') potypedesc,

	isnull([poamount],0) + isnull([potaxamount],0) poamount,case when (select distinct(orderid) from db_mm.dtl_grn where orderid=h.orderid)>0 then 0 else 1 end canedit,
	''status'' = 
	 case when h.approvedby=0 or approvedby is null  then ''Pending For Approval''
	  when h.approvedby>0 and  dt.orderedquantity is null then ''Approved''
	  when   h.approvedby>0  and dt.orderedquantity is  not null and isnull(dt.receivedquantity,0)=0   and dt.atrectquantity is  null then ''Order Placed''  
	  when   h.approvedby>0  and dt.orderedquantity is  not null and (SELECT sum((dt.orderedquantity)-(dt.atrectquantity)) FROM [db_mm].[dtl_purchaseorder] DT  WHERE DT.ORDERID=H.ORDERID GROUP BY ORDERID ) >0  and dt.receivedquantity=0  then ''PARTIALLY RECT AT IQC''
	   when   h.approvedby>0  and (SELECT sum((dt.orderedquantity)-(dt.atrectquantity)) FROM [db_mm].[dtl_purchaseorder] DT  WHERE DT.ORDERID=H.ORDERID GROUP BY ORDERID ) =0 
	   AND DT.RECEIVEDQUANTITY=0 then ''FULLY RECT AT IQC''
	    when   h.approvedby>0  and (SELECT sum((dt.orderedquantity)-(dt.RECEIVEDQUANTITY)) FROM [db_mm].[dtl_purchaseorder] DT  WHERE DT.ORDERID=H.ORDERID GROUP BY ORDERID ) >0 
	    then ''PARTIALLY  RECT AT STORE ''
		 when   h.approvedby>0  and (SELECT sum((dt.orderedquantity)-(dt.RECEIVEDQUANTITY)) FROM [db_mm].[dtl_purchaseorder] DT  WHERE DT.ORDERID=H.ORDERID GROUP BY ORDERID ) =0 
	    then ''COMPLETED ''
	   end 
	 from [db_mm].[hdr_purchaseorder] h
	 join [db_mm].[dtl_purchaseorder] dt on h.orderid=dt.orderid

	 join [db_masters].[supplier] s on h.suplid= s.id

	 join  [db_masters].[users] u on h.createdby = u.userid

	left join [db_masters].[department] d on u.departmentid= d.id 

	left join db_mm.mst_potype t on h.ordertypeid= t.id

	where (h.isjobwork=' + cast(@isjobwork as varchar(5))  + ' or isjobwork is null)'

		set @sql += ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))

		IF (@deptid >0)

		begin

			set @sql+= ' and d.id = ' + cast(@deptid as varchar(6)) 

		end

		IF (@suplid >0)

		begin

			set @sql+=  ' and h.suplid = ' + cast(@suplid as varchar(6)) 

		end

		IF (@preparedby >0)

		begin

			set @sql+=  ' and h.createdby = ' + cast(@preparedby as varchar(6)) 

		end

		IF (@fromdate != '')

		begin

			set @sql+=  ' and  convert(Date,h.orderdate) >= ''' + cast(@fromdate as varchar(20)) + ''''

		end

       IF (@todate != '')

		begin

			set @sql+=   ' and  convert(Date,h.orderdate) <= ''' + cast(@todate as varchar(20)) + ''''

		end

		if (@search !=null or @search !='')

				begin

				if (@searchtype != null or @searchtype !='')

					begin

						set @sql += ' and   H.ordernumber = ' + cast(@search as varchar(5)) 

					end

				else if (@searchtype = 'suplname')

					begin

						set @sql += ' and  h.suplname like ''' + cast(@search as varchar(50)) + '%'''

					end

					end

					--PRINT @SQL

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

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

	begin

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

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

	end 

	print @sql

	EXEC sp_executesql @SQL



	set @sql = 'Select count(h.[orderid]) records from  [db_mm].[hdr_purchaseorder] h

	 join [db_masters].[supplier] s on h.suplid= s.id

	 join  [db_masters].[users] u on h.createdby = u.userid

	left join [db_masters].[department] d on u.departmentid= d.id 

	where (h.isjobwork=' + cast(@isjobwork as varchar(5))  + ' or isjobwork is null)'

		set @sql += ' and h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))

		IF (@deptid >0)

		begin

			set @sql+= ' and d.id = ' + cast(@deptid as varchar(6)) 

		end

		IF (@suplid >0)

		begin

			set @sql+=  ' and h.suplid = ' + cast(@suplid as varchar(6)) 

		end

		IF (@preparedby >0)

		begin

			set @sql+=  ' and h.createdby = ' + cast(@preparedby as varchar(6)) 

		end

		IF (@fromdate != '')

		begin

			set @sql+=  ' and  convert(Date,h.orderdate) >= ''' + cast(@fromdate as varchar(20)) + ''''

		end

       IF (@todate != '')

		begin

			set @sql+=   ' and  convert(Date,h.orderdate) <= ''' + cast(@todate as varchar(20)) + ''''

		end

		if (@search !=null or @search !='')

				begin

				if (@searchtype = null or @searchtype ='')

					begin

						set @sql += ' and   H.ordernumber = ' + cast(@search as varchar(5)) 

					end

				else if (@searchtype = 'suplname')

					begin

						set @sql += ' and  h.suplname like ''' + cast(@search as varchar(50)) + '%'''

					end

					end

				

	EXEC sp_executesql @SQL

	

	

END











GO
/****** Object:  StoredProcedure [db_mm].[pr_getpolistforpassing]    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_mm].[pr_getpolistforpassing]1,100,1,1,'ordernumber','asc'
-- =============================================

CREATE PROCEDURE [db_mm].[pr_getpolistforpassing]
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='ordernumber',
	@sortorder nvarchar(100)='asc',
	@search varchar(50)='',
	@searchtype nvarchar(20)='' 
as
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql = 'Select [ordernumber],h.orderid, d.[deptname],[orderdate],[suplname], isnull([potaxamount],0) +  isnull([poamount],0) poamount from [db_mm].[hdr_purchaseorder] h
	left join [db_masters].[department] d on h.deptid= d.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		set @sql += ' and [postatus] not like  ''%C%'''
		set @sql +=' order by '  + cast(@sort as varchar(100)) + ' ' + @sortorder + ' ' 
		if (@search !=null or @search !='')
				begin
				if (@searchtype = null or @searchtype ='')
					begin
						set @sql += ' and   H.ordernumber = ' + cast(@search as varchar(5)) 
					end
				else if (@searchtype = 'suplname')
					begin
						set @sql += ' and  h.suplname like ''' + cast(@search as varchar(50)) + '%'''
					end
					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
		 select count(h.orderid)records from [db_mm].[hdr_purchaseorder] h
END

GO
/****** Object:  StoredProcedure [db_mm].[pr_getposupplieranduser]    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,14-05-2018>
-- Description:	<Description,Get po creater and supplier data>
--[db_mm].[pr_getposupplieranduser] 1,1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getposupplieranduser] 	
	@coid int,
	@boid int,
	@fyid int
	
as
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	Select distinct  h.[createdby] id,u.username name from [db_mm].[hdr_purchaseorder] h
	join [db_masters].[users] u on h.createdby = u.userid where h.coid=@coid and h.boid=@boid and h.fyid=@fyid 


	
	Select distinct h.suplid id, [suplname] name from [db_mm].[hdr_purchaseorder] h
	join [db_masters].[supplier] s on h.suplid= s.id where h.coid=@coid and h.boid=@boid and h.fyid=@fyid 
	
END




GO
/****** Object:  StoredProcedure [db_mm].[pr_getpurchaseaccounts]    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_mm].[pr_getpurchaseaccounts] 1
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getpurchaseaccounts] 
@coid int
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tree') IS NOT NULL DROP TABLE #tree
	CREATE TABLE #tree
(
    ID INT,
    name VARCHAR(100),
    parentgroupid INT,
	code varchar(20)
);

INSERT into  #tree (id,name,parentgroupid) SELECT id,name,parentgroupid from [db_accounts].[accountGroups] where coid=@coid

;WITH x AS
(
    -- anchor:
    SELECT ID, name, parentgroupid, [level] = 0
    FROM #tree WHERE  parentgroupid=4
    UNION ALL
    -- recursive:
    SELECT t.ID, t.name, t.parentgroupid, [level] = x.[level] + 1
    FROM x INNER JOIN  #tree AS t
    ON t.parentgroupid = x.ID 
)
SELECT ID, name, parentgroupid [level] FROM x
ORDER BY [level]
OPTION (MAXRECURSION 100);
DROP TABLE  #tree;

	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getrequisitiondata]    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>3

--[db_mm].[pr_getrequisitiondata] 1,1,2101,'N'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getrequisitiondata] 
	@coid int,
	@boid int,
	@reqnid int,
	@forreqn char(1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	Declare @productid bigint = 	(select productid  from [db_mm].[hdr_requisition]  where reqnid = @reqnid)
	
Select [reqnid],[reqnno],ih.[createdon],c.name costcentre,s.name store,d.deptname,[ih].[batchno],[ih].[manualslipno] ,reqndate,[deptid],[costcentreid],
	s.id storeid,[ih].[productid],itm.itemname productname,ih.[bomid],ISNULL([lotsize],0),(case when  ih.productid>0 then  'true' else 'false' end) bomexist,
	[batchmfgdate],[batchexpirydate],ISNULL( b.batchsize,0) batchsize,um.uom from [db_mm].[hdr_requisition] ih
	left join [db_masters].[costcentre] c on ih.costcentreid =c.id
	left  join [db_masters].[department] d on ih.deptid = d.id
	 left join [db_mm].[mst_store] s on s.id=ih.storeid
	 left join [db_mm].[hdr_bom] b on ih.productid=b.productid and ih.bomid=b.bomid
	 left join db_mm.mst_item itm on ih.productid=itm.id

left join [db_mm].[mst_item] im  on ih.productid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	 where ih.reqnid = @reqnid
	
	set @sql = ' select im.[itemcode],im.[oldcode],im.[itemname],im.[id] itemid,isnull([id].[requestedquantity],0) /nullif ([ih].[lotsize],0) [qty1] ,id.requestedquantity,b.[name],b.[id] brandid,
	  isnull((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator=''+''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator=''-''   and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   id.itemid = s.itemid),0) stockinhand,um.[uom],id.remarks,ISNULL(bd.quantity,pd.quantity) bomquantity,
    ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0))  from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty,isnull(issuedquantity,0) qtyalreadyissued
	  ,(isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0)) issuedquantity
      ,im.itemcategoryid  from [db_mm].[dtl_requisition] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	  left join [db_mm].[mst_item] im  on id.itemid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	  join [db_mm].[hdr_requisition] ih on id.reqnid=ih.reqnid
	  left join [db_mm].[dtl_bom] bd on ih.productid=bd.pid and ih.bomid=bd.bomid and id.itemid=bd.cid
	  left join [db_mm].[dtl_pbom] pd on ih.productid=pd.pid and ih.bomid=pd.pbomid and id.itemid=pd.cid
	   where id.reqnid = ' + cast(@reqnid as varchar(5))  
	if(@forreqn='N')
		begin 
		 set @sql +=  'and (isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0))>0 
		'  
		end
		print @sql
		EXEC sp_executesql @SQL
		--select * from #a2
		
SELECT str( b.version) version,b.bomid
	 from [db_mm].[hdr_bom] b
	WHERE b.productid=@productid
	--AND b.version!=0
	union
	select 'N/A' as version,0 as bomid



    -- get max indentno
	Select max(reqnno) as reqnno from [db_mm].[hdr_requisition] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

    -- get costcentres
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid

	-- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get store
	 select id, name, case when checksexempted=1 then 0 else 1 end porequired  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -----
	-- SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid
	-- from [db_mm].[hdr_bom] b
	--join  [db_mm].[mst_item] im on b.productid=im.id
	--join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid

	SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid,'R' as type
	 from [db_mm].[hdr_bom] b
	 join  [db_mm].[mst_item] im on b.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	 union all select  DISTINCT (productid),im.[itemname],im.itemcode,U.uom,p.pbomid,'P' as type
	from  [db_mm].[hdr_pbom] p
	join  [db_mm].[mst_item] im on p.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid


	----get requisition_arwise 
	select itemid,[brandid],[arno],[requestedquantity] from db_mm.dtl_requisition_arwise 
	where reqnid=@reqnid


	create table #tempcategorylist(
	id int,
	name	varchar(200),
	code	varchar(20),
	parentgroupid	int,
	categcode varchar(20),
	categname varchar(500),
	level int,
	lastitemcode	varchar(20),
	childcnt	int
	)
	insert into #tempcategorylist
	exec [db_masters].[pr_getitemcategorylist] @coid,1

	SELECT * FROM #tempcategorylist where parentgroupid=0

	SELECT * FROM  #tempcategorylist  WHERE parentgroupid > 0
	end

	
select isnull(arnumber,0) arnumber, sum(isnull(a.itemquantity,0))qty,itemid [itemid],
isnull(batch,0) [batch],0 [issueqty],0 [balanceqty] into #a1 
from db_mm.item_stk_trn  a where coid=@coid and boid=@boid  and trntypeid <>19 
and itemid in  (select distinct(itemid) from db_mm.dtl_requisition where reqnid=@reqnid) and trnoperator='+' group by itemid,arnumber,batch,
itemid,batch,manufacturer,supplier,assay,lod ,mfgdate,expdate

update #a1 set [issueqty] = isnull(a.qty,0)
from (select itemid,arnumber,batch,sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn where trnoperator='-' group by itemid,arnumber,batch) a 
where #a1.itemid = a.itemid and #a1.arnumber =isnull(a.arnumber,0) 


update #a1 set [balanceqty]=isnull(qty,0)-isnull([issueqty],0)


select * from  #a1
drop table #a1;
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.






GO
/****** Object:  StoredProcedure [db_mm].[pr_getrequisitiondata_mohit]    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>3

--[db_mm].[pr_getrequisitiondata_mohit] 1,1,2101,'N'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getrequisitiondata_mohit] 
	@coid int,
	@boid int,
	@reqnid int,
	@forreqn char(1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	Declare @productid bigint = 	(select productid  from [db_mm].[hdr_requisition]  where reqnid = @reqnid)
	
Select [reqnid],[reqnno],ih.[createdon],c.name costcentre,s.name store,d.deptname,[ih].[batchno],[ih].[manualslipno] ,reqndate,[deptid],[costcentreid],
	s.id storeid,[ih].[productid],itm.itemname productname,ih.[bomid],ISNULL([lotsize],0),(case when  ih.productid>0 then  'true' else 'false' end) bomexist,
	[batchmfgdate],[batchexpirydate],ISNULL( b.batchsize,0) batchsize,um.uom from [db_mm].[hdr_requisition] ih
	left join [db_masters].[costcentre] c on ih.costcentreid =c.id
	left  join [db_masters].[department] d on ih.deptid = d.id
	 left join [db_mm].[mst_store] s on s.id=ih.storeid
	 left join [db_mm].[hdr_bom] b on ih.productid=b.productid and ih.bomid=b.bomid
	 left join db_mm.mst_item itm on ih.productid=itm.id

left join [db_mm].[mst_item] im  on ih.productid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	 where ih.reqnid = @reqnid

	 IF OBJECT_ID('tempdb..#tempstockxx') IS NOT NULL DROP TABLE #tempstockxx
	create table #tempstockxx
	(
		id			bigint,
		stkdate		date,
		trntypeid	int,
		arnumber	varchar(100),
		Rectqty		decimal(10,3),
		issqty		decimal(10,3),
		balanceqty	decimal(10,3),
		unitid		int,
		unit		varchar(20),
		itemid		bigint,
		itemcode	varchar(20), 
		oldcode		varchar(20),
		itemname	varchar(250),
		rate		decimal(15,2),
		amount		decimal(15,2),
		batchno		varchar(20),
		manufacturer	varchar(500),
		supplier	varchar(500),
		assay	decimal(5,2),
		lod		decimal(5,2),
		mfgdate		date,
		expdate		date,
		store varchar(100),
		storeid int,
		requiredqty decimal(15,3),
		reservedstock decimal(15,3)
		 ---added by sukhbir on 22/07/2019 to auto populate arwise requested qty.
	);
	   DECLARE @myCursor cursor;
DECLARE @tableName char(100);
BEGIN
  SET @myCursor = CURSOR FOR
 select  distinct(itemid) from  [db_mm].[dtl_requisition] where reqnid = 2101

  OPEN @myCursor
  FETCH NEXT FROM @myCursor
  INTO @tableName

  WHILE @@FETCH_STATUS = 0
        BEGIN		

insert  #tempstockxx	exec [db_mm].[pr_itemstockarwise]1,1,1,@tableName			
FETCH NEXT FROM @myCursor INTO @tableName 			              
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END
	select * from #tempstockxx
	set @sql = ' select ''-'' as arnumber,im.[itemcode],im.[oldcode],im.[itemname],im.[id] itemid,isnull([id].[requestedquantity],0) /nullif ([ih].[lotsize],0) [qty1] ,id.requestedquantity,b.[name],b.[id] brandid,
	  isnull((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator=''+''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator=''-''   and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   id.itemid = s.itemid),0) stockinhand,um.[uom],id.remarks,ISNULL(bd.quantity,pd.quantity) bomquantity,
    ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0))  from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty,isnull(issuedquantity,0) qtyalreadyissued
	  ,(isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0)) issuedquantity
      ,im.itemcategoryid  from [db_mm].[dtl_requisition] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	  left join [db_mm].[mst_item] im  on id.itemid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	  join [db_mm].[hdr_requisition] ih on id.reqnid=ih.reqnid
	  left join [db_mm].[dtl_bom] bd on ih.productid=bd.pid and ih.bomid=bd.bomid and id.itemid=bd.cid
	  left join [db_mm].[dtl_pbom] pd on ih.productid=pd.pid and ih.bomid=pd.pbomid and id.itemid=pd.cid
	   where id.reqnid = ' + cast(@reqnid as varchar(5))  
	if(@forreqn='N')
		begin 
		 set @sql +=  'and (isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0))>0 
		'  
		end
	set	@sql +=' union all select arnumber, itemcode,oldcode,itemname,itemid,0 as [qty1],0 requestedquantity ,''-'' as name,0 as brandid ,0 as stockinhand,''-'' as uom,arnumber as remarks,0 as bomquantity,0 as reservedqty,0 as qtyalreadyissued
	,0 as issuedquantity,0 as itemcategoryid from #tempstockxx order by itemid'
	print @sql
		EXEC sp_executesql @SQL
		

		
SELECT str( b.version) version,b.bomid
	 from [db_mm].[hdr_bom] b
	WHERE b.productid=@productid
	--AND b.version!=0
	union
	select 'N/A' as version,0 as bomid



    -- get max indentno
	Select max(reqnno) as reqnno from [db_mm].[hdr_requisition] where coid=@coid and boid=@boid 

	
	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

    -- get costcentres
	select id,name  from db_masters.costcentre where  coid= @coid and boid=@boid

	-- get item brands
	select id ,name from db_mm.mst_brand  where coid=@coid and boid = @boid and isActive = 1

	---get store
	 select id, name, case when checksexempted=1 then 0 else 1 end porequired  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -----
	-- SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid
	-- from [db_mm].[hdr_bom] b
	--join  [db_mm].[mst_item] im on b.productid=im.id
	--join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid

	SELECT DISTINCT (productid),im.[itemname],im.itemcode,U.uom,b.bomid,'R' as type
	 from [db_mm].[hdr_bom] b
	 join  [db_mm].[mst_item] im on b.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid
	 union all select  DISTINCT (productid),im.[itemname],im.itemcode,U.uom,p.pbomid,'P' as type
	from  [db_mm].[hdr_pbom] p
	join  [db_mm].[mst_item] im on p.productid=im.id
	join [db_mm].[mst_itemuom] u on u.id=im.receivingunitid


	----get requisition_arwise 
	select itemid,[brandid],[arno],[requestedquantity] from db_mm.dtl_requisition_arwise 
	where reqnid=@reqnid


	create table #tempcategorylist(
	id int,
	name	varchar(200),
	code	varchar(20),
	parentgroupid	int,
	categcode varchar(20),
	categname varchar(500),
	level int,
	lastitemcode	varchar(20),
	childcnt	int
	)
	insert into #tempcategorylist
	exec [db_masters].[pr_getitemcategorylist] @coid,1

	SELECT * FROM #tempcategorylist where parentgroupid=0

	SELECT * FROM  #tempcategorylist  WHERE parentgroupid > 0





	-- IF OBJECT_ID('tempdb..#tempstockxx') IS NOT NULL DROP TABLE #tempstockxx
 --select  * from  [db_mm].[dtl_requisition] where reqnid = 2101
	--create table #tempstockxx
	--(
	--	id			bigint IDENTITY(1,1) NOT NULL,
	--	stkdate		date,
	--	trntypeid	int,
	--	arnumber	varchar(100),
	--	Rectqty		decimal(10,3),
	--	issqty		decimal(10,3),
	--	balanceqty	decimal(10,3),
	--	unitid		int,
	--	unit		varchar(20),
	--	itemid		bigint,
	--	itemcode	varchar(20), 
	--	oldcode		varchar(20),
	--	itemname	varchar(250),
	--	rate		decimal(15,2),
	--	amount		decimal(15,2),
	--	batchno		varchar(20),
	--	manufacturer	varchar(500),
	--	supplier	varchar(500),
	--	assay	decimal(5,2),
	--	lod		decimal(5,2),
	--	mfgdate		date,
	--	expdate		date,
	--	store varchar(100),
	--	storeid int,
	--	requiredqty decimal(15,3),
	--	reservedstock decimal(15,3)
	--	 ---added by sukhbir on 22/07/2019 to auto populate arwise requested qty.
	--);
--DECLARE @myCursor cursor;
--DECLARE @tableName char(100);
--DECLARE @myCursor1 cursor;
--DECLARE @tableName1 char(100);
-- declare @totalqty decimal(13,3);
-- declare @reqqty char(100);
--BEGIN
--  SET @myCursor = CURSOR FOR select  distinct(itemid) from  [db_mm].[dtl_requisition] where reqnid = 2101

--  OPEN @myCursor
--  FETCH NEXT FROM @myCursor
--  INTO @tableName

--  WHILE @@FETCH_STATUS = 0
--  BEGIN
--insert  #tempstockxx	exec [db_mm].[pr_itemstockarwise]1,1,1,@tableName	
--FETCH NEXT FROM @myCursor INTO @tableName 			              
--        END   
--  CLOSE @myCursor
--  DEALLOCATE @myCursor
--END
--select  * from  #tempstockxx

--BEGIN
--  SET @myCursor1 = CURSOR FOR select  id from  #tempstockxx   
--  OPEN @myCursor1
--  FETCH NEXT FROM @myCursor1
--  INTO @tableName1
--  WHILE @@FETCH_STATUS = 0
--  BEGIN
--  set  @totalqty =  (select  requestedquantity from  [db_mm].[dtl_requisition] where reqnid = 2101 and itemid=@tableName)
--  set @reqqty=(select  balanceqty from  #tempstockxx where id = @tableName1 )
-- while @totalqty>=@reqqty 
-- begin
-- update #tempstockxx set issqty=balanceqty  
-- set @totalqty=@totalqty-@reqqty
-- end
 
-- while @totalqty<=@reqqty and @totalqty>0
-- begin
-- update #tempstockxx set issqty=@totalqty
-- set @totalqty=@totalqty-@totalqty
-- end
 
--FETCH NEXT FROM @myCursor1 INTO @tableName1			              
--        END   
--  CLOSE @myCursor1
--  DEALLOCATE @myCursor1
--END

--select * from #tempstockxx







	end

	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.






GO
/****** Object:  StoredProcedure [db_mm].[pr_getrequisitiondataravi]    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>3

--[db_mm].[pr_getrequisitiondatasukhi]  1,1,2101,'N'
-- =============================================
create PROCEDURE [db_mm].[pr_getrequisitiondataravi] 
	@coid int,
	@boid int,
	@reqnid int,
	@forreqn char(1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max), @mytable varchar(1000) = '#tree'
	Declare @productid bigint = 	(select productid  from [db_mm].[hdr_requisition]  where reqnid = @reqnid)
	begin 
Select [reqnid],[reqnno],ih.[createdon],c.name costcentre,s.name store,d.deptname,[ih].[batchno],[ih].[manualslipno] ,reqndate,[deptid],[costcentreid],
	s.id storeid,[ih].[productid],itm.itemname productname,ih.[bomid],ISNULL([lotsize],0),(case when  ih.productid>0 then  'true' else 'false' end) bomexist,
	[batchmfgdate],[batchexpirydate],ISNULL( b.batchsize,0) batchsize,um.uom from [db_mm].[hdr_requisition] ih
	left join [db_masters].[costcentre] c on ih.costcentreid =c.id
	left  join [db_masters].[department] d on ih.deptid = d.id
	 left join [db_mm].[mst_store] s on s.id=ih.storeid
	 left join [db_mm].[hdr_bom] b on ih.productid=b.productid and ih.bomid=b.bomid
	 left join db_mm.mst_item itm on ih.productid=itm.id

left join [db_mm].[mst_item] im  on ih.productid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	 where ih.reqnid = @reqnid
	if OBJECT_ID('tempdb..#reqntable') IS NOT NULL DROP TABLE #reqntable
	CREATE TABLE #reqntable (
	        itemcode varchar(100),
			oldcode varchar(100),
			itemname varchar(500),
			itemid INT,
			qty1 decimal(15,5) default(0.00000),
			requestedquantity decimal(15,5) default(0.00000),
			name varchar(500),
			brandid bigint,
			stockinhand decimal(15,5) default(0.00000),
			uom varchar(100),
			remarks varchar(500),
			bomquantity decimal(15,5) default(0.00000),
			reservedqty decimal(15,5) default(0.00000),
			qtyalreadyissued decimal(15,5) default(0.00000),

			issuedquantity decimal(15,5) default(0.00000),
			itemcategoryid int
		);
		
	set @sql = ' insert into #reqntable (itemcode,oldcode,itemname,itemid,qty1,requestedquantity,name,brandid,stockinhand,uom,remarks,bomquantity,reservedqty,
	qtyalreadyissued,issuedquantity,itemcategoryid) (select im.[itemcode],im.[oldcode],im.[itemname],im.[id] itemid,isnull([id].[requestedquantity],0) /nullif ([ih].[lotsize],0) [qty1] ,id.requestedquantity,b.[name],b.[id] brandid,
	  isnull((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator=''+''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator=''-''   and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   id.itemid = s.itemid),0) stockinhand,um.[uom],id.remarks,ISNULL(bd.quantity,pd.quantity) bomquantity,
    ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0))  from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty,isnull(issuedquantity,0) qtyalreadyissued
	  ,(isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0)) issuedquantity
      ,im.itemcategoryid  from [db_mm].[dtl_requisition] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	  left join [db_mm].[mst_item] im  on id.itemid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	  join [db_mm].[hdr_requisition] ih on id.reqnid=ih.reqnid
	  left join [db_mm].[dtl_bom] bd on ih.productid=bd.pid and ih.bomid=bd.bomid and id.itemid=bd.cid
	  left join [db_mm].[dtl_pbom] pd on ih.productid=pd.pid and ih.bomid=pd.pbomid and id.itemid=pd.cid
	   where id.reqnid = ' + cast(@reqnid as varchar(5))  
	if(@forreqn='N')
		begin 
		 set @sql +=  ' and (isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0))>0)
		'  
		end
		print @sql
		EXEC sp_executesql @SQL
		select * from #reqntable
	
	select isnull(arnumber,0) arnumber, sum(isnull(a.itemquantity,0))qty,itemid [itemid],
isnull(batch,0) [batch],0 [issueqty],0 [balanceqty],0 arqty into #a1 
from db_mm.item_stk_trn  a where coid=@coid and boid=@boid  and trntypeid <>19 
and itemid in  (select distinct(itemid) from db_mm.dtl_requisition where reqnid=@reqnid) and trnoperator='+' group by itemid,arnumber,batch,
itemid,batch,manufacturer,supplier,assay,lod ,mfgdate,expdate

update #a1 set [issueqty] = isnull(a.qty,0)
from (select itemid,arnumber,batch,sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn where trnoperator='-' group by itemid,arnumber,batch) a 
where #a1.itemid = a.itemid and #a1.arnumber =isnull(a.arnumber,0) 


update #a1 set [balanceqty]=isnull(qty,0)-isnull([issueqty],0)

declare  @totqty int,@iarqty int;
set @totqty = (select top 1 issuedquantity from #reqntable)

set @iarqty= (select top 1 balanceqty from #a1)

--if @totqty>@iarqty
--begin
--select @iarqty
--update  a set a.arqty=a.balanceqty from   #a1 a
--join #reqntable b on a.itemid=b.itemid 
--set @totqty=@totqty
--select @totqty
--end
declare @sukh decimal
DECLARE @issueqtyarwise AS int;
DECLARE @CurEmpNo AS varchar;
declare @arqty int;
SELECT @issueqtyarwise = (select top 1 issuedquantity from #reqntable)

DECLARE arwise_cursor CURSOR FOR
  SELECT arnumber
  FROM   #a1

OPEN arwise_cursor;

FETCH NEXT FROM arwise_cursor INTO @CurEmpNo

WHILE @@FETCH_STATUS = 0

--set @arqty=a.arqty
  BEGIN

     
	 
	 set @sukh=400 --(select balanceqty from #a1  WHERE  arnumber= CURRENT OF arwise_cursor);
	 select @sukh
	 select @CurEmpNo  
	  --set @arqty=#a1.arqty
	  --set @arqty= a.arqty
     
	  if(@sukh<@issueqtyarwise)
       begin
	    set @issueqtyarwise = @issueqtyarwise-@sukh;
	   UPDATE #a1
       SET    arqty = isnull(@issueqtyarwise,0)
       WHERE  CURRENT OF arwise_cursor;
	   end
	   else
	   begin
	      set @issueqtyarwise =0;
	     UPDATE #a1
       SET    arqty = isnull(@sukh,0)
       WHERE  CURRENT OF arwise_cursor;
	   end;


	   --UPDATE #a1
    --  SET    arqty = isnull(@sukh,0)
    --  WHERE  CURRENT OF arwise_cursor;
	  --UPDATE #a1
   --   SET    arqty = isnull(@issueqtyarwise,0)
   --   WHERE  CURRENT OF arwise_cursor;

      FETCH NEXT FROM arwise_cursor INTO @CurEmpNo
	   --SELECT @issueqtyarwise = @issueqtyarwise -@arqty;
  END;

CLOSE arwise_cursor;
select * from #a1



end
end
	






GO
/****** Object:  StoredProcedure [db_mm].[pr_getrequisitiondatasukhi]    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>3

--[db_mm].[pr_getrequisitiondatasukhi]  1,1,2101,'N'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getrequisitiondatasukhi] 
	@coid int,
	@boid int,
	@reqnid int,
	@forreqn char(1)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max), @mytable varchar(1000) = '#tree'
	Declare @productid bigint = 	(select productid  from [db_mm].[hdr_requisition]  where reqnid = @reqnid)
	begin 
Select [reqnid],[reqnno],ih.[createdon],c.name costcentre,s.name store,d.deptname,[ih].[batchno],[ih].[manualslipno] ,reqndate,[deptid],[costcentreid],
	s.id storeid,[ih].[productid],itm.itemname productname,ih.[bomid],ISNULL([lotsize],0),(case when  ih.productid>0 then  'true' else 'false' end) bomexist,
	[batchmfgdate],[batchexpirydate],ISNULL( b.batchsize,0) batchsize,um.uom from [db_mm].[hdr_requisition] ih
	left join [db_masters].[costcentre] c on ih.costcentreid =c.id
	left  join [db_masters].[department] d on ih.deptid = d.id
	 left join [db_mm].[mst_store] s on s.id=ih.storeid
	 left join [db_mm].[hdr_bom] b on ih.productid=b.productid and ih.bomid=b.bomid
	 left join db_mm.mst_item itm on ih.productid=itm.id

left join [db_mm].[mst_item] im  on ih.productid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	 where ih.reqnid = @reqnid
	if OBJECT_ID('tempdb..#reqntable') IS NOT NULL DROP TABLE #reqntable
	CREATE TABLE #reqntable (
	        itemcode varchar(100),
			oldcode varchar(100),
			itemname varchar(500),
			itemid INT,
			qty1 decimal(15,5) default(0.00000),
			requestedquantity decimal(15,5) default(0.00000),
			name varchar(500),
			brandid bigint,
			stockinhand decimal(15,5) default(0.00000),
			uom varchar(100),
			remarks varchar(500),
			bomquantity decimal(15,5) default(0.00000),
			reservedqty decimal(15,5) default(0.00000),
			qtyalreadyissued decimal(15,5) default(0.00000),

			issuedquantity decimal(15,5) default(0.00000),
			itemcategoryid int
		);
		
	set @sql = ' insert into #reqntable (itemcode,oldcode,itemname,itemid,qty1,requestedquantity,name,brandid,stockinhand,uom,remarks,bomquantity,reservedqty,
	qtyalreadyissued,issuedquantity,itemcategoryid) (select im.[itemcode],im.[oldcode],im.[itemname],im.[id] itemid,isnull([id].[requestedquantity],0) /nullif ([ih].[lotsize],0) [qty1] ,id.requestedquantity,b.[name],b.[id] brandid,
	  isnull((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator=''+''  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator=''-''   and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   id.itemid = s.itemid),0) stockinhand,um.[uom],id.remarks,ISNULL(bd.quantity,pd.quantity) bomquantity,
    ((select sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0))  from [db_mm].[dtl_requisition] id where id.itemid=im.id group by id.itemid))reservedqty,isnull(issuedquantity,0) qtyalreadyissued
	  ,(isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0)) issuedquantity
      ,im.itemcategoryid  from [db_mm].[dtl_requisition] id
	 left join [db_mm].[mst_brand] b  on id.brandid = b.id
	  left join [db_mm].[mst_item] im  on id.itemid= im.id
	  left join [db_mm].[mst_itemuom] um on im.issuingunitid  = um.id
	  join [db_mm].[hdr_requisition] ih on id.reqnid=ih.reqnid
	  left join [db_mm].[dtl_bom] bd on ih.productid=bd.pid and ih.bomid=bd.bomid and id.itemid=bd.cid
	  left join [db_mm].[dtl_pbom] pd on ih.productid=pd.pid and ih.bomid=pd.pbomid and id.itemid=pd.cid
	   where id.reqnid = ' + cast(@reqnid as varchar(5))  
	if(@forreqn='N')
		begin 
		 set @sql +=  ' and (isnull(id.requestedquantity,0)-isnull(id.issuedquantity,0)+isnull(id.woffquantity,0))>0)
		'  
		end
		print @sql
		EXEC sp_executesql @SQL
		select * from #reqntable
	
	select isnull(arnumber,0) arnumber, sum(isnull(a.itemquantity,0))qty,itemid [itemid],
isnull(batch,0) [batch],0 [issueqty],0 [balanceqty],0 arqty into #a1 
from db_mm.item_stk_trn  a where coid=@coid and boid=@boid  and trntypeid <>19 
and itemid in  (select distinct(itemid) from db_mm.dtl_requisition where reqnid=@reqnid) and trnoperator='+' group by itemid,arnumber,batch,
itemid,batch,manufacturer,supplier,assay,lod ,mfgdate,expdate

update #a1 set [issueqty] = isnull(a.qty,0)
from (select itemid,arnumber,batch,sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn where trnoperator='-' group by itemid,arnumber,batch) a 
where #a1.itemid = a.itemid and #a1.arnumber =isnull(a.arnumber,0) 


update #a1 set [balanceqty]=isnull(qty,0)-isnull([issueqty],0)


declare @sukh decimal (12,5);
DECLARE @issueqtyarwise AS decimal (12,5);
DECLARE @balnceqty  AS decimal (12,5);
DECLARE @CurEmpNo AS varchar(250);
DECLARE @qtyleft AS decimal (12,5);
declare @arqty int;
DECLARE @qty AS decimal (12,5);
SELECT @issueqtyarwise = (select top 1 issuedquantity from #reqntable)

DECLARE arwise_cursor CURSOR FOR
  SELECT arnumber
  FROM   #a1

OPEN arwise_cursor;

FETCH NEXT FROM arwise_cursor INTO @CurEmpNo
--set @qtyleft = @issueqtyarwise
WHILE @@FETCH_STATUS = 0
--set @arqty=a.arqty
  BEGIN
 
	  set @balnceqty=(select balanceqty from #a1  where arnumber=@CurEmpNo)
	  -- set @qtyleft=@issueqtyarwise-@balnceqty
	  if @issueqtyarwise>@balnceqty
	  begin 

	   UPDATE #a1
       SET    arqty = isnull(@balnceqty,0)-isnull(@qtyleft,0)
       WHERE  CURRENT OF arwise_cursor;
	   --set @qty=(select arqty from  #a1 where arnumber=@CurEmpNo)
	   set @qtyleft=@issueqtyarwise-(select balanceqty from #a1 where arnumber=@CurEmpNo)
	   set @qty=@issueqtyarwise-(select arqty from  #a1 where arnumber=@CurEmpNo)
	   select @qtyleft as leftqty
	   set @balnceqty=0
	   end 
	   else
       begin
	  -- set @qtyleft=@issueqtyarwise-@balnceqty
	   UPDATE #a1
       SET    arqty = isnull(@issueqtyarwise,0)-isnull(@qtyleft,0)
       WHERE  CURRENT OF arwise_cursor;
	   --set @qtyleft=@issueqtyarwise-(select balanceqty from #a1 where arnumber=@CurEmpNo)
	   --select @qtyleft as leftqty
	   set @balnceqty=0
	   end
	  


      FETCH NEXT FROM arwise_cursor INTO @CurEmpNo
	   --SELECT @issueqtyarwise = @issueqtyarwise -@arqty;
  END;

CLOSE arwise_cursor;
select * from #a1


end
end

	






GO
/****** Object:  StoredProcedure [db_mm].[pr_getrequisitionlist]    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_mm].[pr_getrequisitionlist] 1,1000,1,1,'reqnid','desc','1162','reqnno','2'
-- ===========================================
CREATE PROCEDURE [db_mm].[pr_getrequisitionlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='reqnid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@searchtype varchar(20) = '',
	@storeid int =null
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select distinct(h.reqnid),[reqnno] ,c.name costcentre,s.name store,[reqndate], u.username,d.[deptname],[manualslipno],[batchmfgdate],[batchexpirydate],[batchno],[productid],m.itemname,lotsize batchsize,
	  (case when sum(isnull(dt.requestedquantity,0)-isnull(dt.issuedquantity,0)-isnull(dt.woffquantity,0) 
       )>0 then 0 else 1 end)reqnsettled 
	from [db_mm].[hdr_requisition] h
	 join  [db_mm].[dtl_requisition] dt on h.reqnid = dt.reqnid
	left join [db_mm].[mst_item] m on  h.productid=m.id
	left  join [db_masters].[department] d on h.deptid= d.id
	  left join [db_masters].[users] u on h.createdby = u.userid
	  left join [db_masters].[costcentre] c on h.costcentreid=c.id 
	left  join [db_mm].[mst_store] s on h.storeid=s.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if (@searchtype = 'reqno' and @search!='') 
	begin
		set @sql += ' and h.reqnno = ' + @search
	end
	else if (@searchtype = 'productname' and @search!='')
	begin
		set @sql += ' and  m.itemname like ''%' + cast(@search as varchar(50)) + '%'''
	end
	if(@storeid!='')
		begin
		 set @sql += ' and H.storeid =  ' + cast(@storeid as varchar(2))
		end
      set @sql += ' group by (h.reqnid),[reqnno],c.name ,s.name ,[reqndate], u.username,d.[deptname],[manualslipno],[batchmfgdate],[batchexpirydate],[batchno],[productid],m.itemname,lotsize '
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	 select count(h.[reqnid])records from [db_mm].[hdr_requisition] h
	 join [db_masters].[department] d on h.deptid= d.id
	join [db_masters].[users] u on h.createdby = u.userid 
				
	SELECT distinct (h.reqnid),h.[reqnno],h.reqndate [createdon],s.id [deptid],s.name deptname,h.reqndate from [db_mm].[hdr_requisition] h
	join [db_masters].[department] d on h.deptid=d.id 
    join db_mm.mst_store s on h.storeid = s.id
	join [db_mm].[dtl_requisition] dt on h.reqnid = dt.reqnid
	where  isnull(dt.requestedquantity,0)-isnull(dt.issuedquantity,0)-isnull(dt.woffquantity,0) > 0
    order by h.reqndate,s.name
	
	
END






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

-- =============================================
-- Author:		<Author, Ravinder>
-- Create date: <Create Date,31-10-2019>
-- Description:	<Description,Get supplier data>
--[db_mm].[pr_getrgpdata]  1,1,10
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getrgpdata] 
	@coid int,
	@boid int,
	@rgpid int

AS
BEGIN
	SET NOCOUNT ON;
	declare @partyid int, @fyid int, @orderid int;
	
	select  @partyid=[partyid], @fyid=fyid, @orderid=orderid from [db_mm].[hdr_rgp] WHERE id=@rgpid

	SELECT p.[id] as rgpid,[rgpno],[partyid],c.name partyname,cn.countryname country,ct.cityname city,st.statename state,c.gstin,employeeid,
	[outtime],[vehiclename],[vehicleno],[deptid],[storeid],[deliveryaddress],p.createdon,p.remarks,p.transportid, p.orderid,p.[rgpdate]
	from [db_mm].[hdr_rgp] p
	join db_masters.supplier c on p.partyid=c.id
	left join db_masters.city ct on c.city=ct.id
	left join db_masters.country cn on c.country=cn.id
	left join [db_masters].[statemaster] st on c.state=st.id
   WHERE p.id=@rgpid


	
	IF @orderid>0 
	  BEGIN
          exec [db_mm].[pogrossrequirement] 1,1,1,@orderid,@rgpid
	  END	
	ELSE
		BEGIN

		SELECT [itemid],[qty] as quantity,[brandid],[brandid], [expecteddate],im.itemname,im.itemcode,im.oldcode,
		 im.itemdescription, u.uom itemuom, p.itemspecification from [db_mm].[dtl_rgp_returnitems] p
		 JOIN [db_mm].[mst_item] im ON P.itemid=im.id
		  left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
		where P.rgpid = @rgpid

		 SELECT [itemid],[qtysent],[qtysent] as quantity, [qtysent] as pendingqty, [brandid],[rate], [brandid], [qtyrecdunused], 
		        im.itemname,im.itemcode,im.oldcode, p.itemspecification,  isnull([rate],0)*isnull([qtysent],0) as approxvalue, u.uom itemuom
		from [db_mm].[dtl_rgp] p
		 JOIN [db_mm].[mst_item] im ON P.itemid=im.id
		 left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
		where P.rgpid = @rgpid
	End
--	select * from #podetails
--	select * from #grossrequirement

	 --SELECT [itemid],[qtysent],[rate],[brandid],[rate],[brandid], [approxvalue],im.itemname,im.itemcode,im.oldcode,
	 --im.itemdescription from [db_mm].[dtl_rgp] p
	 --JOIN [db_mm].[mst_item] im ON P.itemid=im.id
  --  where P.rgpid = @rgpid

	-- get all departments
	select id, deptname  from db_masters.department where  coid= @coid and boid=@boid

	---get store
	 select id, name  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))

	 -- get employee
	select userid,firstname  from db_masters.users where  coid=@coid  and boid=@boid

	 ---get transport
	 SELECT [id],name from  [db_masters].[transport] where coid =  @coid  and boid=@boid


	 exec [db_mm].[pr_getsupplierpos]1,1,@partyid

	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getrgplist]    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_mm].[pr_getrgplist] 1,10,1,1,'rgpid','desc',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getrgplist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='rgpid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select h.[id] as rgpid,[rgpno],[name],h.[createdon],u.username,deptname, h.rgpdate from [db_mm].[hdr_rgp] h
	left join [db_masters].[users] u on h.createdby = u.userid
	left join  [db_masters].[department] d on h.deptid=d.id
	join [db_masters].[supplier] c on h.partyid=c.id'
	 
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.rgpno = ' + 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

	 select count(h.[id])records from [db_mm].[hdr_rgp] h
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getsaledashboarddata]    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_mm].[pr_getsaledashboarddata]  1,1,1
-- =============================================
-- [db_mm].[pr_getsaledashboarddata]  1,1,1

CREATE PROCEDURE [db_mm].[pr_getsaledashboarddata]
	@coid int,
	@boid int,
	@userid bigint,
	@dataformat varchar(20)=null
AS
BEGIN
  SET NOCOUNT ON;
		--pie chart
		    SELECT mq.name AS Labels,
	        count(hdr.enqstage) Data, mq.backgroundcolor, mq.hoverBackgroundColor, 
	        ROW_NUMBER() OVER (PARTITION BY mq.backgroundcolor,mq.hoverBackgroundColor 
	        ORDER BY mq.name,mq.backgroundcolor) row_no 
            FROM db_mktg.hdr_enq hdr
            LEFT JOIN db_mktg.mst_quotestage mq
            ON hdr.enqstage=mq.id GROUP BY 
		    enqstage,mq.name,mq.backgroundcolor,mq.hoverBackgroundColor
END;

GO
/****** Object:  StoredProcedure [db_mm].[pr_getsaledashboardenquires]    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_mm].[pr_getsaledashboarddata]  1,1,1
-- =============================================
-- [db_mm].[pr_getsaledashboardenquires] 1,1,1

CREATE PROCEDURE [db_mm].[pr_getsaledashboardenquires]
	@coid int,
	@boid int,
	@userid bigint,
	@dataformat varchar(20)=null
AS
BEGIN
  SET NOCOUNT ON;
    declare @currentyear int;	
	       
     select @currentyear = year(fystartdate) from db_masters.financialyears where iscurrentyr=1

	 select COUNT(*) Data,(case when MONTH(enqdate)=1 then 'January' 
		             when MONTH(enqdate)=2 then 'February' 
					 when MONTH(enqdate)=3 then 'March'  
					 when MONTH(enqdate)=4 then 'April' 
					 when MONTH(enqdate)=5 then 'May'  
					 when MONTH(enqdate)=6 then 'June'
					 when MONTH(enqdate)=7 then 'July'
					 when MONTH(enqdate)=8 then 'August'
					 when MONTH(enqdate)=9 then 'September'
					 when MONTH(enqdate)=10 then 'October'
					 when MONTH(enqdate)=11 then 'November'
					 when MONTH(enqdate)=12 then 'December'
		else ''  end) AS month
		FROM db_mktg.hdr_enq
        WHERE YEAR(enqdate)=2019
        GROUP BY MONTH(enqdate)


	 select COUNT(*) Data,(case when MONTH(quotedate)=1 then 'January' 
		          when MONTH(quotedate)=2 then 'February' 
				  when MONTH(quotedate)=3 then 'March'  
				  when MONTH(quotedate)=4 then 'April' 
				  when MONTH(quotedate)=5 then 'May'  
				  when MONTH(quotedate)=6 then 'June'
				  when MONTH(quotedate)=7 then 'July'
				  when MONTH(quotedate)=8 then 'August'
				  when MONTH(quotedate)=9 then 'September'
				  when MONTH(quotedate)=10 then 'October'
				  when MONTH(quotedate)=11 then 'November'
				  when MONTH(quotedate)=12 then 'December'
		else ''  end) AS month
		FROM db_mktg.hdr_quote
        WHERE YEAR(quotedate)=2019
        GROUP BY MONTH(quotedate)

END;

GO
/****** Object:  StoredProcedure [db_mm].[pr_getsaledashboardstatuswise]    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_mm].[pr_getsaledashboarddata]  1,1,1
-- =============================================
-- [db_mm].[pr_getsaledashboardstatuswise] 1,1,1

CREATE PROCEDURE [db_mm].[pr_getsaledashboardstatuswise]
	@coid int,
	@boid int,
	@userid bigint,
	@dataformat varchar(20)=null
AS
BEGIN
  SET NOCOUNT ON;
		select st.status, count(hdr.enqstatus) as Data,st.colorcode backgroundcolor,st.hoverBackgroundColor
		from db_mktg.hdr_enq hdr 
		left join db_mktg.mst_enqstatus st on hdr.enqstatus=st.id
		group by hdr.enqstatus,st.status,st.colorcode,st.hoverBackgroundColor

END;

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

CREATE PROCEDURE [db_mm].[pr_getstandardbomdata]
	@coid int,
	@boid int,
	@CHECKBOMTYPE VARCHAR =NULL
	as
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	IF(@CHECKBOMTYPE='S')
	
	BEGIN

	set @sql = '
	SELECT hdr.bomid,hdr.productid,hdr.version,hdr.remarks,hdr.coid,hdr.boid,hdr.drawingno,hdr.batchsize,
	im.itemname,im.itemdescription,im.id as itemid,im.itemcode,im.hsncode,im.oldcode,im.remarks,im.receivingunitid,um.uom
	FROM [db_mm].[hdr_bom] hdr
	join [db_mm].[mst_item] im on hdr.productid=im.id
	join [db_mm].[mst_itemuom] um on im.issuingunitid=um.id '

	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

	ELSE

	BEGIN

	set @sql = '	
	SELECT hdr.bomid,hdr.productid,hdr.version,hdr.remarks,hdr.coid,hdr.boid,hdr.drawingno,hdr.batchsize,
	so.oano,so.oadate,so.customerid,so.customername,so.customeraddr1,so.customeraddr2, sod.itemid
	FROM [db_mm].[hdr_customizedbom] hdr
	JOIN [db_sop].[dtl_saleorder] sod ON hdr.bomid=sod.bomid
	JOIN [db_sop].[hdr_saleorder] so ON sod.oaid=so.oaid'

	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
	 
	end
	

GO
/****** Object:  StoredProcedure [db_mm].[pr_getstktransferdata]    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_mm].[pr_getstktransferdata]  1,1,8
-- =============================================
create PROCEDURE [db_mm].[pr_getstktransferdata] 
	@coid int,
	@boid int,
	@stktransferid int

AS
BEGIN
	SET NOCOUNT ON;
	
	
	Select [stktransferid],[stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks]
  from [db_mm].[hdr_stktransfer] ih
	 where ih.[stktransferid] = @stktransferid

	 select im.[itemcode],im.[itemname],id.itemid,[id].[quantity],[arno]
	 from [db_mm].[dtl_stktransfer] id
	   join [db_mm].[mst_item] im  on id.itemid= im.id
	   where id.[stktransferid] = @stktransferid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_mm].[pr_getstktransferList]    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_mm].[pr_getstktransferlist] 1,10,1,1,'1','asc',''
-- =============================================

CREATE PROCEDURE [db_mm].[pr_getstktransferList] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='stktransferno',
	@sortorder nvarchar(100)='asc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select [stktransferid],[stktransferno],[manualslipno],[trntype] ,s.name recevingstore, u.username,d.[deptname],h.[remarks],h.createdon from [db_mm].[hdr_STKTRANSFER] h
	 join [db_masters].[department] d on h.departmentid= d.id
	  join [db_masters].[users] u on h.createdby = u.userid
	  join [db_mm].[mst_store] s on h.RECEIVINGSTOREID=s.id '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and H.stktransferno = ' + 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

	 select count(h.[stktransferid])records from [db_mm].[hdr_stktransfer] h
	 join [db_masters].[department] d on h.departmentid= d.id
	join [db_masters].[users] u on h.createdby = u.userid 
				
	
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getstore]    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_getstore]1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getstore] 
    @coid int,
	@boid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id, name  from [db_mm].[mst_store]where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getsubcostcentre]    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_getsubcostcentre]1,1,1
-- =============================================
create PROCEDURE [db_mm].[pr_getsubcostcentre] 
    @coid int,
	@boid int,
	@costcentreid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	select id,name  from db_masters.subcostcentre where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5)) and costcentreid = +cast(@costcentreid as varchar(5))
	
	END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getsupplierpoitems]    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_mm].[pr_getsupplierpoitems]1,1,'2054'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getsupplierpoitems]
    @coid int,
	@boid int,
	@poid VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;

	select CONCAT(m.itemcode,'- ',m.itemname,'- ',m.hsncode) itemdetail,m.oldcode, m.itemcode,h.orderid,uom.uom receiptuom,d.itemid,d.brandid, h.orderid,[ordernumber], h.orderdate,isnull(orderedquantity,0)-isnull(d.atrectquantity,0) orderedquantity,isnull(orderedquantity,0)-isnull(d.atrectquantity,0) AS quantityreceived,isnull(orderedquantity,0)-isnull(d.atrectquantity,0)
	as pendingquantity,itemrate,itemdiscount,itemtax,m.gstid,g.igst,g.cgst,g.sgst, g.igst,orderedquantity poquantity ,discpercent discpercentage
	from [db_mm].[hdr_purchaseorder] h
	 join [db_mm].[dtl_purchaseorder] d on h.orderid= d.orderid
	  join [db_mm].[mst_item] m  on d.itemid = m.id
	  left join db_mm.mst_gst g on m.gstid=g.gstid
	  LEFT JOIN [db_mm].[mst_itemuom] uom on m.receivingunitid=uom.id
	where ((orderedquantity)-(isnull(d.atrectquantity,0) + isnull(writeoffquantity,0))) > 0
	and h.orderid  in (SELECT DATA FROM dbo.Split1(@poid,','))  and h.orderdate < getdate();
	END
 



GO
/****** Object:  StoredProcedure [db_mm].[pr_getsupplierpos]    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_mm].[pr_getsupplierpoitems]1,1,180
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getsupplierpos] 
    @coid int,
	@boid int,
	@suplid int 
AS
BEGIN
	SET NOCOUNT ON;

	select  distinct(h.orderid),[ordernumber], h.orderdate from [db_mm].[hdr_purchaseorder] h
	join  [db_mm].[dtl_purchaseorder] d on h.orderid= d.orderid
	where ((d.orderedquantity)-(isnull(d.atrectquantity,0) + isnull(d.writeoffquantity,0))) > 0
	and h.approvedby>0
	and h.suplid = @suplid and h.orderdate < getdate();
	
	END




GO
/****** Object:  StoredProcedure [db_mm].[pr_gettermsandconditions]    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_mm].[pr_gettermsandconditions]1,1,188
-- =============================================
CREATE PROCEDURE [db_mm].[pr_gettermsandconditions] 
@coid int,
@boid INT,
@suplid int
AS
BEGIN
DECLARE @orderid int
	SET NOCOUNT ON;
	
	SET @orderid = (SELECT MAX(orderid) FROM [db_mm].[hdr_purchaseorder] WHERE suplid=@suplid)

	IF (@orderid) IS NOT NULL
	BEGIN
	
SELECT tc.id,name FROM [db_mm].[mst_termsandconditions] tc
JOIN [db_mm].[purchase_termsandconditions] ptc ON tc.id=ptc.termsandconditionsid
WHERE ptc.orderid=@orderid
END
ELSE 
begin
SELECT id,name FROM [db_mm].[mst_termsandconditions] where coid= @coid and boid=@boid 
END
END


GO
/****** Object:  StoredProcedure [db_mm].[pr_getvendorallocationlist]    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_mm].[pr_getvendorallocationlist] 1,20,1,1,1,'listno','asc',19,'listno'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getvendorallocationlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid INT,
	@boid INT,
	@userid int = 0,
	@sort nvarchar(100)='listno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@searchtype varchar(20) = '',
	@listtype char(1)='U'
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'Select listid,listno, listdate,h.userid,valuecustorder,valuestkorder,remarks,h.isactive, case when confirmedby > 0 then 1 else 0 end isconfirmed, 
	firstname + '' '' + lastname listuser,isnull((select max(appvllevel) batchno from db_mm.hdr_vendorallocation_approvals 
	where listid = h.listid and isactive=1),0) level from [db_mm].[hdr_vendor_allocation_list] h
	join db_masters.users u on h.userid= u.userid'
	 
	set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5)) 
	set @sql += ' and h.userid = case when ' + cast(@userid as varchar(5))  + '=0 then h.userid else ' + cast(@userid as varchar(5)) + ' end '

	if (@searchtype='listno' and @search>0) 
	begin
		set @sql += ' and h.listno = '  + cast(@search as varchar(50)) + ' '
	end
	if (@searchtype='batchno' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.hdr_vendor_allocation_list  where srctypeid = 5 and refid in (select batchid from db_production.hdr_batch where batchno  = '  + cast(@search as varchar(50)) + ' )) '
	end
	if (@searchtype='itemid' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.dtl_vendor_allocation_list  where itemid = '  + cast(@search as varchar(50)) + ' ) '
	end
	if (@searchtype='suplid' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.dtl_vendor_allocation_list  where suplid = '  + cast(@search as varchar(50)) + ' ) '
	end

	if (@listtype='U')
	begin
		set @sql += ' and isnull(h.confirmedby,0) = 0 '
	end
	if (@listtype='C')
	begin
		set @sql += ' and isnull(h.confirmedby,0) > 0 '
	end
	if (@listtype='A')
	begin
		set @sql += ' and h.listid in (select listid from db_mm.hdr_vendorallocation_approvals where isactive = 1)'
	end


	if (@sort!='')
		begin
			set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		end 
	else 
		begin
			set @sql +=' order by listno desc'
		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(h.[listid])  records from [db_mm].[hdr_vendor_allocation_list] h
	join db_masters.users u on h.userid= u.userid '
			set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
	
	if (@searchtype='listno' and @search>0) 
	begin
		set @sql += ' and h.listno = '  + cast(@search as varchar(50)) + ' '
	end
	if (@searchtype='batchno' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.hdr_vendor_allocation_list  where srctypeid = 5 and refid in (select batchid from db_production.hdr_batch where batchno  = '  + cast(@search as varchar(50)) + ' )) '
	end
	if (@searchtype='itemid' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.dtl_vendor_allocation_list  where itemid = '  + cast(@search as varchar(50)) + ' ) '
	end
	if (@searchtype='suplid' and @search>0) 
	begin
		set @sql += ' and h.listid in (select distinct listid from db_mm.dtl_vendor_allocation_list  where suplid = '  + cast(@search as varchar(50)) + ' ) '
	end
	if (@listtype='U')
	begin
		set @sql += ' and isnull(h.confirmedby,0) = 0 '
	end
	if (@listtype='C')
	begin
		set @sql += ' and isnull(h.confirmedby,0) > 0 '
	end
	if (@listtype='A')
	begin
		set @sql += ' and h.listid in (select listid from db_mm.hdr_vendorallocation_approvals where isactive = 1)'
	end

		EXEC sp_executesql @SQL

				
	select max(appvllevel) maxlevel from db_mm.mst_vendorallocation_approvals where isactive = 1
	
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getvendorallocationlistforapprovals]    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_mm].[pr_getvendorallocationlistforapprovals] 1,1,1,20,1,1,'listno','desc','',''
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getvendorallocationlistforapprovals] 
	@coid INT,
	@boid INT,
	@PageNumber INT=1,
	@PageSize INT=20,
	@userid int = 0,
	@supervisorid int = 0,
	@sort nvarchar(100)='listno',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@searchtype varchar(20) = ''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @level int=0;

	select @level=isnull(appvllevel,0) from db_mm.mst_vendorallocation_approvals where appvlauthorizeuserid = @userid

	if (@level>0)
	begin
		set @sql = 'Select h.listid,listno, listdate,h.userid,valuecustorder,valuestkorder,h.remarks,h.isactive, case when confirmedby > 0 then 1 else 0 end isconfirmed, 
		isnull(max(appvllevel),0) level , isnull(max(id),0) appvlid, 
		firstname + '' '' + lastname listuser from [db_mm].[hdr_vendor_allocation_list] h
		join db_masters.users u on h.userid= u.userid left join db_mm.hdr_vendorallocation_approvals pp on h.listid = pp.listid 
		and ((isnull(pp.appvllevel,0)<' + cast(@level as varchar(2)) + ' and pp.isactive=1) and  (isnull(pp.appvllevel,0)>' + cast(@level as varchar(2)) + ' and isnull(pp.isconfirmed,0)=0 and pp.isactive=0) )'
	
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5)) + ' and isnull(h.confirmedby,0)>0 '
		set @sql +=' and h.userid = case when ' + cast(@supervisorid as varchar(2)) + ' > 0 then ' + cast(@supervisorid as varchar(2)) + ' else h.userid end' 
		if (@searchtype = 'listno' and @search!='') 
		begin
			set @sql += ' and h.listno = '  + cast(@search as varchar(50)) + ' '
		end
		set @sql += ' group by h.listid,listno, listdate,h.userid,valuecustorder,valuestkorder,h.remarks,h.isactive, confirmedby,firstname + '' '' + lastname '
		if (@sort!='')
			begin
				set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
			end 
		else 
			begin
				set @sql +=' order by listno desc'
			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(h.[listid])  records from [db_mm].[hdr_vendor_allocation_list] h
		join db_masters.users u on h.userid= u.userid  left join db_mm.hdr_vendorallocation_approvals pp on h.listid = pp.listid  
		and ((isnull(pp.appvllevel,0)<' + cast(@level-1 as varchar(2)) + ' and pp.isactive=1) and  (isnull(pp.appvllevel,0)>=' + cast(@level-1 as varchar(2)) + ' and pp.isactive=0)) '

				set @sql += ' where isnull(h.confirmedby,0)>0 and  h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
				set @sql +=' and h.userid = case when ' + cast(@supervisorid as varchar(2)) + ' > 0 then ' + cast(@supervisorid as varchar(2)) + ' else h.userid end' 
			if (@searchtype = 'listno' and @search!='') 
				begin
					set @sql += ' and h.listno = ' + @search
				end
				print @sql
			EXEC sp_executesql @SQL
	end			
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getvendorallocationlistitems]    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_mm].[pr_getvendorallocationlistitems]  1,1,1,23
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getvendorallocationlistitems] 
	@coid INT,
	@boid INT,
	@fyid int,
	@listid int
AS
BEGIN
	SET NOCOUNT ON;
	
	Select h.listid,listno, listdate,h.userid,valuecustorder,valuestkorder,h.remarks,h.isactive, case when confirmedby > 0 then 1 else 0 end isconfirmed, 
	firstname + ' ' + lastname listuser, isnull(max(app.appvllevel),0) level, isnull(max(app.id),0) appvlid from [db_mm].[hdr_vendor_allocation_list] h
	join db_masters.users u on h.userid= u.userid 
	left join db_mm.hdr_vendorallocation_approvals app on h.listid = app.listid 
	where h.listid=@listid and h.coid = @coid and h.boid = @boid 
	group by h.listid,listno, listdate,h.userid,valuecustorder,valuestkorder,h.remarks,h.isactive, confirmedby,firstname , lastname 
	

	select dtl.id,dtl.listid,hdr.listno, hdr.listdate,dtl.indentid,dtl.itemid,mst.itemname,mst.itemcode,mst.oldcode,dtl.suplid,dtl.itemquantity,
	dtl.itemrate,dtl.approvedrate, dtl.qtyapproved,dtl.qtyrejected,dtl.quoteno,dtl.quotedate,dtl.quoterate,dtl.laborrate, sup.name suppliername,
	isnull(mst.gstid,0) gstid, isnull(gst.description,'') gstname,mst.hsncode, dtl.remarks , idn.indentnumber, 0 discountrate, 
	isnull(btc.batchno,0) batchno, isnull(btc.itemname,'') Product, (isnull(btc.instock,0)-isnull(btc.outstock,0)) stock,
	itemquantity * itemrate amount, (itemquantity*itemrate)*(gst.igst/100) taxamount, (itemquantity*itemrate)*(1+ (gst.igst/100))  gtotal ,
	0 lpurrate , '' lpurdate , gst.igst taxpercent , '' dlvydate , isnull(dtl.poid,0) poid 
	from db_mm.dtl_vendor_allocation_list dtl 
	join db_mm.hdr_vendor_allocation_list hdr on dtl.listid = hdr.listid and coid = @coid and boid = @boid
	left join db_mm.hdr_indent idn on dtl.indentid = idn.indentid 
	left join (select hdr.batchid,hdr.batchno, hdr.batchdate, dtl.itemid,dtl.quantity, mst.itemname,mst.oldcode,mst.itemcode,
	sum(case when trnoperator = '+' then itemquantity else 0 end) instock,sum(case when trnoperator = '-' then itemquantity else 0 end) outstock
	from db_production.hdr_batch hdr join db_production.dtl_batch dtl on hdr.batchid = dtl.batchid 
	join db_mm.mst_item mst on dtl.itemid = mst.id 
	join db_mm.item_stk_trn trn on mst.id = trn.itemid
	group by hdr.batchid,hdr.batchno, hdr.batchdate, dtl.itemid,dtl.quantity, mst.itemname,mst.oldcode,mst.itemcode) btc 
	on idn.refid = btc.batchid and idn.srctypeid = 5 and btc.itemid = dtl.itemid 
	join db_mm.mst_item mst on dtl.itemid = mst.id
	left join db_masters.supplier sup on dtl.suplid= sup.id 
	left join db_mm.mst_gst gst on mst.gstid = gst.gstid 
	 where dtl.listid=@listid;
	
	select 0 appvllevel,'Un-Confirmed' appvldescription
	union
	select appvllevel,appvldescription from db_mm.mst_vendorallocation_approvals where isactive=1 order by appvllevel

	select ordernumber,orderdate,suplname, supladdress1, supladdress2, suplcity, suplstate,suplpincode, poamount from db_mm.hdr_purchaseorder where orderid in (select poid from db_mm.dtl_vendor_allocation_list where listid = @listid)
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_getvendorallocationlistpos]    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_mm].[pr_getvendorallocationlistpos]  1,1,1,27
-- =============================================
CREATE PROCEDURE [db_mm].[pr_getvendorallocationlistpos] 
	@coid INT,
	@boid INT,
	@fyid int,
	@listid int
AS
BEGIN
	SET NOCOUNT ON;
	
	select distinct(orderid), orderdate,ordernumber,suplname,poamount,potaxamount,postatus 
	from [db_mm].[dtl_vendor_allocation_list] lst join [db_mm].[hdr_purchaseorder] hdr
	on lst.poid = hdr.orderid where lst.listid=@listid 
	--and hdr.coid = @coid and hdr.boid = @boid and hdr.fyid = @fyid 
	
END



GO
/****** Object:  StoredProcedure [db_mm].[pr_itemenquiry]    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].[pr_itemenquiry] 1,20,1,1,1,'Itemname','asc',null,1,1,null,null,1,'',''
-- =============================================

CREATE PROCEDURE [db_mm].[pr_itemenquiry] 
	@PageNumber bigint=1,
	@PageSize bigint=100,
	@fyid INT,
	@coid int = 1,
	@boid int = 1,
    @sort nvarchar(100)='ITEMNAME',
	@sortorder nvarchar(100)='asc',
	@itemid bigint= null,
	@storeid bigint = null,
	@categoryid int= null,
	@itemtypeids varchar(100)=null,
	@salepurchasetag bigint=null,
	@userid bigint= null,
	@accesstoken varchar(200)=null,
	@search nvarchar(100)=null,
	@searchtype nvarchar(20)='' 

AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	declare @sql1 nvarchar(max);
	--if exists (select userid from db_masters.users where userid = coalesce(@userid,userid) and useraccesstoken = coalesce(@accesstoken,useraccesstoken))

	begin
		-- check if temporary table exists or not
		IF OBJECT_ID('tempdb..#itemenquiry') IS NOT NULL DROP TABLE #itemenquiry
	
		CREATE TABLE #itemenquiry (
			itemid INT,
			itemcode varchar(100),
			itemname varchar(500),
			oldcode varchar(100),
			itemcategory varchar(500),
			itemcategoryid int,
			uom varchar(100),
			unitid int,
			openingstock decimal(15,5) default(0.00000),
			stockinhand decimal(15,5) default(0.00000),
			receivedqty decimal(15,5) default(0.00000),
			issueqty decimal(15,5) default(0.00000),
			underiqc decimal(15,5) default(0.00000),
			reservedstock decimal(15,5) default(0.00000),
			minlevel decimal(15,5) default(0.00000),
			maxlevel decimal(15,5) default(0.00000),
			reorderlevel decimal(15,5) default(0.00000),
			eoqlevel decimal(15,5) default(0.00000),
			totalindentqty decimal(15,5) default(0.00000),
			pendingpoqty decimal(15,5) default(0.00000),
			rejectedbyiqc decimal(15,5) default(0.00000),
			location varchar(200),
			wipqty decimal(15,5)  default(0.00000),
			igst decimal(15,5) default(0.00000),
			sgst decimal(15,5) default(0.00000),
			cgst decimal(15,5) default(0.00000),
			gstid int,
			hsncode varchar(200),
			hsnid int,
			conctaxid int,
			itemspecification varchar(max),
			leadtimesurface INT,
			billingdescription varchar(100),
			rmtype char(1)
		);
		
	--change by mohit (25-05-19 2:45 pm) add new  two line	concessionaltaxid conctaxid and left join db_mm.mst_hsn h on g.gstid=h.concessionaltaxid 
			--change  by mohit (13-06-19 1:45 pm) add (g.gstid=h.gstid and im.hsncode=h.hsncode) and h.id hsnid
		set @sql = 'Insert into #itemenquiry (itemid,itemcode,itemname,oldcode,itemcategoryid,unitid,
		openingstock,minlevel,maxlevel,reorderlevel,eoqlevel,location, gstid, igst, sgst, cgst, hsncode,stockinhand,conctaxid,hsnid,itemspecification,leadtimesurface
		,billingdescription,rmtype)
		select im.id, itemcode,itemname,isnull(oldcode,''''),itemcategoryid,receivingunitid,
		0,isnull(minlevel,0),isnull(maxlevel,0),isnull(rol,0),isnull(eoq,0),location, im.gstid, g.igst, g.sgst, g.cgst, im.hsncode,0  
		,0,h.id hsnid,itemspecification,isnull(leadtimesurface,0), isnull(im.billingdescription,''''),case when [itemcode] like ''MC%'' then 1 else 0 end rmtype
		from db_mm.mst_item im
		inner join [db_mm].[mst_itemcategory] ct on ct.id = im.itemcategoryid
		left join [db_mm].[item_types] it on im.id=it.itemid  
		left join [db_mm].[mst_gst] g on im.gstid=g.gstid
		left join db_mm.mst_hsn h on im.hsncode=h.hsncode'
		print @sql
		--left join [db_mm].[item_types] it on im.id = it.itemid 
		set @sql+= ' where im.coid=' + cast(@coid as varchar(2))+ ' and im.boid=' + cast(@boid as varchar(2))
		IF (@itemid != '')
		begin
			set @sql+= ' and im.id = ' + cast(@itemid as varchar(6)) 
		end
		IF (@categoryid != '')
		begin
			set @sql+= ' and im.itemcategoryid in (select * from dbo.fngetchilditemcategoryids(' + cast(@categoryid as varchar(4)) + '))'
		end

        if (@userid != '')
        begin
            set @sql+= ' and im.itemcategoryid in (select itemcategoryid from db_mm.[itemcategories_userrights] where userid =' + cast(@userid as varchar(6)) + ')'
        end    
		IF (@itemtypeids != '')
		begin
			set @sql+= ' and it.typeid in (select * from dbo.fnSplitstring(''' + cast(@itemtypeids as varchar(100)) + ''','','')) '
		end
		if (@search !=null or @search !='')
				begin
				if (@searchtype = null or @searchtype ='')
					begin
						set @sql += ' and  im.itemname like ''%' + cast(@search as varchar(50)) + '%''  or  im.itemcode like ''%' + cast(@search as varchar(50)) + '%''  or  im.oldcode like ''%' + cast(@search as varchar(50)) + '%'''
					--change by mohit (28-06-2019)
                         set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemname)asc, LEN(itemname)' + @sortorder + ' '
					end
				else if (@searchtype = 'name')
					begin
						set @sql += ' and  im.itemname like ''%' + cast(@search as varchar(50)) + '%'''
						--change by mohit (28-06-2019)
                             set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemname)asc, LEN(itemname)' + @sortorder + ' '

					end
				else if (@searchtype = 'oldcode')
					begin
						set @sql += ' and  im.oldcode like ''%' + cast(@search as varchar(50)) + '%'''
						--change by mohit (28-06-2019)
                            set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',oldcode)asc, LEN(oldcode)' + @sortorder + ' '
					end
				else if (@searchtype = 'itemcode')
					begin
						set @sql += ' and  im.itemcode like ''%' + cast(@search as varchar(50)) + '%'''
						--change by mohit (28-06-2019)
                             set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemcode)asc, LEN(itemcode)' + @sortorder + ' '
					end					
				
		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(10))  + ' ROWS
		FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
		end
		
		EXEC sp_executesql @SQL
	
		

		 -- update itemcategory from mst_itemcategory
		 update #itemenquiry set itemcategory = name from 
		#itemenquiry join db_mm.mst_itemcategory iCat on #itemenquiry.itemcategoryid = iCat.id
		
		 -- update uom from mst_itemuom
		 update #itemenquiry set #itemenquiry.uom = iUOM.uom from 
		#itemenquiry join db_mm.mst_itemuom iUOM on #itemenquiry.unitid = iUOM.id
		

		-- update opening stock from db_mm.item_stk_trn table, trytype = 16 for opening stock
		update #itemenquiry set openingstock = stk.stock from 
		(select itemid, sum(isnull(itemquantity,0)) stock from db_mm.item_stk_trn
		where boid=@boid and trntypeid = 16  and storeid = coalesce(@storeid,storeid) and 
		coid =@coid  and fyid=@fyid group by itemid) stk where #itemenquiry.itemid = stk.itemid 
				
		--receivedqty 
		update #itemenquiry set receivedqty =  stk1.stock
		from (select itemid, sum(isnull(itemquantity,0)) stock from db_mm.item_stk_trn
		where boid=@boid and trnoperator='+' and storeid = coalesce(@storeid,storeid) 
        and trntypeid not in (16 ,19) and
		coid =@coid  and fyid=@fyid group by itemid) stk1
		where #itemenquiry.itemid = stk1.itemid

        --issueqty 
		update #itemenquiry set issueqty =  stk2.stock
		from  
		(select itemid, sum(isnull(itemquantity,0)) stock from db_mm.item_stk_trn
		where boid=@boid and trnoperator='-'  and storeid = coalesce(@storeid,storeid) and  
		coid =@coid and fyid=@fyid group by itemid) stk2
		where #itemenquiry.itemid = stk2.itemid

		---- calculate stock in hand 
		--update #itemenquiry set stockinhand =   stk3.stock
		--from  
		--(select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn 
		--where  storeid = coalesce(@storeid,storeid) and boid=@boid and coid =@coid  
  --      and fyid=@fyid  and trntypeid <>19 group by itemid) stk3
		--where #itemenquiry.itemid = stk3.itemid
		---- calculate stock in hand 

		update #itemenquiry set stockinhand = isnull((SELECT sum(s.itemquantity) FROM (
  SELECT itemid, itemquantity FROM [db_mm].[item_stk_trn] where trnoperator='+'  and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
  UNION ALL
  SELECT itemid, -itemquantity  FROM [db_mm].[item_stk_trn] where trnoperator='-'   and boid=1 and coid =1  
        and fyid=1  and trntypeid <>19
) s where   #itemenquiry.itemid = itemid),0)


		--underiqc 
        update #itemenquiry set underiqc = isnull(a.iqcqty,0) from 
        (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)) iqcqty 
        from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on hdr.grnid = dtl.grnid and hdr.[status] in ('E','Q')
        group by itemid) a 
        where #itemenquiry.itemid = a.itemid

        --underiqc 
        update #itemenquiry set underiqc = underiqc + isnull(stk4.stock,0) from 
		(select itemid, sum(isnull(itemquantity,0)) stock from db_mm.item_stk_trn
		where boid=@boid and trntypeid = 19  and storeid = coalesce(@storeid,storeid) and 
		coid =@coid  and fyid=@fyid group by itemid) stk4 where #itemenquiry.itemid = stk4.itemid 
		

		--reservedstock 
        update #itemenquiry set reservedstock = rsvstk.rsvqty from 
        (select itemid, sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0)) rsvqty
         from db_mm.dtl_requisition  group by itemid) rsvstk where #itemenquiry.itemid = rsvstk.itemid
         

		--totalindentqty
		update #itemenquiry set totalindentqty = indentstock.qty from 
		(select itemid,sum(isnull(quantityapproved,0)) qty from db_mm.dtl_indent group by itemid) indentstock
		where #itemenquiry.itemid = indentstock.itemid

		--update totalindentqty
		update #itemenquiry set totalindentqty = totalindentqty - receivedstock.qty from 
		(select itemid, sum(isnull(receivedquantity,0)) qty from db_mm.dtl_purchaseorder where indentid > 0 group by itemid) receivedstock
		where #itemenquiry.itemid = receivedstock.itemid

		--pendingpoqty 
		--rejectedbyiqc
		--wipqty 

		SELECT DISTINCT(itemid), * from #itemenquiry
	--set @sql1 = 'select count(im.id) records
	--	from db_mm.mst_item im
	--	inner join [db_mm].[mst_itemcategory] ct on ct.id = im.itemcategoryid
	--	left join [db_mm].[item_types] it on im.id=it.itemid  
	--	left join [db_mm].[mst_gst] g on im.gstid=g.gstid
	--	left join db_mm.mst_hsn h on im.hsncode=h.hsncode'
		
	--	--left join [db_mm].[item_types] it on im.id = it.itemid 
	--	set @sql1+= ' where im.coid=' + cast(@coid as varchar(2))+ ' and im.boid=' + cast(@boid as varchar(2))
	--	IF (@itemid != '')
	--	begin
	--		set @sql1+= ' and im.id = ' + cast(@itemid as varchar(6)) 
	--	end
	--	IF (@categoryid != '')
	--	begin
	--		set @sql1+= ' and im.itemcategoryid in (select * from dbo.fngetchilditemcategoryids(' + cast(@categoryid as varchar(4)) + '))'
	--	end

 --       if (@userid != '')
 --       begin
 --           set @sql1+= ' and im.itemcategoryid in (select itemcategoryid from db_mm.[itemcategories_userrights] where userid =' + cast(@userid as varchar(6)) + ')'
 --       end    
	--	IF (@itemtypeids != '')
	--	begin
	--		set @sql1+= ' and it.typeid in (select * from dbo.fnSplitstring(''' + cast(@itemtypeids as varchar(100)) + ''','','')) '
	--	end
	--	if (@search !=null or @search !='')
	--			begin
	--			if (@searchtype = null or @searchtype ='')
	--				begin
	--					set @sql1 += ' and  im.itemname like ''%' + cast(@search as varchar(50)) + '%''  or  im.itemcode like ''%' + cast(@search as varchar(50)) + '%''  or  im.oldcode like ''%' + cast(@search as varchar(50)) + '%'''
	--				--change by mohit (28-06-2019)
 --                        set @sql1 +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemname)asc, LEN(itemname)' + @sortorder + ' '
	--				end
	--			else if (@searchtype = 'name')
	--				begin
	--					set @sql1 += ' and  im.itemname like ''%' + cast(@search as varchar(50)) + '%'''
	--					--change by mohit (28-06-2019)
 --                            set @sql1 +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemname)asc, LEN(itemname)' + @sortorder + ' '

	--				end
	--			else if (@searchtype = 'oldcode')
	--				begin
	--					set @sql1 += ' and  im.oldcode like ''%' + cast(@search as varchar(50)) + '%'''
	--					--change by mohit (28-06-2019)
 --                           set @sql1 +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',oldcode)asc, LEN(oldcode)' + @sortorder + ' '
	--				end
	--			else if (@searchtype = 'itemcode')
	--				begin
	--					set @sql1 += ' and  im.itemcode like ''%' + cast(@search as varchar(50)) + '%'''
	--					--change by mohit (28-06-2019)
 --                            set @sql1 +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',itemcode)asc, LEN(itemcode)' + @sortorder + ' '
	--				end					
				
	--	end
	--	exec sp_executesql @sql1
		select ROWCOUNT_BIG() as records
		
		SELECT * from #itemenquiry where itemcode like 'RM%'	
		
	end
END










GO
/****** Object:  StoredProcedure [db_mm].[pr_itemstockarwise]    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_mm].[pr_itemstockarwise]1,1,1,21
-- =============================================
CREATE PROCEDURE [db_mm].[pr_itemstockarwise]
@coid int,
@boid int,
@fyid int,
@itemid bigint=null
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tempstock') IS NOT NULL DROP TABLE #tempstock
	create table #tempstock
	(
		id			bigint,
		stkdate		date,
		trntypeid	int,
		arnumber	varchar(100),
		Rectqty		decimal(10,3),
		issqty		decimal(10,3),
		balanceqty	decimal(10,3),
		unitid		int,
		unit		varchar(20),
		itemid		bigint,
		itemcode	varchar(20), 
		oldcode		varchar(20),
		itemname	varchar(250),
		rate		decimal(15,2),
		amount		decimal(15,2),
		batchno		varchar(20),
		manufacturer	varchar(500),
		supplier	varchar(500),
		assay	decimal(5,2),
		lod		decimal(5,2),
		mfgdate		date,
		expdate		date,
		store varchar(100),
		storeid int,
		requiredqty decimal(15,3),
		reservedstock decimal(15,3),
		gstid int null,
		igst decimal(15,3),
		sgst decimal(15,3),
		cgst decimal(15,3),
		suppplierstate int,

		 ---added by sukhbir on 22/07/2019 to auto populate arwise requested qty.
	);

-- check and insert stock 
--insert into #tempstock (stkdate,trntypeid,arnumber,rectqty,issqty,balanceqty,unit,itemid,rate,
--amount,batchno,manufacturer,supplier,assay,lod,mfgdate,expdate,storeid)
--select createdon,trntypeid,arnumber, sum(isnull(a.itemquantity,0))qty,0,0,receiptuom,itemid,itemrate,
--itemrate*itemquantity, batch,manufacturer,supplier,assay,lod , mfgdate , expdate, storeid    
--from db_mm.item_stk_trn  a where coid=@coid and boid=@boid and fyid=@fyid and trntypeid <>19 
--and itemid=  coalesce(@itemid,itemid) and trnoperator='+' group by itemid,arnumber,batch,trntypeid,createdon,
--receiptuom,itemid,itemrate,
--itemrate*itemquantity, batch,manufacturer,supplier,assay,lod ,mfgdate,expdate,storeid

--insert into #tempstock (trntypeid,arnumber,rectqty,issqty,balanceqty,unit,itemid,rate,
--amount,batchno,manufacturer,supplier,assay,lod,mfgdate,expdate,storeid)
--select trntypeid,isnull(arnumber,0), sum(isnull(a.itemquantity,0))qty,0,0,receiptuom,itemid,itemrate,
--itemrate*itemquantity, isnull(batch,0),manufacturer,supplier,assay,lod , mfgdate , expdate, storeid    
--from db_mm.item_stk_trn  a where coid=@coid and boid=@boid and fyid=@fyid and trntypeid <>19 
--and itemid=  coalesce(@itemid,itemid) and trnoperator='+' group by itemid,arnumber,batch,trntypeid,
--receiptuom,itemid,itemrate,
--itemrate*itemquantity, batch,manufacturer,supplier,assay,lod ,mfgdate,expdate,storeid
--------------------insert into #tempstock (arnumber,rectqty,issqty,balanceqty,itemid,batchno,manufacturer,supplier,assay,lod,mfgdate,expdate,rate)
--------------------select isnull(arnumber,0), sum(isnull(a.itemquantity,0))qty,0,0,itemid,
--------------------isnull(batch,0),manufacturer,supplier,assay,lod , mfgdate , expdate,itemrate 
--------------------from db_mm.item_stk_trn  a where coid=@coid and boid=@boid and fyid=@fyid and trntypeid <>19 
--------------------and itemid=  coalesce(@itemid,itemid) and trnoperator='+' group by itemid,arnumber,batch,
--------------------itemid,
-------------------- batch,manufacturer,supplier,assay,lod ,mfgdate,expdate,itemrate

----changesd by sukhbir because arnumber is always unique no need to sum aty
declare @supplierstate int,@companystate int,@sameState bit = 0;
insert into #tempstock (arnumber,rectqty,issqty,balanceqty,itemid,batchno,manufacturer,supplier,assay,lod,mfgdate,expdate,rate)
select isnull(arnumber,0), isnull(a.itemquantity,0)qty,0,0,itemid,
isnull(batch,0),manufacturer,supplier,assay,lod , mfgdate , expdate,itemrate 
from db_mm.item_stk_trn  a where coid=@coid and boid=@boid and fyid=@fyid and trntypeid <>19 
and itemid=  coalesce(@itemid,itemid) and trnoperator='+' 



---update incoming stock
--update #tempstock set rectqty =(select sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn  a where trnoperator='+'
 --AND #tempstock.itemid = a.itemid and #tempstock.arnumber = a.arnumber or #tempstock.batchno=a.batch group by itemid,arnumber,batch,trntypeid)



--update #tempstock set issqty = a.qty
--from (select itemid,arnumber,batch,sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn where trnoperator='-' group by itemid,arnumber,batch) a 
--where #tempstock.itemid = a.itemid and #tempstock.arnumber = a.arnumber or #tempstock.batchno=a.batch
update #tempstock set issqty = isnull(a.qty,0)
from (select itemid,arnumber,batch,sum(isnull(itemquantity,0)) qty from db_mm.item_stk_trn where trnoperator='-' group by itemid,arnumber,batch) a 
where #tempstock.itemid = a.itemid and #tempstock.arnumber =isnull(a.arnumber,0) and #tempstock.batchno= isnull(a.batch,0)

update #tempstock set  balanceqty = Rectqty -isnull(issqty,0)
set  @companystate = (select homestateid  from db_general.company_branches where boid =@boid)

--update #tempstock set supplierstate = ( select s.state from db_masters.supplier s JOIN a on a.suplid=a.id)
--set @supplierstate= ( select s.state from db_masters.supplier s JOIN a on a.suplid=a.id)
 if (@companystate=@supplierstate) 
     BEGIN
        set @sameState=1
     END
--update item details
update #tempstock set itemcode = a.itemcode, oldcode = a.oldcode, itemname = a.itemname,gstid=a.gstid, igst=g.igst, sgst=0, cgst=0
from db_mm.mst_item a
 left join [db_mm].[mst_gst] g on a.gstid=g.gstid
 where #tempstock.itemid = a.id


  set  @companystate = (select homestateid  from db_general.company_branches where boid =@boid)
    
-- update store 
update #tempstock set store = a.name
from [db_mm].[mst_store] a where #tempstock.storeid = a.id
---update requiredqty from [db_mm].[dtl_requisition_arwise] added by sukhbir on 22/07/2019 to auto populate arwise requested qty.

update #tempstock set requiredqty=isnull(a.[requestedquantity],0)  from [db_mm].[dtl_requisition_arwise] a WHERE
 #tempstock.itemid = a.itemid and  #tempstock.arnumber = a.arno

  update #tempstock set reservedstock = rsvstk.rsvqty from 
        (select arno,itemid, sum(isnull(requestedquantity,0)-isnull(issuedquantity,0)-isnull(woffquantity,0)) rsvqty
         from db_mm.dtl_requisition_arwise  group by itemid,arno) rsvstk where #tempstock.itemid = rsvstk.itemid and #tempstock.arnumber=rsvstk.arno



select * from #tempstock  order by stkdate,id


drop table #tempstock;


END













GO
/****** Object:  StoredProcedure [db_mm].[pr_mrpgrossreqd]    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_mm].[pr_mrpgrossreqd]  1,1,1,null,'1,2'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_mrpgrossreqd] 
@coid int,
@boid int,
@userid int,
@oaid bigint = null,
@planid varchar(200)= null,
@level int=null
AS
BEGIN
	SET NOCOUNT ON;
	declare @msg varchar(500);
	declare @planno bigint, @pid bigint;
	IF @oaid IS NULL  and @planid is null
		BEGIN  
			set @msg = 'You must provide either oaid or planid to calculate gross requirement'
			PRINT @msg  
			RETURN  @msg
		END  

	IF OBJECT_ID('tempdb..#tempplan') IS NOT NULL DROP TABLE #tempplan
	create table #tempplan 
	(
		planid			bigint,
		planno			bigint,
		oaid			bigint,
		bomid			bigint,
		bomversion		varchar(10),
		productid		bigint,
		quantity		decimal(10,2),
		bombatchsize	decimal(10,2),
		mfactor			decimal(10,2)
	)

	--set @pid = @planid

	
	-- add data into planning table if @planid is null or @planid =0
	if @oaid > 0 and (@planid is null or @planid='0')
	begin
		select @planno = isnull(max(planno),0)+1 from db_mm.hdr_plan;
		insert into db_mm.hdr_plan (planno,createdby,plandate,confirmedby,confirmedon,remarks,coid,boid)
		values 
		(@planno, @userid, getdate(),@userid,getdate(),'plan created automatically from production confirmation screen',@coid,@boid)

		SELECT @pid= SCOPE_IDENTITY()

        set @planid = @pid

		insert into db_mm.dtl_plan (planid,productid,bomid,orderquantity,samplequantity,totalquantity,manufacturedqty,knockedoffqty,oaid)
		select @pid, itemid, 0, orderedquantity,0,orderedquantity,0,0,oaid from db_sop.dtl_saleorder 
		where oaid = @oaid
		
		update db_mm.dtl_plan set bomid = a.bomid 
		from db_mm.hdr_bom a where db_mm.dtl_plan.productid = a.productid 
		and db_mm.dtl_plan.oaid = @oaid

		
	end


	insert into #tempplan (planid, productid, oaid, quantity,bombatchsize,bomid,mfactor) 
	select planid, productid, oaid, totalquantity - isnull(manufacturedqty,0) - isnull(knockedoffqty,0) ,1,0,1 from db_mm.dtl_plan 
	where planid in (select * from dbo.fnSplitString(@planid,',')) and totalquantity - isnull(manufacturedqty,0) - isnull(knockedoffqty,0) > 0

	-- update planno in #tempplan
	update #tempplan set planno = a.planno
	from db_mm.hdr_plan a where #tempplan.planid = a.planid

	--update bomid and batchsize from bom table
	update #tempplan set bomid = isnull(a.bomid,0), bombatchsize = isnull(a.batchsize,0),bomversion = a.version  
	from db_mm.hdr_bom a 
	join (select productid, max(bomid) bomid from db_mm.hdr_bom group by productid) b 
	on a.productid = b.productid 
	where #tempplan.productid = a.productid and coid = @coid and boid=@boid

	update #tempplan set bombatchsize = 1 where isnull(bombatchsize,0)=0

	--update mfactor column 
	update #tempplan set mfactor = quantity/isnull(bombatchsize,1)

	
	--select * from #tempplan


-- disable excisting gross requirement for planid
update db_mm.dtl_mrpgrossrequirement set isactive = 0 where planid in (select * from dbo.fnSplitString(@planid,','));

declare @grossid bigint;


-- insert row in hrd_mrpgrossrequirement
insert into db_mm.hdr_mrpgrossrequirement (grossdate, createdby,createdon,planid) values (getdate(),@userid,getdate(),@planid);
SELECT	@grossid = SCOPE_IDENTITY();

WITH x AS
(
    -- anchor:
    SELECT p.planid,p.planno, cast(p.productid as bigint) productid, cast(p.quantity as decimal(15,3)) quantity,p.mfactor, tolerance,wastagequantity,wastagepercent,bom.toexplode, [level] = 0 
	FROM #tempplan p left join 
	 db_mm.dtl_bom bom  on p.bomid =bom.bomid 
    UNION ALL
    -- recursive:
    SELECT x.planid,x.planno, cast(isnull(t.cid,0) as bigint) productid, cast(isnull(t.quantity,0) as decimal(15,3)) quantity ,x.mfactor, t.tolerance,t.wastagequantity,t.wastagepercent, t.toexplode,	[level] = x.[level] + 1 
    FROM x INNER JOIN db_mm.dtl_bom AS t 
    ON t.pid = x.productid where x.[level]+1 <= coalesce(@level,x.[level]+1) --and x.toexplode = 1
	
)
insert into db_mm.dtl_mrpgrossrequirement (grossid, planid,planno,rowno,itemid,itemname,itemcode,grossqty,isactive,createdby,createdon)
SELECT @grossid, planid, planno, ROW_NUMBER() OVER(ORDER BY x.productid ASC) AS Rowno , x.productid, a.itemname parent, a.oldcode oldcode, 
sum(quantity) grossquantity , 1, @userid,getdate() 
FROM x 
left join db_mm.mst_item a on x.productid = a.id 
group by planid, planno, x.productid, a.itemname , a.oldcode 
OPTION (MAXRECURSION 100);

