DROP TABLE #tempplan;

--select * from db_mm.dtl_mrpgrossrequirement where grossid = @grossid

select planid, planno, plandate,createdby from hdr_plan where planid in (select * from dbo.fnSplitString(@planid,',')) order by planid;

select dtl.planid, hdr.planno,hdr.plandate, dtl.productid,itemname, oldcode itemcode,uom.uom,dtl.orderquantity,dtl.samplequantity,
isnull(dtl.inventoryquantity,0) inventoryquantity, dtl.totalquantity from 
db_mm.dtl_plan dtl 
join db_mm.hdr_plan hdr on dtl.planid = hdr.planid 
join db_mm.mst_item on dtl.productid = db_mm.mst_item.id
join db_mm.mst_itemuom uom on db_mm.mst_item.issuingunitid = uom.id
where dtl.planid in (select * from dbo.fnSplitString(@planid,',')) order by dtl.planid, dtl.productid;

Select rp.itemid,rp.itemname, rp.itemcode, sum(isnull(grossqty,0)) qty,uom.uom  from db_mm.dtl_mrpgrossrequirement rp
join db_mm.mst_item item on rp.itemid = item.id
join db_mm.mst_itemuom uom on item.receivingunitid = uom.id
where grossid=@grossid group by rp.itemid,rp.itemname, rp.itemcode, uom.uom
	--select top 2 * from db_mm.mst_itemuom
	--select * from db_mm.dtl_plan where planid in (20)
	-- select * from db_mm.dtl_bom where id in (1,22)
END











GO
/****** Object:  StoredProcedure [db_mm].[pr_print_requisition]    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_print_requisition] 1,1,2101,'N'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_print_requisition] 
	@coid int,
	@boid int,
	@reqnid int
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
   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) lotsize,(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))  
	
		print @sql
		EXEC sp_executesql @SQL   

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







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




--[db_mm].[pr_printgrndata]1,1,1094
CREATE PROCEDURE [db_mm].[pr_printgrndata] 
	@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)
	
	 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]
	,ms.name store,m.accounthead purchasehead FROM  [db_mm].[hdr_grn] ih 
	  inner join db_masters.supplier s on ih.suplid=s.id 
	   inner join db_mm.mst_store ms on ih.storeid=ms.id 
	      inner join db_accounts.accountHeads m on ih.purchaseaccount=m.id 
     where ih.grnid = @grnid

	 select  CONCAT(im.itemcode, ', ',im.[itemname] )itemdetail ,im.id itemid , b.[name] brandname,[quantitybilled],[quantityreceived],id.[quantityrejected],
	 [quantityshortage],[quantitysurplus],[itemrate],[itemdiscount],id.[gstid],[igstamount] igstamt,[cgstamount] cgstamt,[sgstamount] sgstamt,id.[sampleqty]
	 ,id.batchno,case when id.mfgdate='1900-01-01 00:00:00' then '' else FORMAT (id.mfgdate, 'MMM-yy') end mfgdate,
	case when id.expirydate='1900-01-01 00:00:00' then '' else FORMAT (id.expirydate, 'MMM-yy') end expirydate,id.focqty,g.igst,g.cgst,g.sgst,quantitybroken,(id.quantitybilled*id.itemrate)+([igstamount] +[cgstamount] +[sgstamount]) totalamt,id.grnid
	 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
	 join [db_mm].[mst_gst] g  on id.gstid= g.gstid	   
	 where id.grnid = @grnid

	
	 
	-- terms & condition information
	select name termsandcondition from db_sop.mst_termsandconditions 
	-- GRN summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
create table #temp
(
id int ,
description VARCHAR(300),
amount  decimal(13,2)
);
	insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, (billamount)-(igstamount)-(sgstamount)-(cgstamount) amount from [db_mm].[hdr_grn] id 
	 where id.grnid = @grnid
	
	union
	Select 2 id, 'IGST ' + cast(left(igst,6) as varchar(3)) + ' %' description,sum(igstamount) amount from [db_mm].[dtl_grn] id 
	join [db_mm].[mst_gst] g  on id.gstid= g.gstid	
	where id.grnid = @grnid	
	group by igst having sum(isnull(id.igstamount,0))>0
	union
	Select 3 id, 'SGST ' + cast(left(sgst,6) as varchar(3))  + ' %' description,sum(sgstamount) amount from [db_mm].[dtl_grn] id
	join [db_mm].[mst_gst] g  on id.gstid= g.gstid	
	where id.grnid = @grnid 	group by sgst having sum(isnull(sgstamount,0))>0
	union
	Select 4 id, 'CGST ' + cast(left(cgst,6) as varchar(3))  + ' %' description,sum(cgstamount) amount from [db_mm].[dtl_grn] id
	join [db_mm].[mst_gst] g  on id.gstid= g.gstid	
	where id.grnid = @grnid  	group by cgst having sum(isnull(cgstamount,0))>0
	union 
	select 5 id, 'Discount Amount' description, isnull(billdiscount,0) amount from [db_mm].[hdr_grn] where grnid= @grnid 
	union 
	--select 6 id, 'Round Off' description, isnull(roundoff,0) amount from [db_sop].[hdr_sale] where oaid =@id
	--union 
	select 7 id, 'GRAND TOTAL' description, isnull(billamount,0) amount from [db_mm].[hdr_grn] where grnid= @grnid 
	)
	
	select * from #temp order by id
	-- convert inv-Amt to words
	SELECT db_general.NumberToWords(isnull(billamount,0),'Rs.') NumberToWords from [db_mm].[hdr_grn] where grnid= @grnid 

	 select g.[grnid],g.[itemid],[quantity],g.[brandid],g.[arnumber],case when g.mfgdate='1900-01-01 00:00:00' then '' else FORMAT (g.mfgdate, 'MMM-yy') end mfgdate,
	case when g.expirydate='1900-01-01 00:00:00' then '' else FORMAT (g.expirydate, 'MMM-yy') end expirydate,g.[orderid],g.[batchno],g.sampleqty 
	 from [db_mm].[grnbatchwise] g inner join
	 [db_mm].[dtl_grn] id on  g.grnid=id.grnid
	where id.grnid = @grnid and id.itemid = g.itemid and id.brandid = g.brandid
	
	end






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

AS
BEGIN
	SET NOCOUNT ON;
	Select [issuanceid],[issuanceno],isu.reqnid, isu.reqnno,isu.[createdon] date,c.name costcentre,s.name store,d.deptname,isu.batchno, isu.[manualslipno],isu.deptid,
	isu.[costcentreid],s.id storeid,isu.batchmfgdate,isu.batchexpirydate from [db_mm].[hdr_issuance] isu
	join [db_masters].[costcentre] c on isu.costcentreid =c.id
	 join [db_masters].[department] d on isu.deptid = d.id
	 join [db_mm].[mst_store] s on s.id=isu.storeid	
	 where isu.issuanceid = @issuanceid

	 select im.[itemcode],im.[itemname],id.[itemid],id.[brandid], b.[name] brandname,um.uom,[requestedquantity],
	 isnull(bch.issuedquantity,id.issuedquantity)[issuedquantity] ,id.[remarks],bch.arno,h.collectedby receiver,
	row_number() over(order by bch.id asc) as id into #tmptable 
	from [db_mm].[dtl_issuance] id join
	[db_mm].[hdr_issuance] h on id.issuanceid=h.issuanceid
	left  join [db_mm].[issuancebatchwise] bch on id.issuanceid=bch.issuanceid and id.itemid=bch.itemid
	 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 * from #tmptable 
	  --select top 1  itemname,arno from #tmptable 
	  --union all select '', arno from #tmptable where id <>1

	  update #tmptable  set itemname ='',itemcode='',itemid='' ,requestedquantity= null where id NOT IN (
  SELECT MIN(id) 
  FROM #tmptable
  GROUP BY itemname
);
	  select * from #tmptable
	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_printpo]    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_getpoprint] 1,1,5148
-- =============================================
CREATE PROCEDURE [db_mm].[pr_printpo] 
	@coid int,
	@boid int,
	@orderid int
	--@userid int,
	--@accesstoken varchar(50)

AS
BEGIN
	SET NOCOUNT ON;
	
	-- header data -- company information
	select  c.companyname,b.unitname,(isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' ' + isnull(b.city,'')+'-' + isnull(b.pin,'')) address,b.state,
	b.country,b.phone_number,b.email as emailid,b.PAN, b.TAN ,insurance_info
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	where b.coid = @coid and b.boid = @boid

declare @billto varchar(500)=(select  (c.companyname+ ' ' +isnull(b.unitname,'')+ ' Address :- ' +isnull(b.address1,'') + ' ' + isnull(b.address2,'')+' City :- ' + isnull(b.city,'') +' State :- ' +isnull(b.state,'')+' Country :- ' +
	isnull(b.country,'')+' Pin :- ' + isnull(b.pin,'')+' Phone :- ' +isnull(b.phone_number,'')+' Email :- ' +isnull(b.email,'')+' PAN :- ' +isnull(b.PAN,'')+' GSTIN :- ' + isnull(b.gstno,'')) as billto
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	where b.coid = 1 and b.boid = 1)

	Select [ordernumber],[orderdate],[suplname],[supladdress1],[supladdress2],[suplcity],[supltaxregistrationnumber], ih.suplid, ih.suplstate,
		 ih.suplpincode, ih.suplcontactperson,ih.quotationref, billtoid, ih.shiptoid,s.email,s.mobile_number phone_number,	
		 @billto billto,@billto shipto,
db_general.NumberToWords(ih.poamount+ih.potaxamount,'Rs.') amountinword,(ih.poamount+ih.potaxamount) as poamount,ih.costcentreid
	from [db_mm].[hdr_purchaseorder] ih 
	left join 	db_masters.supplier s on ih.billtoid =s.id
	 where ih.orderid = @orderid

	

	
	 select COALESCE(NULLIF(im.oldcode,''),im.itemcode) itemcode,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.brandid , id.itemdiscount, id.netrate*id.orderedquantity as netamt, ( id.netrate*id.orderedquantity)+id.igstamount+id.sgstamount+id.cgstamount total_amt,( id.netrate*id.orderedquantity) taxableamt,
		   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,
		  round(isnull(id.itemrate,0)*isnull(id.orderedquantity,0),2) as  basicamount, isnull(discpercent,0) discpercent
	 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, COALESCE(NULLIF(im.oldcode,''),im.itemcode) 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 d.itemid= im.id
	  left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
	   where d.orderid = @orderid
	   select top(1) emailid,phoneno from [db_general].[erp_modules_functionalities] where moduleid=6

	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_printrequisitiondata]    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,2029
-- =============================================
CREATE PROCEDURE [db_mm].[pr_printrequisitiondata] 
	@coid int,
	@boid int,	
	@reqnid int

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


   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) lotsize,(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))  
	
		print @sql
		EXEC sp_executesql @SQL   

	----get requisition_arwise 
	select itemid,[brandid],[arno],[requestedquantity] from db_mm.dtl_requisition_arwise 
	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_savebom]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [db_mm].[pr_savebom] 
    @statementtype nvarchar(50),
	@bomheader [db_mm].[hdr_bom_tvp] readonly,
	@bomdetail [db_mm].[dtl_bom_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @bomid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
		
		insert into [db_mm].[hdr_bom] ([productid],[version],[createdby],[createdon],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize])
			Select [productid],[version],[createdby],[createdon],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize] from @bomheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding bom header data.', 16, 1)
				RETURN
				END
				SELECT @bomid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting bom id.', 16, 1)
				RETURN
				END
				
				
				insert into [db_mm].[dtl_bom] ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width])
				select @bomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[componentweight],[rmtype],[length],[width]
				from @bomdetail
				end 
				else
				Begin -- begin of update 
			-- fetching bom id from table type
			select top 1 @bomid = bomid from @bomheader

			select [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]
				from db_mm.hdr_bom where bomid = @bomid
				 EXCEPT select  [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]
				 from @bomheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_bom ([productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]) 
					SELECT [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize] from db_mm.hdr_bom where bomid = @bomid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_bom   set 
					    
[productid]=a.[productid],
[version]=a.[version],
[createdby]=a.[createdby],
[createdon]=a.[createdon],
[revisedby]=a.[revisedby],
[revisedon]=a.[revisedon],
[revisedreason]=a.[revisedreason],
[amendedby]=a.[amendedby],
[amendedon]=a.[amendedon],
[amendentmentreason]=a.[amendentmentreason],
[confirmedby]=a.[confirmedby],
[confirmedon]=a.[confirmedon],
[approvedby]=a.[approvedby],
[approvedon]=a.[approvedon],
[deactivatedby]=a.[deactivatedby],
[deactivatedon]=a.[deactivatedon],
[remarks]=a.[remarks],
[coid]=a.[coid],
[boid]=a.[boid],
[drawingno]=a.[drawingno],
[batchsize]=a.[batchsize]

					FROM   @bomheader a
					WHERE db_mm.hdr_bom.bomid= a.bomid 
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing bom record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select bomid from CloudERPbklog.db_mm.hdr_bom where bomid = @bomid)
						begin
							-- insert data in bom HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_bom ([bomid],[productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno]) 
					SELECT [bomid],[productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno] from db_mm.hdr_bom where bomid = @bomid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding bom data.', 16, 1)
								RETURN
								END
										end
				End
			
			--select [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid]
			-- from [db_mm].[dtl_bom] where bomid =@bomid				 
			-- EXCEPT select  [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid]
			--	from @bomdetail
			
			--EXEC sp_executesql @sql

			--SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			--IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_bom ([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid])
					SELECT [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid] from db_mm.dtl_bom where bomid = @bomid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_bom where [bomid]= @bomid
				
                insert into db_mm.dtl_bom([bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[length],[width],[componentweight],[rmtype])
					Select @bomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[length],[width],[componentweight],[rmtype] from @bomdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing bom detail record.', 16, 1)
							RETURN
					END
				END -- end of row count
			END
								commit
								END
								

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



CREATE  PROCEDURE [db_mm].[pr_savedestruction] 
    @statementtype nvarchar(50),
	@destructionheader [db_mm].[hdr_destruction_tvp] readonly,
	@destructiondetail [db_mm].[dtl_destruction_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @destructionid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		declare @destructionnumber int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		set @destructionnumber = (SELECT ISNULL(MAX(destructionno), 0) + 1 FROM db_mm.hdr_destruction)
		
		
		    insert into [db_mm].[hdr_destruction] ([destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[createdby],[createdon],[fyid])
			Select @destructionnumber,[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],@userid,getdate(),[fyid] from @destructionheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding destruction header data.', 16, 1)
				RETURN
				END
				SELECT @destructionid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				
		        insert into [db_mm].[dtl_destruction] ([destructionid],[itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount])
				select @destructionid,[itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
				from @destructiondetail


				---INSERT data INTO stock trn
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[coid],[boid],isactive,createdby,createdon,arnumber,refid)
				SELECT [itemid],[itemid],[quantity],18,'-',(SELECT coid FROM @destructionheader),(SELECT boid FROM @destructionheader),1,@userid,getdate (),arnumber,@destructionid FROM @destructiondetail
				end 
	else
		Begin -- begin of update .
			-- fetching indent id from table type
			select top 1 @destructionid = @destructionid from @destructionheader

			select [olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[fyid]
				from db_mm.hdr_destruction where destructionid = @destructionid
				 EXCEPT select [olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[fyid]
				 from @destructionheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_destruction ([destructionid],[destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select [destructionid],[destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from  db_mm.hdr_destruction where destructionid = @destructionid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_destruction   set 
					          [olnrno]= a.[olnrno],
                              [presenceofuserid1]=a.[presenceofuserid1],
                              [presenceofuserid2]=a.[presenceofuserid2],
                              [presenceofuserid3]=a.[presenceofuserid3],
							  [approvedbyproduction]=a.[approvedbyproduction],
							  [approvedbystorehead]=a.[approvedbystorehead],
							  [approvedbyqa]=a.[approvedbyqa],
							  [igstamt]=a.[igstamt],
							  [cgstamt]=a.[cgstamt],
							  [sgstamt]=a.[sgstamt],
							  [totalamt]=a.[totalamt],
                              [remarks]=a.[remarks],
                              [coid]=a.[coid],
                             [boid]=a.[boid],
                            [modifiedby]=@userid,
                            [modifiedon]=getdate(),
							[fyid]=a.[fyid]
					FROM   @destructionheader a
					WHERE  db_mm.hdr_destruction.destructionid =a.destructionid 
					
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing destruction record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select destructionid from CloudERPbklog.db_mm.hdr_destruction where destructionid = @destructionid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_destruction ([destructionid],[destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[createdby],[createdon],[fyid]) 
					Select [destructionid], [destructionno],[olnrno],[presenceofuserid1],[presenceofuserid2],[presenceofuserid3],[approvedbyproduction],[approvedbystorehead],[approvedbyqa],[igstamt],[cgstamt],[sgstamt],[totalamt],[coid],[boid],[remarks],[createdby],[createdon],[fyid] from db_mm.hdr_destruction where destructionid = @destructionid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding destruction data.', 16, 1)
								RETURN
	            End
		        End
				End
			
			select [itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
			from [db_mm].[dtl_destruction] where destructionid =@destructionid
			EXCEPT 
			SELECT [itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
			from @destructiondetail
			union 
			SELECT [itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
			from @destructiondetail
			EXCEPT 
			select [itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]
			from [db_mm].[dtl_destruction] where destructionid =@destructionid
			
			       

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_destruction ([destructionid],[itemid],[suplid],[quantity],[itemrate],[brandid],[arno],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount])
					SELECT @destructionid,[itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount] from db_mm.dtl_destruction where destructionid = @destructionid

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_destruction where destructionid = @destructionid
				
                insert into db_mm.dtl_destruction([destructionid],[itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount])
					SELECT @destructionid,[itemid],[suplid],[quantity],[itemrate],[brandid],[arnumber],[grnno],[batchno],[batchmfgdate],[batchexpdate],[destructionreason],[destructionmode],[igstamount],[cgstamount],[sgstamount]from @destructiondetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing destruction detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								COMMIT
								
								
								END

GO
/****** Object:  StoredProcedure [db_mm].[pr_savedpr]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mm].[pr_savedpr]
 @statementtype NVARCHAR(50),
@dprheader [db_mm].[hdr_dpr_tvp] READONLY,
@dprdetail [db_mm].[dtl_dpr_tvp] READONLY,
@userid INT = 1
AS

BEGIN  
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @dprid INT
		   ,@rowcnt INT
		   ,@colstring NVARCHAR(MAX)
		   ,@sql NVARCHAR(MAX)
	DECLARE @dprnumber INT
	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN
	set @dprnumber = (SELECT ISNULL(MAX(dprnumber), 0) + 1 FROM db_mm.hdr_dpr )


		INSERT INTO [db_mm].[hdr_dpr] ([dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid])
			SELECT
				[dprdate],@dprnumber,[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid]
			FROM @dprheader
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding dpr header data.', 16, 1)
			RETURN
		END
		SELECT
			@dprid = SCOPE_IDENTITY()
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while getting dpr id.', 16, 1)
			RETURN
		END


		INSERT INTO [db_mm].[dtl_dpr] ([dprid],[itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid],arnumber)
			SELECT
				@dprid,[itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid],arnumber
			FROM @dprdetail

			---INSERT data INTO stock trn
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[trntypeid],[trnoperator],batch,[coid],[boid],[refid],createdby,createdon,storeid)
				SELECT [itemid],[itemid],[brandid],[quantity],17,'+',batchno,(SELECT coid FROM @dprheader),(SELECT boid FROM @dprheader),@dprid,@userid,getdate(),7 FROM @dprdetail
	END
	ELSE
	BEGIN -- begin of update 
		-- fetching dpr id from table type
		SELECT TOP 1
			@dprid = dprid
		FROM @dprheader

		SELECT
			[dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid]
		FROM db_mm.hdr_dpr
		WHERE dprid = @dprid
		EXCEPT
		SELECT
		    [dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid]
		FROM @dprheader

		--print @sql
		--EXEC sp_executesql @sql

		SELECT
			@rowcnt = @@rowcount
		-- data needs to update if query returns a row  
		IF @rowcnt > 0
		BEGIN -- begin of row count
			-- insert records in bkup and checking @@ERROR 
			INSERT INTO CloudERPbklog.db_mm.hdr_dpr ([dprid], [dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid])
				SELECT
					[dprid], [dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],@userid,getdate(),[manualslipno],[fyid]
				FROM db_mm.hdr_dpr
				WHERE dprid = @dprid

			--print @sql

			--EXEC sp_executesql @sql

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			END
			-- updating existing records from supplier table and checking @@ERROR 
			UPDATE db_mm.hdr_dpr
			SET [dprdate] = a.[dprdate]
			   ,[dprnumber] = a.[dprnumber],
               [departmentid]=a.[departmentid],
               [remarks]=a.[remarks],
               [coid]=a.[coid],
               [boid]=a.[boid],
               [confirmedby]=a.[confirmedby],
               [confirmedon]=a.[confirmedon],
                [createdby]=a.[createdby],
               [createdon]=a.[createdon],
               [modifiedby]=a.[modifiedby],
             [modifiedon]=a.[modifiedon],
             [manualslipno]=a.[manualslipno],
            [fyid]=a.[fyid]
			FROM @dprheader a
			WHERE  db_mm.hdr_dpr.dprid= a.dprid 

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating existing dpr record.', 16, 1)
				RETURN
			END
		END -- end of row count
		ELSE -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
		BEGIN
			IF NOT EXISTS (SELECT
						dprid
					FROM CloudERPbklog.db_mm.hdr_dpr
					WHERE dprid = @dprid)
			BEGIN
				-- insert data in dpr HEADER table and checking @@ERROR 
				INSERT INTO CloudERPbklog.db_mm.hdr_dpr ([dprid], [dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid])
					SELECT
					     [dprid], [dprdate],[dprnumber],[departmentid],[remarks],[coid],[boid],[confirmedby],[confirmedon],[createdby],[createdon],[modifiedby],[modifiedon],[manualslipno],[fyid]
					FROM db_mm.hdr_dpr
					WHERE dprid = @dprid
				-- Rollback the transaction if there were any errors
				IF @@error <> 0
				BEGIN
					-- Rollback the transaction
					ROLLBACK
					-- Raise an error and return
					RAISERROR ('Error while adding dpr data.', 16, 1)
					RETURN
				END
			END
		END

		SELECT
		  [itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
		FROM [db_mm].[dtl_dpr]
		WHERE [dprid] = @dprid
		EXCEPT
		SELECT
		   [itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
		FROM @dprdetail
		union select  [itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
		FROM @dprdetail
		except select  [itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
		FROM [db_mm].[dtl_dpr]
		WHERE [dprid] = @dprid
			

		--EXEC sp_executesql @sql

		SELECT
			@rowcnt = @@rowcount
		-- data needs to update if query returns a row  
		IF @rowcnt > 0
		BEGIN -- begin of row count
			-- insert records in bkup and checking @@ERROR 
			INSERT INTO CloudERPbklog.db_mm.dtl_dpr ([dprid], [itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid])
				SELECT
					@dprid,[itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
				FROM db_mm.dtl_dpr
				WHERE [dprid] = @dprid

			--print @sql

			--EXEC sp_executesql @sql

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			END
			DELETE FROM db_mm.dtl_dpr
			WHERE [dprid] = @dprid

			INSERT INTO db_mm.dtl_dpr ([dprid],[itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid])
				SELECT
				    @dprid,
					[itemid],[quantity],[rejectedquantity],[rejectionreason],[batchno],[mfgdate],[expirydate],[retestdate],[coid],[boid],[approvedby],[approvedon],[brandid],[bomid]
				FROM @dprdetail

				delete from  [db_mm].[item_stk_trn] where refid=@dprid and trntypeid=17 and itemid not in(select itemid from @dprdetail)
                update  [db_mm].[item_stk_trn] 
                set [itemid]=a.[itemid],
                [reqditemid]=a.itemid,
                [brandid]= a.[brandid],
                [itemquantity]=a.quantity,
                [trntypeid]='17',
                [trnoperator]='+',
                batch=a.batchno,
                [coid]=(select coid from @dprheader),
                [boid]=(select boid from @dprheader),
                [refid]=@dprid,
                createdby= @userid,
                createdon=getdate(),
                storeid='7'
                from @dprdetail a
                where db_mm.item_stk_trn.refid = @dprid
                and db_mm.item_stk_trn.trntypeid=17
                and db_mm.item_stk_trn.itemid=a.itemid

				---INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[trntypeid],[trnoperator],batch,[coid],[boid],[refid],createdby,createdon,storeid)
				---SELECT [itemid],[itemid],[brandid],[quantity],17,'+',batchno,(SELECT coid FROM @dprheader),(SELECT boid FROM @dprheader),@dprid,@userid,getdate(),7 FROM @dprdetail
			-- Rollback the transaction if there were any errors
		IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating existing dpr detail record.', 16, 1)
				RETURN
			END
		END -- end of row count
	END
	COMMIT

END




GO
/****** Object:  StoredProcedure [db_mm].[pr_savegrn]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_mm].[pr_savegrn] 
    @statementtype nvarchar(50),
	@grnheader [db_mm].[hdr_grn_tvp] readonly,
	@grndetail [db_mm].[dtl_grn_tvp] readonly,
	@grnbatchwise [db_mm].[grnbatchwise_tvp] readonly,
	@grnlevies [db_mm].[dtl_grn_levies_tvp] readonly,
	@userid int=1
AS

BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @grnid int, @rowcnt int,@suplid int,@itemid int,@mainid int
		declare @grnnumber int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
	set @grnnumber = (SELECT ISNULL(MAX(grnnumber), 0) + 1 FROM db_mm.hdr_grn)
		
	
		insert into [db_mm].[hdr_grn] (grndate,grnnumber,gatenoteid,storeid,suplid,poid,billamount,totaltaxamount,billdiscount,billroundoff,billno,billdate,chalanno,chalandate,gateentryno,gateentrydate,
		purchaseaccount,grno,grdate,drcrnoteno,billpassamount,boid,coid,remarks,isactive,createdby,createdon,modifiedby,modifiedon,fyid,[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount],[grncategoryid]) 
			Select grndate,@grnnumber,[gatenoteid],[storeid]
				,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[boid],[coid],[remarks],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount],[grncategoryid]  from @grnheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding grn header data.', 16, 1)
				RETURN
				END
				SELECT @grnid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting indent id.', 16, 1)
				RETURN
				END
				update [db_mm].[hdr_grn] set status ='E' where grnid = @grnid
				
			   insert into [db_mm].[dtl_grn] (grnid,itemid,quantitybilled,quantityreceived,quantityrejected,quantityshortage,
				quantitysurplus,quantitybroken,itemrate,itemdiscount,ratediff,itemtax,brandid,hsncode,arnumber,qtyissued,receiptuom,issueuom,batchno,expirydate,mfgdate,orderid,[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty] )
				select @grnid,[itemid],[quantitybilled],[quantityreceived],[quantityrejected],(quantitybilled-quantityreceived),[quantitysurplus],
				[quantitybroken],[itemrate],[itemdiscount],[ratediff],[itemtax],[brandid],[hsncode],[arnumber],[qtyissued],[receiptuom],[issueuom],[batchno],[expirydate],[mfgdate],[orderid],[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty] 
				from @grndetail


				if   exists(select 1 from @grnbatchwise) 
				begin
				insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,arnumber,batchno,expirydate,mfgdate,orderid,[sampleqty],[supplierretestdate])
				select @grnid,[itemid],[quantity],[brandid],[arnumber],[batchno],[expirydate],[mfgdate],[orderid],[sampleqty],[supplierretestdate] from @grnbatchwise
				  insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,orderid,[sampleqty])
				select @grnid,[itemid],[quantityreceived],[brandid],[orderid],[sampleqty] from @grndetail where itemid  not in (select itemid from @grnbatchwise)
				end 
				ELSE
				begin
                insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,orderid,[sampleqty])
				select @grnid,[itemid],[quantityreceived],[brandid],[orderid],[sampleqty] from @grndetail
				end

				----Insert Levies data
	             insert into [db_mm].[dtl_grn_levies] (grnid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
	             igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate, createdby, createdon)
	             select @grnid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, igstamt, cgstamt, sgstamt, igstrate,
	             cgstrate, sgstrate, @userid, getdate()	from @grnlevies
	 	         IF @@error <> 0
		         BEGIN
			       -- Rollback the transaction
			      ROLLBACK
			-- Raise an error and return
			     RAISERROR ('Error while adding sop invoice levies data.', 16, 1)
			     RETURN
		         END

				---update atrectquantity in podetail
				update db_mm.dtl_purchaseorder  set atrectquantity=isnull(atrectquantity,0)+[quantityreceived] from @grndetail dt where db_mm.dtl_purchaseorder.orderid=dt.orderid
				and db_mm.dtl_purchaseorder.itemid=dt.itemid and db_mm.dtl_purchaseorder.brandid=dt.brandid 

				end 
	    else
		Begin -- begin of update
			select top 1 @grnid = grnid from @grnheader

			   select  [grndate],[grnnumber],[gatenoteid],[storeid]
				,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[suplname],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],
				[customduty],[otherdiscount],[jobworkamount],[grncategoryid]  from @grnheader
				Except
			   select [grndate],[grnnumber],[gatenoteid],[storeid]
				,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[suplname],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount],[grncategoryid]
			   from db_mm.hdr_grn where grnid =@grnid
			

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
				--	insert into CloudERPbklog.db_mm.hdr_GRN ([grnid],[grndate],[grnnumber],[gatenoteid],[storeid]
				--,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				--,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[boid],[coid],[remarks],[isactive],[modifiedby],[fyid],[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount]) 
				--	SELECT [grnid],[grndate],[grnnumber],[gatenoteid],[storeid]
				--,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				--,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[boid],[coid],[remarks],[isactive],@userid,[fyid],[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount]  from db_mm.hdr_grn where grnid = @grnid

					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_grn   set 
					         [grndate] = a.[grndate],
                                [storeid] =a.[storeid],
                             [suplid] =a.[suplid],
                             [poid] =a.[poid],
                             [billamount] =a.[billamount],
                             [totaltaxamount] =a.[totaltaxamount],
                             [billdiscount]=a.[billdiscount],
                             [billroundoff]=a.[billroundoff],
                             [billno]=a.[billno],
                             [billdate]=a.[billdate],
                             [chalanno]=a.[chalanno],
                             [chalandate] =a.[chalandate],
                             [gateentryno] =a.[gateentryno],
                             [gateentrydate] =a.[gateentrydate],
                             [purchaseaccount]=a.[purchaseaccount],
                             [grno] =a.[grno],
                             [grdate] =a.[grdate],
                             [drcrnoteno] =a.[drcrnoteno],
                             [billpassamount]=a.[billpassamount],
                             [boid] =a.[boid],
                             [coid] =a.[coid],
                             [remarks] =a.[remarks],
                             [isactive]=a.[isactive],
                             [modifiedby]=a.[modifiedby],
							 [suplname]=a.[suplname],
							[supladdress1]=a.[supladdress1],
							[supladdress2]=a.[supladdress2],
							[suplcity]=a.[suplcity],
							[suplstate]=a.[suplstate],
							[suplpincode]=a.[suplpincode],
							[suplphoneno]=a.[suplphoneno],
							[igstamount]=a.[igstamount],
							[cgstamount]=a.[cgstamount],
							[sgstamount]=a.[sgstamount],
							[freightandoctroi]=a.[freightandoctroi],
							[othercharges]=a.[othercharges],
							[customduty]=a.[customduty],
							[otherdiscount]=a.[otherdiscount],
							[jobworkamount]=a.[jobworkamount],
							[grncategoryid]=a.[grncategoryid]
					FROM   @grnheader a
					WHERE db_mm.hdr_grn.grnid= a.grnid 
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing grn record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select grnid from CloudERPbklog.db_mm.hdr_grn where grnid = @grnid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_grn([grnid],[grndate],[grnnumber],[gatenoteid],[storeid]
				,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[boid],[coid],[remarks],[isactive],[modifiedby],[fyid],[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount] )
			    Select [grnid],[grndate],[grnnumber],[gatenoteid],[storeid]
				,[suplid],[poid],[billamount],[totaltaxamount],[billdiscount],[billroundoff],[billno],[billdate],[chalanno],[chalandate],[gateentryno],[gateentrydate]
				,[purchaseaccount],[grno],[grdate],[drcrnoteno],[billpassamount],[boid],[coid],[remarks],[isactive],@userid,[fyid],[suplname],[supladdress1],[supladdress2],[suplcity],[suplstate],[suplpincode],[suplphoneno],[igstamount],[cgstamount],[sgstamount],[freightandoctroi],[othercharges],[customduty],[otherdiscount],[jobworkamount]  from db_mm.hdr_grn where grnid = @grnid
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding grn data.', 16, 1)
								RETURN
								END
										end
				End
			
			SELECT itemid,quantitybilled,quantityreceived,quantityrejected,quantityshortage,
			quantitysurplus,quantitybroken,itemrate,itemdiscount,ratediff,itemtax,brandid,hsncode,arnumber,qtyissued,receiptuom,issueuom,batchno,expirydate,mfgdate,orderid,[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty] 
			from [db_mm].[dtl_grn] where [grnid] =@grnid
			EXCEPT select itemid,quantitybilled,quantityreceived,quantityrejected,quantitshortage,
			quantitysurplus,quantitybroken,itemrate,itemdiscount,ratediff,itemtax,brandid,hsncode,arnumber,qtyissued,receiptuom,issueuom,batchno,expirydate,mfgdate,orderid,[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty]   from @grndetail		
			
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			
			IF @rowcnt > 0
				BEGIN 
				insert into CloudERPbklog.db_mm.dtl_grn (grnid,itemid,quantitybilled,quantityreceived,quantityrejected,quantitshortage,
				quantitysurplus,quantitybroken,itemrate,itemdiscount,ratediff,itemtax,brandid,hsncode,arnumber,qtyissued,receiptuom,issueuom,batchno,expirydate,mfgdate,orderid,[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty] ) 
					Select  @grnid,itemid,quantitybilled,quantityreceived,quantityrejected,quantityshortage,
				quantitysurplus,quantitybroken,itemrate,itemdiscount,ratediff,itemtax,brandid,hsncode,arnumber,qtyissued,receiptuom,issueuom,batchno,expirydate,mfgdate,orderid,[gstid],[igstamount],[cgstamount],[sgstamount],[sampleqty]  from db_mm.dtl_grn where [grnid] = @grnid

			
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 update db_mm.dtl_purchaseorder  set atrectquantity=isnull(atrectquantity,0)-[quantityreceived]+(select quantityreceived from @grndetail gd where db_mm.dtl_purchaseorder.itemid=gd.itemid and db_mm.dtl_purchaseorder.brandid=gd.brandid )   from @grndetail dt where db_mm.dtl_purchaseorder.orderid=dt.orderid
				     and db_mm.dtl_purchaseorder.itemid=dt.itemid and db_mm.dtl_purchaseorder.brandid=dt.brandid 
					 delete from db_mm.dtl_grn where [grnid] = @grnid

                
				insert into db_mm.dtl_grn(grnid,itemid,quantitybilled,quantityreceived,quantityrejected,quantityshortage,
				quantitysurplus,quantitybroken,itemrate,itemdiscount,brandid,hsncode,arnumber,qtyissued,receiptuom,orderid,[gstid],[igstamount],[cgstamount],
				[sgstamount],[sampleqty] )
					Select @grnid,itemid,quantitybilled,quantityreceived,quantityrejected,quantitshortage,
				quantitysurplus,quantitybroken,itemrate,itemdiscount,brandid,hsncode,arnumber,qtyissued,receiptuom,orderid,[gstid],[igstamount],[cgstamount],
				[sgstamount],[sampleqty]  from @grndetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing grn detail record.', 16, 1)
							RETURN
						END
						
				IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing grn detail record.', 16, 1)
							RETURN
						END
				END
				
				delete from [db_mm].[grnbatchwise] where grnid=@grnid
				
				if   exists(select 1 from @grnbatchwise) 
				begin
				insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,arnumber,batchno,expirydate,mfgdate,orderid,[sampleqty])
				select @grnid,[itemid],[quantity],[brandid],[arnumber],[batchno],[expirydate],[mfgdate],[orderid],[sampleqty] from @grnbatchwise
				  insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,orderid,[sampleqty])
				select @grnid,[itemid],[quantityreceived],[brandid],[orderid],[sampleqty] from @grndetail where itemid  not in (select itemid from @grnbatchwise)
				end 
				ELSE
				begin
                insert into [db_mm].[grnbatchwise] (grnid,itemid,quantity,brandid,orderid,[sampleqty])
				select @grnid,[itemid],[quantityreceived],[brandid],[orderid],[sampleqty] from @grndetail
				end -- end of row count

				delete from [db_mm].[dtl_grn_levies] where grnid=@grnid
	   insert into [db_mm].[dtl_grn_levies] (grnid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
	igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate, createdby, createdon)
	select @grnid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, igstamt, cgstamt, sgstamt, igstrate,
	 cgstrate, sgstrate, @userid, getdate()	from @grnlevies
			end
								commit
								
END




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

CREATE PROCEDURE [db_mm].[pr_savegrnconfirmation] 
    @grnid int,
	@grnbatchwise [db_mm].[grnbatchwise_tvp] readonly,
	@userid int=1,
	@coid int,
	@boid int
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @rowcnt int,@itemid int
		declare @grnnumber int,@reqnnumber int,@sampleqty int,@issuanceno int,@issuanceid int,@reqnno int,@reqnid int,@suplid int,
		 @sql nvarchar(max)
	BEGIN TRANSACTION

 
	set  @suplid= (select suplid from db_mm.hdr_grn where grnid=@grnid)
			update db_mm.grnbatchwise set confirmedby=@userid,confirmdate=getdate() from @grnbatchwise a where db_mm.grnbatchwise.id=a.id
			IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END


				--- insert data into supplier items table
				--if not exists(select itemid from db_mm.supplier_items where itemid in (select itemid from @grnbatchwise) and suplid=@suplid)
				--BEGIN
    --            insert into [db_mm].[supplier_items] ([suplid],[itemid],[brandid],[lastpurchaserate],[lastpurchasedate],[lastgrnid])
				--select @suplid,[itemid],[brandid],[itemrate],getdate(),@grnid from @grnbatchwise
				--end 
				--else 
				--begin 
				--update [db_mm].[supplier_items] set [lastpurchaserate] = (select [itemrate] from @grnbatchwise),
				--[lastpurchasedate] =(select createdon from [db_mm].[hdr_grn])
				--where itemid in (select itemid from @grnbatchwise) and suplid=@suplid
				 
				--END

					--- insert data into  items brand table
					--if not exists(select itemid from [db_mm].[item_brands]  where itemid in (select itemid from @grnbatchwise) and suplid=@suplid)
					update  brands set brandid=a.brandid,
					itemid=a.itemid,lastpurchasedate=getdate()
					--lastpurchaserate=a.itemrate 
					from  @grnbatchwise a
					join [db_mm].[item_brands] brands on brands.itemid=a.itemid
					



  ---update ststus in grn header
  if  (select count(*)  from [db_mm].[grnbatchwise] where confirmedby is null and  grnid=@grnid) = 0
	begin
	update [db_mm].[hdr_grn] set status ='C' where grnid = @grnid
	end
	IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
	--- insert data into stock transaction table
								
		INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[refid],[arnumber],[itemrate],[storeid],[fyid],
		 [qcdate],[qcby],[nextqcdate],[mfgdate],[expdate],[manufacturer],[supplier],[batch],[assay],[lod],[trntypeid],[trnoperator],[coid],[boid],createdby,createdon)
	    SELECT itemid,itemid,brandid,quantity-quantityrejected,@grnid,arnumber,(select itemrate from [db_mm].[dtl_grn] where itemid=a.itemid AND grnid=@grnid and brandid=a.brandid) ,(select storeid from [db_mm].[hdr_grn] where grnid=@grnid),
		1,[qcdate],[qcby],[nextqcdate],[mfgdate],expirydate,(select name from  db_mm.mst_brand where id=a.brandid),(select name from db_masters.supplier where id=@suplid),batchno,[assay],[lod],2,'+',@coid,@boid,@userid,getdate() FROM @grnbatchwise a
		IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
	--- update rectqty into purchase detail table
				
				update db_mm.dtl_purchaseorder 
				set receivedquantity=isnull(receivedquantity,0) + a.quantity from @grnbatchwise a
				where  db_mm.dtl_purchaseorder.itemid =a.itemid and  db_mm.dtl_purchaseorder.orderid =a.orderid and db_mm.dtl_purchaseorder.brandid=a.brandid
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
								
				---INSERT data INTO stock trn for sample qty issuance
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],refid,[trntypeid],[trnoperator],[storeid],[coid],[boid],createdby,createdon,arnumber,batch,remarks)
				SELECT (d.itemid),(d.itemid),(d.brandid),(d.sampleqty),@issuanceid,20,'-',1,@coid,@boid,1,getdate(),arnumber,batchno,'Sample For IQC' FROM @grnbatchwise d where d.sampleqty>0
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				 
				--set @dradvicerej = (select rejectedquantity FROM db_mm.hdr_grn  where grnid=@grnid) >1
				if (select count(*) FROM db_mm.grnbatchwise   where  quantityrejected > 0 and grnid=@grnid) >0
				begin
				 EXEC [db_mm].[pr_advicegenerationrejection]@grnid,1,1,1,1
				end
				if (select count(*) FROM db_mm.dtl_grn   where  quantityshortage > 0 and grnid=@grnid) >0
				begin
				 EXEC [db_mm].[pr_advicegenerationshortage]@grnid,1,1,1,1
				end
				if (select count(*) FROM db_mm.dtl_grn dt join db_mm.dtl_purchaseorder pd on  dt.orderid=pd.orderid and dt.itemid=pd.itemid where dt.itemrate-pd.itemrate>0  and grnid=@grnid) >0
				begin
				 EXEC [db_mm].[pr_advicegenerationratediffdr]@grnid,1,1,1,1
				end
                  commit
				  END






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

CREATE PROCEDURE [db_mm].[pr_savegrniqc] 
    @grnid int,
	@grnbatchwise [db_mm].[grnbatchwise_tvp] readonly,
	@userid int=1,
	@coid int,
	@boid int
AS

BEGIN 
declare @sql nvarchar(max)
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		
	BEGIN TRANSACTION
	update [db_mm].[grnbatchwise] set sampleqty = a.sampleqty,arnumber=a.arnumber,
	expirydate=a.expirydate,qcdate=a.qcdate,qcby=a.qcby,nextqcdate=a.nextqcdate,assay=a.assay,lod=a.lod,releasedate=getdate(),
	rejectionreasonid=a.rejectionreasonid,
	sampledate=a.sampledate,supplierretestdate=a.supplierretestdate,quantityrejected=a.quantityrejected
   from @grnbatchwise a where  a.grnid = [db_mm].[grnbatchwise].grnid 
   and [db_mm].[grnbatchwise].id=a.id
	if  (select count(*)  from [db_mm].[grnbatchwise] where qcby is null and  grnid=@grnid) = 0
	begin
	update [db_mm].[hdr_grn] set status ='Q' where grnid = @grnid
	end
	--------exec [db_mm].[pr_savegrnconfirmation]@grnid,@grnbatchwise,@userid,@coid,@boid
		commit
		END

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




CREATE PROCEDURE [db_mm].[pr_savegstmaster]
 @statementtype NVARCHAR(50),
@gstmaster [db_mm].[mst_gst_tvp] READONLY,
@userid INT = 1
AS

BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	BEGIN TRANSACTION
	DECLARE @gstid INT, @rowcnt int
	IF (@statementtype = 'Insert')
	BEGIN
	INSERT INTO [db_mm].[mst_gst] ([description],  [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		 [remarks], [coid], [boid],  [createdby], [createdon], saleacid,purchaseacid)
			SELECT [description],  [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		 [remarks], [coid], [boid],  [createdby], getdate()	, saleacid,purchaseacid FROM @gstmaster
				
			
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding INDENT header data.', 16, 1)
			RETURN
		END
	END
	ELSE
	BEGIN -- begin of update 
		-- fetching indent id from table type
		SELECT TOP 1
			@gstid = gstid
		FROM @gstmaster
		SELECT [description],  [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		  [coid], [boid]
		FROM db_mm.mst_gst
		WHERE gstid = @gstid
		EXCEPT
		SELECT [description], [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		  [coid], [boid]
		FROM @gstmaster
		--print @sql
		--EXEC sp_executesql @sql

		SELECT
			@rowcnt = @@rowcount
		-- data needs to update if query returns a row  
		IF @rowcnt > 0
		BEGIN -- begin of row count
			-- insert records in bkup and checking @@ERROR 
			INSERT INTO CloudERPbklog.db_mm.mst_gst ([gstid],[description], [hsncode], [code], [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		 [remarks], [coid], [boid],  [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby],[concessionaligst],[concessionalcgst],[concessionalsgst]
		, [deactivatedon])
				SELECT @gstid, [description], [hsncode], [code], [igst], [cgst]
		, [sgst],[cess],[igstinputacid],[cgstinputacid],[sgstinputacid],[cessinputacid],[igstoutputacid],[cgstoutputacid],[sgstoutputacid],[cessoutputacid],
		 [remarks], [coid], [boid],  [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby],[concessionaligst],[concessionalcgst],[concessionalsgst]
		, [deactivatedon]
				FROM db_mm.mst_gst 
				WHERE gstid = @gstid
			--print @sql
			--EXEC sp_executesql @sql
			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			END
			-- updating existing records from supplier table and checking @@ERROR 
			UPDATE db_mm.mst_gst
			SET 
			[description]=a.[description],
			[igst]=a.[igst],
			[cgst]=a.[cgst],
		    [sgst]=a.[sgst],
			[cess]=a.[cess],
			[igstinputacid]=a.[igstinputacid],
            [cgstinputacid]=a.[cgstinputacid],
			[sgstinputacid]=a.[sgstinputacid],
			[cessinputacid]=a.[cessinputacid],
			[igstoutputacid]=a.[igstoutputacid],
			[cgstoutputacid]=a.[cgstoutputacid],
			[sgstoutputacid]=a.[sgstoutputacid],
			[cessoutputacid]=a.[cessoutputacid],
			saleacid=a.[saleacid],
			purchaseacid=a.[purchaseacid],
			[modifiedby]=a.[createdby], 
			[modifiedon]=getdate()
			FROM @gstmaster a
			WHERE  db_mm.mst_gst.gstid= a.gstid
			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating existing indent record.', 16, 1)
				RETURN
			END
		END -- end of row coun
	END
	COMMIT

END


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




CREATE PROCEDURE [db_mm].[pr_savehsnmaster]
 @statementtype NVARCHAR(50),
 @coid int ,
 @boid int,
 @hsncode varchar(20),
 @gstid int ,
 @hsnid int=null,
 @cocnid int ,
@userid INT = 1
AS

BEGIN
	SET NOCOUNT ON;
	IF (@statementtype = 'Insert')
	BEGIN
	INSERT INTO [db_mm].[mst_hsn] ([hsncode],[gstid], [Concessionaltaxid],[coid], [boid],  [createdby], [createdon])
			values(@hsncode,@gstid,@cocnid,@coid,@boid,@userid,getdate())
		
	END
	IF (@statementtype = 'Update')
	BEGIN 
			UPDATE db_mm.mst_hsn
			SET 
			[hsncode]=@hsncode,			
			[gstid]=@gstid,
			[Concessionaltaxid]=@cocnid
			WHERE  id= @hsnid

			
END
end

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




create PROCEDURE [db_mm].[pr_saveindent]
 @statementtype NVARCHAR(50),
@indentheader [db_mm].[hdr_indent_tvp] READONLY,
@indentdetail [db_mm].[dtl_indent_tvp] READONLY,
@userid INT = 1
AS

BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @indentid INT
		   ,@rowcnt INT
		   ,@colstring NVARCHAR(MAX)
		   ,@sql NVARCHAR(MAX)
	DECLARE @indentnumber INT
	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN
	set @indentnumber = (SELECT ISNULL(MAX(indentnumber), 0) + 1 FROM db_mm.hdr_indent )


		INSERT INTO [db_mm].[hdr_indent] ([indentdate], [indentnumber], [indentpriority], [indentorid], [departmentid]
		, [billingdescription], [remarks], [costcentreid], [coid], [boid], [isactive], [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby]
		, [deactivatedon], [manualslipno], [isjobwork],[productid],[bomid],[lotsize],[fyid])
			SELECT
				[indentdate]
			   ,@indentnumber
			   ,[indentpriority]
			   ,[indentorid]
			   ,[departmentid]
			   ,[billingdescription]
			   ,[remarks]
			   ,[costcentreid]
			   ,[coid]
			   ,[boid]
			   ,[isactive]
			   ,[createdby]
			   ,[createdon]
			   ,[modifiedby]
			   ,[modifiedon]
			   ,[deactivatedby]
			   ,[deactivatedon]
			   ,[manualslipno]
			   ,[isjobwork]
			   ,[productid],[bomid],[lotsize],[fyid]
			FROM @indentheader
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding INDENT header data.', 16, 1)
			RETURN
		END
		SELECT
			@indentid = SCOPE_IDENTITY()
		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while getting indent id.', 16, 1)
			RETURN
		END


		INSERT INTO [db_mm].[dtl_indent] ([indentid], [itemid], [quantityrequired], [quantityapproved], [quantitywoff]
		, [suplname], [itemrate], [poid], [coid], [boid], [approvedby], [approvedon], [deactivatedby], [deactivatedon], [brandid], [remarks], [requiredby])
			SELECT
				@indentid
			   ,[itemid]
			   ,[quantityrequired]
			   ,[quantityapproved]
			   ,[quantitywoff]
			   ,[suplname]
			   ,[itemrate]
			   ,[poid]
			   ,[coid]
			   ,[boid]
			   ,[approvedby]
			   ,[approvedon]
			   ,[deactivatedby]
			   ,[deactivatedon]
			   ,[brandid]
			   ,[remarks]
			   ,[requiredby]
			FROM @indentdetail
	END
	ELSE
	BEGIN -- begin of update 
		-- fetching indent id from table type
		SELECT TOP 1
			@indentid = indentid
		FROM @indentheader

		SELECT
			[indentdate]
		   ,[indentnumber]
		   ,[indentpriority]
		   ,[indentorid]
		   ,[departmentid]
		   ,[billingdescription]
		   ,[remarks]
		   ,[costcentreid]
		   ,[coid]
		   ,[boid]
		   ,[isactive]
		   ,[createdby]
		   ,[createdon]
		   ,[modifiedby]
		   ,[modifiedon]
		   ,[deactivatedby]
		   ,[deactivatedon]
		   ,[manualslipno]
		   ,[isjobwork],
		   [productid],[bomid],[lotsize]
		FROM db_mm.hdr_indent
		WHERE indentid = @indentid
		EXCEPT
		SELECT
			[indentdate]
		   ,[indentnumber]
		   ,[indentpriority]
		   ,[indentorid]
		   ,[departmentid]
		   ,[billingdescription]
		   ,[remarks]
		   ,[costcentreid]
		   ,[coid]
		   ,[boid]
		   ,[isactive]
		   ,[createdby]
		   ,[createdon]
		   ,[modifiedby]
		   ,[modifiedon]
		   ,[deactivatedby]
		   ,[deactivatedon]
		   ,[manualslipno]
		   ,[isjobwork]
		   ,[productid],[bomid],[lotsize]
		FROM @indentheader

		--print @sql
		--EXEC sp_executesql @sql

		SELECT
			@rowcnt = @@rowcount
		-- data needs to update if query returns a row  
		IF @rowcnt > 0
		BEGIN -- begin of row count
			-- insert records in bkup and checking @@ERROR 
			INSERT INTO CloudERPbklog.db_mm.hdr_indent ([indentid], [indentdate], [indentnumber], [indentpriority], [indentorid], [departmentid]
			, [billingdescription], [remarks], [costcentreid], [coid], [boid], [isactive], [createdby], [createdon], [modifiedon], [deactivatedby]
			, [deactivatedon], [manualslipno], [isjobwork], [modifiedby],[productid],[bomid],[lotsize])
				SELECT
					[indentid]
				   ,[indentdate]
				   ,[indentnumber]
				   ,[indentpriority]
				   ,[indentorid]
				   ,[departmentid]
				   ,[billingdescription]
				   ,[remarks]
				   ,[costcentreid]
				   ,[coid]
				   ,[boid]
				   ,[isactive]
				   ,[createdby]
				   ,[createdon]
				   ,[modifiedon]
				   ,[deactivatedby]
				   ,[deactivatedon]
				   ,[manualslipno]
				   ,[isjobwork]
				   ,@userid,
				   [productid],[bomid],[lotsize]
				FROM db_mm.hdr_indent
				WHERE indentid = @indentid

			--print @sql

			--EXEC sp_executesql @sql

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			END
			-- updating existing records from supplier table and checking @@ERROR 
			UPDATE db_mm.hdr_indent
			SET [indentdate] = a.[indentdate]
			   ,[indentnumber] = a.[indentnumber]
			   ,[indentpriority] = a.[indentpriority]
			   ,[indentorid] = a.[indentorid]
			   ,[departmentid] = a.[departmentid]
			   ,[billingdescription] = a.[billingdescription]
			   ,[remarks] = a.[remarks]
			   ,[costcentreid] = a.[costcentreid]
			   ,[coid] = a.[coid]
			   ,[boid] = a.[boid]
			   ,[isactive] = a.[isactive]
			   ,[createdby] = a.[createdby]
			   ,[createdon] = a.[createdon]
			   ,[modifiedby] = a.[modifiedby]
			   ,[modifiedon] = a.[modifiedon]
			   ,[deactivatedby] = a.[deactivatedby]
			   ,[deactivatedon] = a.[deactivatedon]
			   ,[productid]=a.[productid]
			   ,[bomid]=a. [bomid],
			  [lotsize]=a. [lotsize]
			FROM @indentheader a
			WHERE  db_mm.hdr_indent.indentid= a.indentid 

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating existing indent record.', 16, 1)
				RETURN
			END
		END -- end of row count
		ELSE -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
		BEGIN
			IF NOT EXISTS (SELECT
						indentid
					FROM CloudERPbklog.db_mm.hdr_indent
					WHERE indentid = @indentid)
			BEGIN
				-- insert data in INDENT HEADER table and checking @@ERROR 
				INSERT INTO CloudERPbklog.db_mm.hdr_indent ([indentid],[indentdate], [indentnumber], [indentpriority], [indentorid], [departmentid]
				, [billingdescription], [remarks], [costcentreid], coid, boid, [isactive], [createdby], [createdon], [modifiedby], [modifiedon], [deactivatedby]
				, [deactivatedon],[productid],[bomid],[lotsize])
					SELECT
					     [indentid]
						,[indentdate]
					   ,[indentnumber]
					   ,[indentpriority]
					   ,[indentorid]
					   ,[departmentid]
					   ,[billingdescription]
					   ,[remarks]
					   ,[costcentreid]
					   ,[coid]
					   ,[boid]
					   ,[isactive]
					   ,[createdby]
					   ,[createdon]
					   ,[modifiedby]
					   ,[modifiedon]
					   ,[deactivatedby]
					   ,[deactivatedon]
					    ,[productid],[bomid],[lotsize]
					FROM db_mm.hdr_indent
					WHERE indentid = @indentid
				-- Rollback the transaction if there were any errors
				IF @@error <> 0
				BEGIN
					-- Rollback the transaction
					ROLLBACK
					-- Raise an error and return
					RAISERROR ('Error while adding indent data.', 16, 1)
					RETURN
				END
			END
		END

		SELECT
		    [itemid]
		   ,[quantityrequired]
		   ,[quantityapproved]
		   ,[quantitywoff]
		   ,[suplname]
		   ,[itemrate]
		   ,[poid]
		   ,[coid]
		   ,[boid]
		   ,[approvedby]
		   ,[approvedon]
		   ,[deactivatedby]
		   ,[deactivatedon]
		    ,[brandid]
			   ,[remarks]
			   ,[requiredby]
		FROM @indentdetail
		EXCEPT
		SELECT
		   [itemid]
		   ,[quantityrequired]
		   ,[quantityapproved]
		   ,[quantitywoff]
		   ,[suplname]
		   ,[itemrate]
		   ,[poid]
		   ,[coid]
		   ,[boid]
		   ,[approvedby]
		   ,[approvedon]
		   ,[deactivatedby]
		   ,[deactivatedon]
		    ,[brandid]
			   ,[remarks]
			   ,[requiredby]
		   FROM [db_mm].[dtl_indent]
		WHERE [indentid] = @indentid
		

		--EXEC sp_executesql @sql

		SELECT
			@rowcnt = @@rowcount
		-- data needs to update if query returns a row  
		IF @rowcnt > 0
		BEGIN -- begin of row count
			-- insert records in bkup and checking @@ERROR 
			INSERT INTO CloudERPbklog.db_mm.dtl_indent ([indentid], [itemid], [quantityrequired], [quantityapproved], [quantitywoff]
			, [suplname], [itemrate], [poid], [coid], [boid], [approvedby], [approvedon], [deactivatedby], [deactivatedon],[brandid],[remarks]
			   ,[requiredby])
				SELECT
					@indentid
				   ,[itemid]
				   ,[quantityrequired]
				   ,[quantityapproved]
				   ,[quantitywoff]
				   ,[suplname]
				   ,[itemrate]
				   ,[poid]
				   ,[coid]
				   ,[boid]
				   ,[approvedby]
				   ,[approvedon]
				   ,[deactivatedby]
				   ,[deactivatedon]
				    ,[brandid]
			   ,[remarks]
			   ,[requiredby]
				FROM db_mm.dtl_indent
				WHERE [indentid] = @indentid

			--print @sql

			--EXEC sp_executesql @sql

			-- Rollback the transaction if there were any errors
			IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating log enteries.', 16, 1)
				RETURN
			END
			DELETE FROM db_mm.dtl_indent
			WHERE [indentid] = @indentid

			INSERT INTO db_mm.dtl_indent ([indentid],[itemid], [quantityrequired], [quantityapproved], [quantitywoff]
			, [suplname], [itemrate], [poid], [coid], [boid], [approvedby], [approvedon], [deactivatedby], [deactivatedon],[brandid]
			   ,[remarks]
			   ,[requiredby])
				SELECT
				    @indentid
					,[itemid]
				   ,[quantityrequired]
				   ,[quantityapproved]
				   ,[quantitywoff]
				   ,[suplname]
				   ,[itemrate]
				   ,[poid]
				   ,[coid]
				   ,[boid]
				   ,[approvedby]
				   ,[approvedon]
				   ,[deactivatedby]
				   ,[deactivatedon]
				    ,[brandid]
			   ,[remarks]
			   ,[requiredby]
				FROM @indentdetail
			-- Rollback the transaction if there were any errors
		IF @@error <> 0
			BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while updating existing indent detail record.', 16, 1)
				RETURN
			END
		END -- end of row count
	END
	COMMIT

END




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


/****** Object:  StoredProcedure [db_mm].[pr_saveindentpassing]    Script Date: 2/15/2019 2:59:22 AM ******/

 
--- EXEC [db_mm].[pr_saveindentpassing]1,1,1,4,21,6.523,1
CREATE PROCEDURE [db_mm].[pr_saveindentpassing]
    @coid int,
	@boid int,
	@userid int,
	@indentid int,
	@itemid int,
	@qtyapproved decimal(15,3),
	@woffqty decimal(15,3),
	@brandid int

AS

BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
	 
	update [db_mm].[dtl_indent]
	SET
	[approvedby]=@userid,
	[quantityapproved]=isnull(quantityapproved,0)+@qtyapproved,
	[quantitywoff]=isnull(@woffqty,0)
	WHERE [db_mm].[dtl_indent].indentid=@indentid
	AND [db_mm].[dtl_indent].itemid=@itemid
	
    
	
	end

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



CREATE  PROCEDURE [db_mm].[pr_saveinwardnote] 
    @statementtype nvarchar(50),
	@inwardnoteheader [db_mm].[hdr_inwardnote_tvp] readonly,
	@inwardnotedetail [db_mm].[dtl_inwardnote_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @noteid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@grnid int,@gstid int,@igstamt decimal,
		@voucherno int,@grnno int,@grndate date
		declare @notenumber int
	BEGIN TRANSACTION
	If (@statementtype='new')
		Begin
		set @notenumber = (SELECT ISNULL(MAX(noteno), 0) + 1 FROM db_mm.hdr_inwardnote)
		
		
		    insert into [db_mm].[hdr_inwardnote] ([noteno],[notedate],[notetype],[billno],[billdate],[partyacid],[purchaseacid],[inwardid],[drcrvoucherno],[amount],[coid],[boid],[remarks],[createdby],[createdon],[fyid])
			Select @notenumber,[notedate],[notetype],[billno],[billdate],[partyacid],[purchaseacid],[inwardid],[drcrvoucherno],[amount],[coid],[boid],[remarks],[createdby],[createdon],[fyid] from @inwardnoteheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding inwardnote header data.', 16, 1)
				RETURN
				END
				SELECT @noteid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				
		        insert into [db_mm].[dtl_inwardnote] ([noteid],[itemid],[adviceid],[rate],[quantity],[amount],[igstamount],[cgstamount],[sgstamount],[reference])
				select @noteid,[itemid],[adviceid],[rate],[quantity],[amount],[igstamount],[cgstamount],[sgstamount],[reference]
				from @inwardnotedetail

				select top 1 @grnid =inwardid from @inwardnoteheader
				select @grnno= grnnumber from  db_mm.hdr_grn where grnid=@grnid
				select top 1 @gstid=gstid from db_mm.dtl_grn where grnid=@grnid
				select top 1 @igstamt=igstamount from db_mm.hdr_grn where grnid=@grnid
				select @grndate= createdon from  db_mm.hdr_grn where grnid=@grnid
				select @voucherno= isnull(max(voucherno),0)+1 from [db_accounts].[voucher] where vouchercategory='P' 
		select @sql='insert into [db_accounts].[voucher]([voucherno],[rowno],[voucherdate],[voucheramount],[vouchertype],[vouchercategory],[accountid],
				[drcr],
				[narration],[refid],[isconfirm],[trntype],[oppositeacid],[fyid],[coid],[boid],[userid])
				select 2013 as voucherno,1,getdate(),(select billamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + ' ),''J'',''P'',
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1
				union all select 2013 as voucherno,1,getdate(),(select billamount-igstamount-cgstamount-sgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1'
			   if (@igstamt>0)
			   begin 
				set @sql += ' union all  select 2013 as voucherno,1,getdate(),(select igstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 '
				end 
				else 
				begin
				set @sql += ' union all  select 2013 as voucherno,1,getdate(),(select cgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 
				 union all  select 2013 as voucherno,1,getdate(),(select sgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 '
				end
				
	            EXEC sp_executesql @SQL
				---INSERT data INTO stock trn
				--INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[remarks],[storeid],[coid],[boid],isactive,createdby,createdon)
				--SELECT [itemid],[itemid],[quantity],case when (select trntype from @inwardnoteheader)='I' then  13 else 12 end,case when (select trntype from @inwardnoteheader)='I' 
				--then  '-' else '+' end,case when (select trntype from @inwardnoteheader)='I' then  'stock transfer out' else 'stock transfer in' end,
				--(SELECT [receivingstoreid] FROM @inwardnoteheader),(SELECT coid FROM @inwardnoteheader),(SELECT boid FROM @inwardnoteheader),1,@userid,getdate () FROM @inwardnotedetail
				end 
	else
	Begin -- begin of update .
		select top 1 @grnid =inwardid from @inwardnoteheader
				select top 1 @gstid=gstid from db_mm.dtl_grn where grnid=@grnid
				select top 1 @igstamt=igstamount from db_mm.hdr_grn where grnid=@grnid
		select @sql='insert into [db_accounts].[voucher]([voucherno],[rowno],[voucherdate],[voucheramount],[vouchertype],[vouchercategory],[accountid],
				[drcr],
				[narration],[refid],[isconfirm],[trntype],[oppositeacid],[fyid],[coid],[boid],[userid])
				select 2013 as voucherno,1,getdate(),(select billamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + ' ),''J'',''P'',
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1
				union all select 2013 as voucherno,1,getdate(),(select billamount-igstamount-cgstamount-sgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1'
			   if (@igstamt>0)
			   begin 
				set @sql += ' union all  select 2013 as voucherno,1,getdate(),(select igstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 '
				end 
				else 
				begin
				set @sql += ' union all  select 2013 as voucherno,1,getdate(),(select cgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 
				 union all  select 2013 as voucherno,1,getdate(),(select sgstamount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@grnid as varchar(5)) + ',0,123,
				(select suplid from db_mm.hdr_grn where grnid=' + cast(@grnid as varchar(5)) + '),1,1,1,1 '
				end
				
	            EXEC sp_executesql @SQL
			
			END
								COMMIT
								
								
								END

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



CREATE PROCEDURE [db_mm].[pr_saveissuance] 
    @statementtype nvarchar(50),
	@issuanceheader [db_mm].[hdr_issuance_tvp] readonly,
	@issuancedetail [db_mm].[dtl_issuance_tvp] readonly,
	@issuancebatchwise [db_mm].[issuancebatchwise_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @issuanceid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		declare @issuanceno int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		set @issuanceno = (SELECT ISNULL(MAX(issuanceno),0) + 1 FROM db_mm.hdr_issuance)
		
		
		insert into [db_mm].[hdr_issuance]([issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[batchmfgdate],[batchexpirydate],[collectedby])
			Select  @issuanceno,[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[batchmfgdate],[batchexpirydate],[collectedby] from @issuanceheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding issuance header data.', 16, 1)
				RETURN
				END
				SELECT @issuanceid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				---insert data into issuancebatchwise
				--insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				--select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod]  from @issuancebatchwise
					if   exists(select 1 from @issuancebatchwise) 
				begin
				insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod]  from @issuancebatchwise where issuedquantity > 0
			    
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[refid],[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  FROM @issuancebatchwise  where issuedquantity > 0
				 
				 insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod] from @issuancedetail  where itemid  not in (select itemid from @issuancebatchwise)
					INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[refid],[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  from @issuancedetail  where itemid  not in (select itemid from @issuancebatchwise) and issuedquantity > 0
				end 
				ELSE
				begin
               insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod]  from @issuancedetail where issuedquantity > 0

				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],refid,[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  from @issuancedetail
			
				end
				
				insert into [db_mm].[dtl_issuance] ([issuanceid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks])
				select  @issuanceid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks]
				from @issuancedetail				
               ---UPDATE db_mm.dtl_requisition  SET issuedquantity=ISNULL(issuedquantity,0)+(SELECT [issuedquantity] FROM @issuancedetail WHERE 
				--db_mm.dtl_requisition.itemid IN (SELECT itemid FROM @issuancedetail) AND db_mm.dtl_requisition.reqnid=(SELECT TOP 1 reqnid FROM @issuanceheader)) 
				--update issued quantity in requisition detail
		  --     
		  --UPDATE db_mm.dtl_requisition  SET issuedquantity=ISNULL(issuedquantity,0)+(SELECT [issuedquantity] FROM @issuancedetail d WHERE 
				--db_mm.dtl_requisition.itemid =d.itemid AND db_mm.dtl_requisition.reqnid=(SELECT TOP 1 reqnid FROM @issuanceheader)) 
			

			 UPDATE db_mm.dtl_requisition  SET issuedquantity=ISNULL(db_mm.dtl_requisition.issuedquantity,0)+(SELECT d.[issuedquantity]) from @issuancedetail d WHERE 
				db_mm.dtl_requisition.itemid =d.itemid AND db_mm.dtl_requisition.reqnid=(SELECT TOP 1 reqnid FROM @issuanceheader)
				end 
				else
				Begin -- begin of update 
			-- fetching issuance id from table type
			select top 1 @issuanceid = issuanceid from @issuanceheader

			SELECT [issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]
				from db_mm.hdr_issuance where issuanceid = @issuanceid
				 EXCEPT select  [issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]
				 from @issuanceheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_issuance ([issuanceid],[issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select [issuanceid], [issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_issuance where issuanceid = @issuanceid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_issuance  set 
                           [reqnid] =a.[reqnid],
                           [reqnno]=a.[reqnno],
                           [batchno]=a.[batchno],
                           [deptid]=a.[deptid],
                           [costcentreid]=a.[costcentreid],
                           [storeid]=a.[storeid],
                           [manualslipno]=a.[manualslipno],
                           [issuancedate]=a.[issuancedate],
                           [remarks]=a.[remarks],
                           [coid]=a.[coid],
                           [boid]=a.[boid],
                           [confirmedby]=a.[confirmedby],
                           [createdby] =a.[createdby],
                           [createdon] =a.[createdon],
                           [modifiedby] =a.[modifiedby],
                           [modifiedon]=a.[modifiedon],
                           [fyid] =a.[fyid]
					FROM   @issuanceheader a
					WHERE db_mm.hdr_issuance.issuanceid= a.issuanceid 
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing requisition record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select issuanceid from CloudERPbklog.db_mm.hdr_issuance where issuanceid = @issuanceid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_issuance([issuanceid], [issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid])
			                Select [issuanceid], [issuanceno],[reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[issuancedate],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_issuance where issuanceid = @issuanceid
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding issuance data.', 16, 1)
								RETURN
								END
										END
				End
			
			 SELECT [issuanceid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks]
			 from [db_mm].[dtl_issuance] where [issuanceid] =@issuanceid 
			 EXCEPT select @issuanceid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks]
			 from @issuancedetail
			 UNION  select @issuanceid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks]
			 from @issuancedetail
			 EXCEPT select [issuanceid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks]
			 from [dtl_issuance] where [issuanceid] =@issuanceid 

			
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_issuance ([issuanceid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks])
					Select @issuanceid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks] from cloudERP.db_mm.dtl_issuance where [issuanceid] = @issuanceid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_issuance where [issuanceid] = @issuanceid
				
                insert into db_mm.dtl_issuance([issuanceid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks])
					SELECT @issuanceid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[remarks] from @issuancedetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing issuance detail record.', 16, 1)
							RETURN
						END

				DELETE FROM db_mm.issuancebatchwise where @issuanceid=@issuanceid
				delete from [db_mm].[item_stk_trn] where refid=@issuanceid and trntypeid=5
					if   exists(select 1 from @issuancebatchwise) 
				begin
				insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod]  from @issuancebatchwise where issuedquantity > 0
			    
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[refid],[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  FROM @issuancebatchwise  where issuedquantity > 0
				 
				 insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod] from @issuancedetail  where itemid  not in (select itemid from @issuancebatchwise)
					INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],[refid],[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  from @issuancedetail  where itemid  not in (select itemid from @issuancebatchwise) and issuedquantity > 0
				end 
				ELSE
				begin
               insert into [db_mm].[issuancebatchwise]([issuanceid],[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod])
				select @issuanceid,[itemid],[issuedquantity],[brandid],[arno],[batchno],[expirydate],[mfgdate],[storeid],[assay],[lod]  from @issuancedetail where issuedquantity > 0

				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[itemquantity],refid,[trntypeid],[trnoperator],[storeid],[coid],[boid],isactive,createdby,createdon,[arnumber],[batch],[expdate],[mfgdate],[assay],[lod] )
				SELECT [itemid],[itemid],[brandid],[issuedquantity],@issuanceid,5,'-',[storeid],(SELECT coid FROM @issuanceheader),(SELECT boid FROM @issuanceheader),1,@userid,getdate (),[arno],[batchno],[expirydate],[mfgdate],[assay],[lod]  from @issuancedetail
			
				end
						
						
						END  
			            END
					    commit
					    END

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



CREATE  PROCEDURE [db_mm].[pr_saveissuereturn] 
    @statementtype nvarchar(50),
	@issuereturnheader [db_mm].[hdr_issuereturn_tvp] readonly,
	@issuereturndetail [db_mm].[dtl_issuereturn_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @issuereturnid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		declare @issuereturnnumber int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		set @issuereturnnumber = (SELECT ISNULL(MAX(issuereturnno), 0) + 1 FROM db_mm.hdr_issuereturn)
		
		
		insert into [db_mm].[hdr_issuereturn] ([issuereturnno],[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid])
			Select @issuereturnnumber,[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from @issuereturnheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding issuereturn header data.', 16, 1)
				RETURN
				END
				SELECT @issuereturnid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				
				
				insert into [db_mm].[dtl_issuereturn] ([issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason])
				select @issuereturnid,[itemid],[quantityreturned],[arno],[batch], [returnreason]
				from @issuereturndetail
				--insert data into stock trn
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[remarks],[arnumber],[batch],
				[storeid],[coid],[boid],isactive,createdby,createdon)
				SELECT [itemid],[itemid],[quantityreturned],7,'+','SHOP RETURN',[arno],[batch],
				(SELECT [storeid] FROM @issuereturnheader),(SELECT coid FROM @issuereturnheader),(SELECT boid FROM @issuereturnheader),1,@userid,getdate () FROM @issuereturndetail



				end 
	else
		Begin -- begin of update 
			-- fetching indent id from table type
			select top 1 @issuereturnid = @issuereturnid from @issuereturnheader

			select [issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]
				from db_mm.hdr_issuereturn where issuereturnid = @issuereturnid
				 EXCEPT select [issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] 
				 from @issuereturnheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_issuereturn ([issuereturnid],[issuereturnno],[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select @issuereturnid,[issuereturnno],[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_issuereturn where issuereturnid = @issuereturnid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_issuereturn   set 
					          [issuanceid]= a.[issuanceid],
                              [departmentid]=a.[departmentid],
                              [storeid]=a.[storeid],
                              [costcentreid]=a.[costcentreid],
                              [remarks]=a.[remarks],
                              [coid]=a.[coid],
                             [boid]=a.[boid],
                            [createdby]=a.[createdby],
                             [createdon]=a.[createdon],
                            [modifiedby]=a.[modifiedby],
                            [modifiedon]=a.[modifiedon],
							[fyid]=a.[fyid]
					FROM   @issuereturnheader a
					WHERE  db_mm.hdr_issuereturn.issuereturnid =a.issuereturnid 
					
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing issuereturn record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select issuereturnid from CloudERPbklog.db_mm.hdr_issuereturn where issuereturnid = @issuereturnid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
						insert into CloudERPbklog.db_mm.hdr_issuereturn ([issuereturnid],[issuereturnno],[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select @issuereturnid,[issuereturnno],[issuanceid],[departmentid],[storeid],[costcentreid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_issuereturn where issuereturnid = @issuereturnid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding issuereturn data.', 16, 1)
								RETURN
	            End
		        End
				End
			
			select [issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason]
			from [db_mm].[dtl_issuereturn] where issuereturnid =@issuereturnid
			EXCEPT 
			SELECT[issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason]
			from @issuereturndetail
			union 
			SELECT [issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason]
			from @issuereturndetail
			EXCEPT 
			select [issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason]
			from [db_mm].[dtl_issuereturn] where issuereturnid =@issuereturnid
			
			       

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_issuereturn ([issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason])
					SELECT @issuereturnid,[itemid],[quantityreturned],[arno],[batch], [returnreason] from db_mm.dtl_issuereturn where issuereturnid = @issuereturnid

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_issuereturn where issuereturnid = @issuereturnid
				
                insert into db_mm.dtl_issuereturn([issuereturnid],[itemid],[quantityreturned],[arno],[batch], [returnreason])
					SELECT @issuereturnid,[itemid],[quantityreturned],[arno],[batch], [returnreason] from @issuereturndetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing issuereturn detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								COMMIT
								
								
								END

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

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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_accounts].[pr_manageGLAccountHeads] 'testxcz',1,1,1,1,10,0,1,'','Insert'
-- =============================================
CREATE PROCEDURE [db_mm].[pr_saveitemcategory] 
	@categorycode varchar(2),
	@categoryname  varchar(80),	
	@isactive bit,
	@parentcategoryid int,
	@purchaseitem	bit,
	@saleitem	bit,
	@coid int,
	@boid int,
	@userid int,
	@id int,
	@statementtype varchar(250) =null,
	@dimenstionarray as [db_mm].[dtl_catgdimension_tvp] readonly
AS
BEGIN
	SET NOCOUNT ON;
	
IF (@statementtype='Insert')
begin
	
INSERT INTO [db_mm].[mst_itemcategory]
        ([name],[categorycode],[parentid],[isactive],[boid],[coid],[createdby],[createdon],[issaleitem],[ispurchaseitem])
     VALUES
        (@categoryname,@categorycode,@parentcategoryid,@isactive,@boid,@coid,@userid,getdate(),@saleitem,@purchaseitem)
		declare @catgid int =@@identity

		----for calc. wt at time of BOM (add by mohit 2019-11-06)

		insert into [db_mm].[dtl_categorywise_dimension_mapping]
		(coid,boid,categoryid,dimensionid,isactive,createdby,createdon)
		select @coid,@boid,@catgid,dimensionid,@isactive,@userid,getdate() from @dimenstionarray
END
IF (@statementtype='Update')
BEGIN
	update [db_mm].[mst_itemcategory] set name = @categoryname,categorycode = @categorycode, parentid=@parentcategoryid, isactive=@isactive, modifiedby =@userid, 
	modifiedon=getdate(), issaleitem=@saleitem, ispurchaseitem=@purchaseitem where id = @id

	delete from [db_mm].[dtl_categorywise_dimension_mapping] where categoryid=@id

	insert into [db_mm].[dtl_categorywise_dimension_mapping]
		(coid,boid,categoryid,dimensionid,isactive,createdby,createdon,modifiedby,modifiedon)
		select @coid,@boid,@id,dimensionid,@isactive,createdby,getdate(),@userid,getdate() from @dimenstionarray
end
select * from [db_mm].[mst_itemcategory]

END



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



CREATE PROCEDURE [db_mm].[pr_savenrgp] 
    @statementtype nvarchar(50),
	@nrgpheader [db_mm].[hdr_nrgp_tvp] readonly,
	@nrgpdetail [db_mm].[dtl_nrgp_tvp] readonly,
	@userid int
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @nrgpid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@nrgpno int
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
			set @nrgpno = (SELECT ISNULL(MAX(nrgpno),0) + 1 FROM db_mm.hdr_nrgp)
		
		
		insert into [db_mm].[hdr_nrgp] ([nrgpno],[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon])
			SELECT @nrgpno,[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon] from @nrgpheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding nrgp header data.', 16, 1)
				RETURN
				END
				SELECT @nrgpid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting nrgp id.', 16, 1)
				RETURN
				END
				
				
				insert into [db_mm].[dtl_nrgp] ([nrgpid],[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount])
				select @nrgpid,[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount]
				from @nrgpdetail
				end 
				else
				Begin -- begin of update 
			-- fetching nrgp id from table type
			select top 1 @nrgpid = nrgpid from @nrgpheader

			select [partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress]
				from db_mm.hdr_nrgp where nrgpid = @nrgpid
				 EXCEPT select [partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress]
				 from @nrgpheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_nrgp ([nrgpno],[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon]) 
					SELECT @nrgpid,[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon] from db_mm.hdr_nrgp where nrgpid = @nrgpid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_nrgp  
					set
		           [partyid]=a.[partyid],
                   [invid]=a.[invid],
                   [invno]=a. [invno],
                   [invdate]=a.[invdate],
                   [outtime]=a.[outtime],
                   [transportid]=a.[transportid],
                   [vehicletypeid]=a.[vehicletypeid],
                   [vehiclename]=a.[vehiclename],
                   [vehicleno]=a.[vehicleno],
                   [employeeid]=a.[employeeid],
                   [deptid]=a.[deptid],
                   [storeid]=a.[storeid],
                   [remarks]=a.[remarks],
                   [modifiedby]=@userid,
                   [modifiedon]=getdate(),
                   [deliveryaddress]=a.[deliveryaddress]
                   FROM   @nrgpheader a
					WHERE db_mm.hdr_nrgp.nrgpid= a.nrgpid 

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing nrgp record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select nrgpid from CloudERPbklog.db_mm.hdr_nrgp where nrgpid = @nrgpid)
						begin
							-- insert data in nrgp HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_nrgp ([nrgpno],[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon]) 
					        SELECT [nrgpno],[partyid],[invid],[invno],[invdate],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon] from db_mm.hdr_nrgp where nrgpid = @nrgpid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding nrgp data.', 16, 1)
								RETURN
								END
										end
				End
			
			select [itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount]
			 from [db_mm].[dtl_nrgp] where nrgpid =@nrgpid				 
			 EXCEPT select [itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount]
				from @nrgpdetail
			
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_nrgp ([nrgpid],[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount])
					SELECT @nrgpid,[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount] from db_mm.dtl_nrgp where nrgpid = @nrgpid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_nrgp where [nrgpid]= @nrgpid
				
                insert into db_mm.dtl_nrgp([nrgpid],[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount])
					Select @nrgpid,[itemid],[quantity],[amount],[itemuom],[rate],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount] from @nrgpdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing nrgp detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								commit
								
								END

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



CREATE PROCEDURE [db_mm].[pr_savepackingbom] 
    @statementtype nvarchar(50),
	@bomheader [db_mm].[hdr_bom_tvp] readonly,
	@bomdetail [db_mm].[dtl_bom_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @bomid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
		
		insert into [db_mm].[hdr_pbom] ([productid],[version],[createdby],[createdon],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize])
			Select [productid],[version],[createdby],[createdon],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize] from @bomheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding bom header data.', 16, 1)
				RETURN
				END
				SELECT @bomid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting bom id.', 16, 1)
				RETURN
				END
				
				
				insert into [db_mm].[dtl_pbom] ([pbomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[length],[width])
				select @bomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid],[length],[width]
				from @bomdetail
				end 
				else
				Begin -- begin of update 
			-- fetching bom id from table type
			select top 1 @bomid = bomid from @bomheader

			select [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]
				from db_mm.hdr_pbom where pbomid = @bomid
				 EXCEPT select  [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]
				 from @bomheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_pbom ([productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]) 
					SELECT [productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize] from db_mm.hdr_bom where bomid = @bomid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_pbom   set 
					    
[productid]=a.[productid],
[version]=a.[version],
[createdby]=a.[createdby],
[createdon]=a.[createdon],
[revisedby]=a.[revisedby],
[revisedon]=a.[revisedon],
[revisedreason]=a.[revisedreason],
[amendedby]=a.[amendedby],
[amendedon]=a.[amendedon],
[amendentmentreason]=a.[amendentmentreason],
[confirmedby]=a.[confirmedby],
[confirmedon]=a.[confirmedon],
[approvedby]=a.[approvedby],
[approvedon]=a.[approvedon],
[deactivatedby]=a.[deactivatedby],
[deactivatedon]=a.[deactivatedon],
[remarks]=a.[remarks],
[coid]=a.[coid],
[boid]=a.[boid],
[drawingno]=a.[drawingno],
[batchsize]=a.[batchsize]


					FROM   @bomheader a
					WHERE db_mm.hdr_pbom.pbomid= a.bomid 
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing bom record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select pbomid from CloudERPbklog.db_mm.hdr_pbom where pbomid = @bomid)
						begin
							-- insert data in bom HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_pbom ([pbomid],[productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize]) 
					SELECT [bomid],[productid],[version],[createdby],[revisedby],[revisedon],[revisedreason],[amendedby],[amendedon],[amendentmentreason],[confirmedby],[confirmedon],[approvedby],[approvedon],[deactivatedby],[deactivatedon],[remarks],[coid],[boid],[drawingno],[batchsize] from db_mm.hdr_bom where bomid = @bomid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding bom data.', 16, 1)
								RETURN
								END
										end
				End
			
			--select [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid]
			-- from [db_mm].[dtl_bom] where bomid =@bomid				 
			-- EXCEPT select  [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid]
			--	from @bomdetail
			
			--EXEC sp_executesql @sql

			--SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			--IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_pbom ([pbomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid])
					SELECT [bomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid] from db_mm.dtl_bom where bomid = @bomid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_pbom where [pbomid]= @bomid
				
                insert into db_mm.dtl_pbom([pbomid],[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid], [length],[width])
					Select @bomid,[pid],[cid],[unit],[quantity],[tolerance],[brandid],[wastagequantity],[wastagepercent],[coid],[boid], [length],[width] from @bomdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing bom detail record.', 16, 1)
							RETURN
					END
				END -- end of row count
			END
								commit
								END
								

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



create PROCEDURE [db_mm].[pr_saveplan] 
    @statementtype nvarchar(50),
	@planheader [db_mm].[hdr_plan_tvp] readonly,
	@plandetail [db_mm].[dtl_plan_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @planid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@planno int
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
			set @planno = (SELECT ISNULL(MAX(planno),0) + 1 FROM db_mm.hdr_plan)
		
		
		insert into [db_mm].[hdr_plan] ([planno],[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid])
			SELECT @planno,[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid] from @planheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding plan header data.', 16, 1)
				RETURN
				END
				SELECT @planid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting plan id.', 16, 1)
				RETURN
				END
				
				
				insert into [db_mm].[dtl_plan] ([planid],[productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity])
				select @planid,[productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity]
				from @plandetail
				end 
				else
				Begin -- begin of update 
			-- fetching plan id from table type
			select top 1 @planid = planid from @planheader

			select [createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid]
				from db_mm.hdr_plan where planid = @planid
				 EXCEPT select [createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid]
				 from @planheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_plan ([planid],[planno],[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid]) 
					SELECT @planid,[planno],[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid] from db_mm.hdr_plan where planid = @planid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_plan   set 
				   [createdby]=a.[createdby],
                   [plandate]=a.[plandate],
				   [confirmedby]=a.[confirmedby],
				   [confirmedon]=a.[confirmedon],
				   [approvedby]=a.[approvedby],
				   [approvedon]=a.[approvedon],
				   [remarks]=a.[remarks],
				   [coid]=a.[coid],
				   [boid]=a.[boid]
                    FROM   @planheader a
					WHERE db_mm.hdr_plan.planid= a.planid 
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing plan record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select planid from CloudERPbklog.db_mm.hdr_plan where planid = @planid)
						begin
							-- insert data in plan HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_plan ([planid],[planno],[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid]) 
					SELECT @planid,[planno],[createdby],[plandate],[confirmedby],[confirmedon],[approvedby],[approvedon],[remarks],[coid],[boid] from db_mm.hdr_plan where planid = @planid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding plan data.', 16, 1)
								RETURN
								END
										end
				End
			
			select [productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity]
			 from [db_mm].[dtl_plan] where planid =@planid				 
			 EXCEPT select [productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity]
				from @plandetail
			
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_plan ([planid],[productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity])
					SELECT @planid,[productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity] from db_mm.dtl_plan where planid = @planid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_plan where [planid]= @planid
				
                insert into db_mm.dtl_plan([planid], [productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity])
					Select @planid,[productid],[batchid],[bomid],[orderquantity],[samplequantity],[inventoryquantity],[totalquantity] from @plandetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing plan detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								commit
								
								END

GO
/****** Object:  StoredProcedure [db_mm].[pr_savepo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_mm].[pr_savepo] 
    @statementtype nvarchar(50),
	@poheader [db_mm].[hdr_purchaseorder_tvp] readonly,
	@podetail [db_mm].[dtl_purchaseorder_tvp] readonly,
	@popaymentterms [db_mm].[purchase_paymentterms_tvp] readonly,
	@potermsandconditions [db_mm].[purchase_termsandconditions_tvp] readonly,
	@podeliveryschedule [db_mm].[purchase_deliveryschedule_tvp] READONLY,
	@pofollowup [db_mm].[purchase_followup_tvp] READONLY,
	@userid int,
	@directpo char(1)
 AS
 BEGIN 
 SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
		declare @orderid int, @rowcnt int,@suplid int, @colstring nvarchar(max),@sql nvarchar(max),@ordernumber int,@indentnumber int,@indentid int,@listid int
		declare @isjobwork varchar(1)
		DECLARE @error VARCHAR(100)
	BEGIN TRANSACTION 
		select top 1 @suplid=suplid from @poheader
		If (@statementtype='Insert')
			BEGIN
			set @isjobwork= (select top 1 isjobwork from @poheader)
			set @ordernumber = (SELECT ISNULL(MAX(ordernumber), 0) + 1 FROM db_mm.hdr_purchaseorder )
			if (@directpo = 'V') 
				begin 
					set @listid = (select top 1 orderid from @poheader )
				end
		    insert into [db_mm].[hdr_purchaseorder] ([orderdate],[ordernumber],[ordertypeid],[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],[deactivatedby],
				[deactivatedon],[shiptoid],[billtoid],[fyid],[quotationref],[costcentreid])
			Select [orderdate],@ordernumber,[ordertype],[suplid],(select name from [db_masters].[supplier] where id=@suplid),
			[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],@userid,getdate(),[deactivatedby]
			,[deactivatedon],[shiptoid],[billtoid],[fyid],[quotationref],[costcentreid] from @poheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK     
				-- Raise an error and return
				RAISERROR ('Error while adding po header data.', 16, 1)
				SET @error = 'Error while adding po header data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				SELECT @orderid= SCOPE_IDENTITY()
				if (@directpo='V') 
					begin
						update db_mm.dtl_vendor_allocation_list set poid = @orderid where listid = @listid and suplid = @suplid
					end
				if @directpo ='T'
				BEGIN
					set @indentnumber = (SELECT ISNULL(MAX(indentnumber), 0) + 1 FROM db_mm.hdr_indent )
					INSERT INTO [db_mm].[hdr_indent] ([indentdate], [indentnumber], [indentorid], [departmentid]
					, [remarks], [costcentreid], [coid], [boid], [createdby], [createdon],isactive)
					SELECT
						[orderdate]
					   ,@indentnumber
						,@userid
					   ,(select id from db_masters.department where deptname like '%PURCHASE%')
					   ,'AUTO GENERATED INDENT FROM PO'
					   ,[costcentreid]
					   ,[coid]
					   ,[boid]
					   ,[createdby]
					   ,[createdon]
					   ,1
					   from @poheader
					   SELECT @indentid= SCOPE_IDENTITY()
			   end
            	insert into [db_mm].[dtl_purchaseorder] ([orderid],[itemid],[orderedquantity],[itemname],[itemrate],[itemuom],[itemdiscount],[itemtax],[indentid],[netrate],[remarks],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount],[selectedbrandid],discpercent)
				select @orderid,[itemid],[orderedquantity],[itemname],[itemrate],[itemuom],[itemdiscount],[itemtax],[indentid],[netrate],[remarks],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount],[selectedbrandid],discpercent
				from @podetail
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
					RAISERROR ('Error while adding po detail data.', 16, 1)
				SET @error = 'Error while adding po detail data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				----update quantittordered in indentdetail
				update dtlindent  set quantityordered=isnull(quantityordered,0)+[orderedquantity] from 
				[db_mm].[dtl_indent] dtlindent join @podetail pd
				on dtlindent.indentid=pd.indentid and dtlindent.itemid=pd.itemid
				if @directpo ='T'
				begin
					INSERT INTO [db_mm].[dtl_indent] ([indentid], [itemid], [quantityrequired],[quantityapproved],[quantitywoff]
						, [itemrate],[poid],[approvedby], [approvedon],[brandid],[remarks],[suplname])
					SELECT
						@indentid
					   ,[itemid]
					   ,[orderedquantity]
					   ,[orderedquantity]
					   ,0
					   ,[itemrate]
					   ,@orderid
					   ,@userid
					   ,getdate()
					   ,[brandid]
					   ,[remarks],
					   (select suplname from @poheader)
					FROM @podetail
	                end 
				insert into [db_mm].[purchase_paymentterms] ([orderid],[paymenttermid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[paymentterm])
				select @orderid,[paymenttermid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[paymentterm] from @popaymentterms
					IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
					RAISERROR ('Error while adding po pyt data.', 16, 1)
				SET @error = 'Error while adding po pyt data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				insert into [db_mm].[purchase_termsandconditions] ([orderid],[termsandconditionsid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[termsandcondition])
				select @orderid,[termsandconditionsid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[termsandcondition] from @potermsandconditions
					IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
					RAISERROR ('Error while adding po terms data.', 16, 1)
				SET @error = 'Error while adding po terms data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				insert into [db_mm].[purchase_deliveryschedule] ([orderid],[itemid],[remarks],[deliverydate],[requiredqty],[receivedqty],[receivedon])
				select @orderid,[itemid],[remarks],[deliverydate],[requiredqty],[receivedqty],[receivedon] from @podeliveryschedule
				 	IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
					RAISERROR ('Error while adding po delivery data.', 16, 1)
				SET @error = 'Error while adding po delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				insert into [db_mm].[purchase_followup] ([orderid],[remarks],[date],[contactperson],[contactphone],[settled])
				select @orderid,[remarks],[date],[contactperson],[contactphone],[settled] from @pofollowup
				 	IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
					RAISERROR ('Error while adding po delivery data.', 16, 1)
				SET @error = 'Error while adding po delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
				--INSERT INTO [db_mm].[dtl_purchaselevies]([orderid],[leviesid],[leviesname],[levypercent],[levyvalue],[itemid])
				--SELECT @orderid,(SELECT id FROM [db_mm].[mst_levies] WHERE lower(leviesname) = (SELECT leviesname FROM @podetail)),'leviesname','levypercent','levyvalue',itemid FROM @podetail
				--IF @@ERROR <> 0
				--BEGIN
				-- Rollback the transaction
				--ROLLBACK
				-- Raise an error and return
					--RAISERROR ('Error while adding po purchaselevies data.', 16, 1)
				--SET @error = 'Error while adding po purchaselevies data.  error no: ' + CAST(@@error AS VARCHAR(3))
				--RETURN @error 
				--END
			END
	else
		   Begin -- begin of update 
			-- fetching indent id from table type
			select top 1 @orderid = orderid from @poheader
			UPDATE db_mm.hdr_purchaseorder set 
				[orderdate]=a.[orderdate], 	[ordertypeid]=a.[ordertype],	[suplid]=a.[suplid],	
				[suplname]=(select name from [db_masters].[supplier] where id=a.suplid),
				[supladdress1]=a.[supladdress1],	[supladdress2]=a.[supladdress2],	
				[suplcity]=a.[suplcity],	[suplstate]=a.[suplstate],	[suplpincode]=a.[suplpincode],
				[suplphoneNo]=a.[suplphoneNo],	[suplcontactperson]=a.[suplcontactperson],	
				[supltaxregistrationnumber]=a.[supltaxregistrationnumber],	[billingaddress]=a.[billingaddress],
				[billingcity]=a.[billingcity],	[billingstate]=a.[billingstate],	
				[billingpincode]=a.[billingpincode],	[billinggstin]=a.[billinggstin],
				[shippingaddress]=a.[shippingaddress],	[shippingcity]=a.[shippingcity],	
				[shippingstate]=a.[shippingstate],	[shippingpincode]=a.[shippingpincode], 
				[shippinggstin]=a.[shippinggstin],	[quotationid]=a.[quotationid],	[poamount]=a.[poamount], 	
				[potaxamount]=a.[potaxamount], 	[podiscount]=a.[podiscount], 
				[pofrieghtamount]=a.[pofrieghtamount], 	[amendmentnumber]=a.[amendmentnumber],	
				[frieghttype]=a.[frieghttype], 	[customduty]=a.[customduty], 
				[clgfwdcharges]=a.[clgfwdcharges],	[taxonclgfwdcharges]=a.[taxonclgfwdcharges], 	
				[currency]=a.[currency], 	[currencyrate]=a.[currencyrate], 
				[postatus]=a.[postatus],	[boid]=a.[boid], 	[coid]=a.[coid], 	
				[remarks]=a.[remarks],	[isactive]=a.[isactive], 	[modifiedby]=a.[modifiedby],
				[modifiedon]=a.[modifiedon], 	[deactivatedby]=a.[deactivatedby],	[deactivatedon]=a.[deactivatedon],	
				[shiptoid]=a.[shiptoid], 	[billtoid]=a.[billtoid],[fyid]=a.[fyid],	[quotationref]=a.[quotationref]
			    FROM   @poheader a	WHERE db_mm.hdr_purchaseorder.orderid=  a.orderid 
               delete from db_mm.dtl_purchaseorder where [orderid] = @orderid
            insert into db_mm.dtl_purchaseorder([orderid],[itemid],[orderedquantity],[receivedquantity],[itemname],[itemrate],[itemuom],[itemdiscount],[itemtax],[netrate],[remarks],[indentid],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount],[selectedbrandid],discpercent)
			SELECT @orderid,[itemid],[orderedquantity],[receivedquantity],[itemname],[itemrate],[itemuom],[itemdiscount],[itemtax],[netrate],[remarks],[INDENTID],[brandid],[gstid],[igstamount],[cgstamount],[sgstamount],[selectedbrandid],discpercent from @podetail
	        delete from db_mm.purchase_paymentterms where [orderid] = @orderid
            insert into db_mm.purchase_paymentterms([orderid],[paymenttermid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[paymentterm])
			select @orderid,[paymenttermid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[paymentterm] from @popaymentterms
			delete from db_mm.purchase_termsandconditions where [orderid] = @orderid
            insert into db_mm.purchase_termsandconditions([orderid],[termsandconditionsid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[termsandcondition])
			select @orderid,[termsandconditionsid],[coid],[boid],[isactive],[createdby],[createdon],[modifiedby],[modifiedon],[deactivatedby],[deactivatedon],[termsandcondition] from @potermsandconditions
			delete from db_mm.purchase_deliveryschedule where [orderid] = @orderid
            insert into db_mm.purchase_deliveryschedule([orderid],[itemid],[remarks],[deliverydate],[requiredqty],[receivedqty],[receivedon])
			select @orderid,[itemid],[remarks],[deliverydate],[requiredqty],[receivedqty],[receivedon]  from @podeliveryschedule
		END
		IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK     
			-- Raise an error and return
			RAISERROR ('Error while adding po header data.', 16, 1)
			SET @error = 'Error while adding po header data.  error no: ' + CAST(@@error AS VARCHAR(3))
			RETURN @error 
		END
		commit
END
GO
/****** Object:  StoredProcedure [db_mm].[pr_savepopassing]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


/****** Object:  StoredProcedure [db_mm].[pr_saveindentpassing]    Script Date: 2/15/2019 2:59:22 AM ******/

 

CREATE PROCEDURE [db_mm].[pr_savepopassing]
    @coid int,
	@boid int,
	@userid int,
	@orderid varchar(250)

AS

BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
	 
	update [db_mm].[hdr_purchaseorder]
	SET [approvedby]=@userid,
	[approvedon]=GETDATE(),
	[postatus]='C'
	WHERE [db_mm].[hdr_purchaseorder].orderid in (SELECT DATA FROM dbo.Split1(@orderid,','))  
	end

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



create  PROCEDURE [db_mm].[pr_saverequisition] 
    @statementtype nvarchar(50),
	@requisitionheader [db_mm].[hdr_requisition_tvp] readonly,
	@requisitiondetail [db_mm].[dtl_requisition_tvp] readonly,
	@requisitionarwise [db_mm].[dtl_requisition_arwise_tvp] readonly,
    @userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @reqnid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		declare @reqnnumber int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		set @reqnnumber = (SELECT ISNULL(MAX(reqnno), 0) + 1 FROM db_mm.hdr_requisition)
		
		
		insert into [db_mm].[hdr_requisition] ([reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[productid],[bomid],[lotsize],[batchmfgdate],[batchexpirydate])
			Select @reqnnumber,[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[productid],[bomid],[lotsize],[batchmfgdate],[batchexpirydate] from @requisitionheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding requisition header data.', 16, 1)
				RETURN
				END
				SELECT @reqnid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				
				if   exists(select 1 from @requisitionarwise) 
				begin
				insert into [db_mm].[dtl_requisition_arwise](reqnid,[itemid],[requestedquantity],[issuedquantity],[brandid],[arno])
				select @reqnid,[itemid],[requestedquantity],[issuedquantity],[brandid],[arno]  from @requisitionarwise
			    
				
				 
				 insert into [db_mm].[dtl_requisition_arwise](reqnid,[itemid],[requestedquantity],[brandid],[arno])
				select @reqnid,[itemid],[requestedquantity],[brandid],[arno] from @requisitiondetail  where itemid  not in (select itemid from @requisitionarwise)
				
				end 
				ELSE
				begin
               insert into [db_mm].[dtl_requisition_arwise](reqnid,[itemid],[requestedquantity],[brandid],[arno])
				select @reqnid,[itemid],[requestedquantity],[brandid],[arno] from @requisitiondetail
                end
				insert into [db_mm].[dtl_requisition] ([reqnid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks],[receivedby])
				select @reqnid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity],[remarks],[receivedby]
				from @requisitiondetail
				end 
	else
		Begin -- begin of update 
			-- fetching indent id from table type
			select top 1 @reqnid = reqnid from @requisitionheader

			select [batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon]
				from db_mm.hdr_requisition where reqnid = @reqnid 
				 EXCEPT select [batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon] 
				 from @requisitionheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_requisition ([reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[batchmfgdate],[batchexpirydate]) 
					Select [reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[batchmfgdate],[batchexpirydate] from db_mm.hdr_requisition where reqnid = @reqnid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_requisition   set 
					          [reqnno]= a.[reqnno],
                              [batchno]=a.[batchno],
                              [deptid]=a.[deptid],
                              [costcentreid]=a.[costcentreid],
                              [storeid]=a.[storeid],
                              [manualslipno]=a.[manualslipno],
                              [reqndate]=a.[reqndate],
                               [isconfirm]=a.[isconfirm],
                              [remarks]=a.[remarks],
                              [coid]=a.[coid],
                             [boid]=a.[boid],
                              [confirmedby]=a.[confirmedby],
                            [createdby]=a.[createdby],
                             [createdon]=a.[createdon],
                            [modifiedby]=a.[modifiedby],
                            [modifiedon]=a.[modifiedon],
							[fyid]=a.[fyid],
							[productid]=a.[productid],
							[bomid]=a.[bomid],
							[lotsize]=a.[lotsize],
							[batchmfgdate]=a.[batchmfgdate],
							[batchexpirydate]=a.[batchexpirydate]
					FROM   @requisitionheader a
					WHERE  db_mm.hdr_requisition.reqnid =a.reqnid 
					
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing requisition record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select reqnid from CloudERPbklog.db_mm.hdr_requisition where reqnid = @reqnid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_requisition([reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[productid],[bomid],[lotsize],[batchmfgdate],[batchexpirydate])
			    SELECT  [reqnid],[reqnno],[batchno],[deptid],[costcentreid],[storeid],[manualslipno],[reqndate],[isconfirm],[remarks],[coid],[boid],[confirmedby],[createdby],[createdon],[modifiedby],[modifiedon],[fyid],[productid],[bomid],[lotsize],[batchmfgdate],[batchexpirydate] from db_mm.hdr_requisition where reqnid = @reqnid
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding requisition data.', 16, 1)
								RETURN
	            End
		        End
				End
			
			select [itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks]
			from [db_mm].[dtl_requisition] where [reqnid] =@reqnid 
			EXCEPT 
			SELECT [itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks]
			from @requisitiondetail
			union 
			SELECT [itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks]
			from @requisitiondetail
			EXCEPT 
			select [itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks]
			from [db_mm].[dtl_requisition] where [reqnid] =@reqnid 
			
			       

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_requisition ([reqnid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks],[receivedby])
					SELECT @reqnid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks],[receivedby] from db_mm.dtl_requisition where [reqnid] = @reqnid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_requisition where [reqnid] = @reqnid
				
                insert into db_mm.dtl_requisition([reqnid],[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks],[receivedby])
					SELECT @reqnid,[itemid],[brandid],[grnid],[arno],[requestedquantity],[issuedquantity],[woffquantity], [remarks],[receivedby] from @requisitiondetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing requisition detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								COMMIT
								
								
								END

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



CREATE PROCEDURE [db_mm].[pr_savergp] 
    @statementtype nvarchar(50),
	@rgpheader [db_mm].[hdr_rgp_tvp] readonly,
	@rgpdetail [db_mm].[dtl_rgp_tvp] readonly,
	@rgpexpdetail [db_mm].[dtl_rgp_returnitems_tvp] readonly,
	@userid int
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @rgpid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@rgpno int
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
			set @rgpno = (SELECT ISNULL(MAX(rgpno),0) + 1 FROM db_mm.hdr_rgp)
		
		
		    insert into [db_mm].[hdr_rgp] ([rgpno],[rgpdate],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[userid],[cosigneeid],[deliveryaddress], [approvedby],[approvedon], [grno],[grdate], [deptid],[storeid],[boid],[coid],[fyid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon], [orderid])
			SELECT @rgpno,[rgpdate],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[userid],[employeeid],[cosigneeid],[deliveryaddress], [approvedby],[approvedon], [grno],[grdate], [deptid],[storeid],[boid],[coid],[fyid],[remarks], [createdby],  [createdon], [modifiedby],[modifiedon], [orderid] from @rgpheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding rgp header data.', 16, 1)
				RETURN
				END
				SELECT @rgpid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting rgp id.', 16, 1)
				RETURN
				END
				insert into [db_mm].[dtl_rgp] ([rgpid],[itemid],[qtysent],[rate],[brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification] )
				select @rgpid,[itemid],[qtysent],[rate],[brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected] ,[itemspecification]
				from @rgpdetail
				
				insert into [db_mm].[dtl_rgp_returnitems] ([rgpid],[itemid],[qty],[brandid],[expecteddate],[itemspecification] )
				select @rgpid,[itemid],[qty],[brandid],[expecteddate],[itemspecification] 
				from @rgpexpdetail

			end 
	else
		Begin -- begin of update 
			-- fetching rgp id from table type
			select top 1 @rgpid =id from @rgpheader
			
			select [rgpdate],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[userid],[employeeid],[cosigneeid],[deliveryaddress], [approvedby],[approvedon], [grno],[grdate], [deptid],[storeid],[boid],[coid],[fyid],[remarks], [createdby],  [createdon], [modifiedby],[modifiedon], [orderid]
				 from @rgpheader
			EXCEPT 
			select [rgpdate],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[userid],[employeeid],[cosigneeid],[deliveryaddress], [approvedby],[approvedon], [grno],[grdate], [deptid],[storeid],[boid],[coid],[fyid],[remarks], [createdby],  [createdon], [modifiedby],[modifiedon], [orderid]
				from db_mm.hdr_rgp where id = @rgpid

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
			
					insert into CloudERPbklog.db_mm.hdr_rgp (id,[rgpno],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon],[cosigneeid], [orderid]) 
					SELECT @rgpid,[rgpno], [partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon],[cosigneeid], [orderid] from db_mm.hdr_rgp where id = @rgpid 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					END
					-- updating existing records from supplier table and checking @@ERROR 
				   UPDATE db_mm.hdr_rgp  
			       set
		           [partyid]=a.[partyid],
                   [outtime]=a.[outtime],
                   [transportid]=a.[transportid],
                   [vehicletypeid]=a.[vehicletypeid],
                   [vehiclename]=a.[vehiclename],
                   [vehicleno]=a.[vehicleno],
                   [employeeid]=a.[employeeid],
                   [deptid]=a.[deptid],
                   [storeid]=a.[storeid],
                   [remarks]=a.[remarks],
                   [modifiedby]=@userid,
                   [modifiedon]=getdate(),
                   [deliveryaddress]=a.[deliveryaddress],
				   [cosigneeid]=a.[cosigneeid],
				   [orderid]=a.[orderid]
                   FROM   @rgpheader a
  				   WHERE db_mm.hdr_rgp.id= a.id 

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing rgp record.', 16, 1)
							RETURN
					END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin

				select 'ravinder1' from @rgpheader
					if not exists(select id from CloudERPbklog.db_mm.hdr_rgp where id = @rgpid)
						begin
							-- insert data in rgp HEADER table and checking @@ERROR 
							insert into CloudERPbklog.db_mm.hdr_rgp (id,[rgpno],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon],[cosigneeid], [orderid]) 
					        SELECT @rgpid,[rgpno],[partyid],[outtime],[transportid],[vehicletypeid],[vehiclename],[vehicleno],[employeeid],[deptid],[storeid],[boid],[coid],[remarks],[createdby],[createdon],[modifiedby],[modifiedon],[deliveryaddress],[fyid],[approvedby],[approvedon],[cosigneeid], [orderid] from db_mm.hdr_rgp where id = @rgpid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding rgp data.', 16, 1)
								RETURN
							END
					end
			End
			
			select [itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification]
			from [db_mm].[dtl_rgp] where rgpid =@rgpid				 
			EXCEPT 
			SELECT [itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification]
			FROM @rgpdetail
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_rgp ([rgpid],[itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification])
					SELECT @rgpid,[itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification] from db_mm.dtl_rgp where rgpid = @rgpid 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_rgp where [rgpid]= @rgpid
				
                    insert into db_mm.dtl_rgp([rgpid],[itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification])
					Select @rgpid,[itemid], [qtysent],[rate], [brandid],[approxvalue],[qtyrecdunused],[qtyrecdwoff],[qtyrecdrejected],[itemspecification] from @rgpdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing rgp detail record.', 16, 1)
							RETURN
					END
			END -- end of row count


			select [itemid],[qty],[brandid],[expecteddate],[itemspecification]
			from [db_mm].[dtl_rgp_returnitems] where rgpid =@rgpid				 
			EXCEPT 
			select [itemid],[qty],[brandid],[expecteddate],[itemspecification]
			from @rgpexpdetail
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_rgp_returnitems ([rgpid],[itemid],[qty],[brandid],[expecteddate],[itemspecification])
					SELECT @rgpid,[itemid],[qty],[brandid],[expecteddate],[itemspecification] from db_mm.dtl_rgp_returnitems where rgpid = @rgpid 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_rgp_returnitems where [rgpid]= @rgpid
				
                    insert into db_mm.dtl_rgp_returnitems([rgpid],[itemid],[qty],[brandid],[expecteddate],[itemspecification])
					Select @rgpid,[itemid],[qty],[brandid],[expecteddate],[itemspecification] from @rgpexpdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing rgp detail record.', 16, 1)
							RETURN
					END
			END -- end of row count

				select [itemid],[qty],[brandid],[expecteddate]
			from [db_mm].[dtl_rgp_returnitems] where rgpid =@rgpid				 
			EXCEPT 
			select [itemid],[qty],[brandid],[expecteddate]
			from @rgpexpdetail
			--EXEC sp_executesql @sql
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_rgp_returnitems ([rgpid],[itemid],[qty],[brandid],[expecteddate])
					SELECT @rgpid,[itemid],[qty],[brandid],[expecteddate] from db_mm.dtl_rgp_returnitems where rgpid = @rgpid 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_rgp_returnitems where [rgpid]= @rgpid
				
                    insert into db_mm.dtl_rgp_returnitems([rgpid],[itemid],[qty],[brandid],[expecteddate])
					Select @rgpid,[itemid],[qty],[brandid],[expecteddate] from @rgpexpdetail 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing rgp detail record.', 16, 1)
							RETURN
					END
			END -- end of row count

		END	
	commit
								
END

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



CREATE  PROCEDURE [db_mm].[pr_savestktransfer] 
    @statementtype nvarchar(50),
	@stktransferheader [db_mm].[hdr_stktransfer_tvp] readonly,
	@stktransferdetail [db_mm].[dtl_stktransfer_tvp] readonly,
	@userid int=1
AS


BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @stktransferid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max)
		declare @stktransfernumber int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		set @stktransfernumber = (SELECT ISNULL(MAX(stktransferno), 0) + 1 FROM db_mm.hdr_stktransfer)
		
		
		    insert into [db_mm].[hdr_stktransfer] ([stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid])
			Select @stktransfernumber,[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from @stktransferheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding stktransfer header data.', 16, 1)
				RETURN
				END
				SELECT @stktransferid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting reqn id.', 16, 1)
				RETURN
				END
				
		        insert into [db_mm].[dtl_stktransfer] ([stktransferid],[itemid],[quantity],[arno])
				select @stktransferid,[itemid],[quantity],[arno]
				from @stktransferdetail


				---INSERT data INTO stock trn
				INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[itemquantity],[trntypeid],[trnoperator],[remarks],[storeid],[coid],[boid],isactive,createdby,createdon)
				SELECT [itemid],[itemid],[quantity],case when (select trntype from @stktransferheader)='I' then  13 else 12 end,case when (select trntype from @stktransferheader)='I' 
				then  '-' else '+' end,case when (select trntype from @stktransferheader)='I' then  'stock transfer out' else 'stock transfer in' end,
				(SELECT [receivingstoreid] FROM @stktransferheader),(SELECT coid FROM @stktransferheader),(SELECT boid FROM @stktransferheader),1,@userid,getdate () FROM @stktransferdetail
				end 
	else
		Begin -- begin of update .
			-- fetching indent id from table type
			select top 1 @stktransferid = @stktransferid from @stktransferheader

			select [manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]
				from db_mm.hdr_stktransfer where stktransferid = @stktransferid
				 EXCEPT select [manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]
				 from @stktransferheader
			
			--print @sql
			--EXEC sp_executesql @sql

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_stktransfer ([stktransferid],[stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select @stktransferid,[stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_stktransfer where stktransferid = @stktransferid 

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					-- updating existing records from supplier table and checking @@ERROR 
					UPDATE db_mm.hdr_stktransfer   set 
					          [manualslipno]= a.[manualslipno],
                              [trntype]=a.[trntype],
                              [departmentid]=a.[departmentid],
                              [receivingstoreid]=a.[receivingstoreid],
							  [issuingstoreid]=a.[issuingstoreid],
							  [issuingboid]=a.[issuingboid],
                              [remarks]=a.[remarks],
                              [coid]=a.[coid],
                             [boid]=a.[boid],
                            [createdby]=a.[createdby],
                             [createdon]=a.[createdon],
                            [modifiedby]=a.[modifiedby],
                            [modifiedon]=a.[modifiedon],
							[fyid]=a.[fyid]
					FROM   @stktransferheader a
					WHERE  db_mm.hdr_stktransfer.stktransferid =a.stktransferid 
					
		
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing stktransfer record.', 16, 1)
							RETURN
						END
				END -- end of row count
			Else -- if record count of except statement is 0,check for supplier entry in log table, if record count is 0, insert record for the first time in log table 
				Begin
					if not exists(select stktransferid from CloudERPbklog.db_mm.hdr_stktransfer where stktransferid = @stktransferid)
						begin
							-- insert data in INDENT HEADER table and checking @@ERROR 
					insert into CloudERPbklog.db_mm.hdr_stktransfer ([stktransferid],[stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid]) 
					Select @stktransferid,[stktransferno],[manualslipno],[trntype],[departmentid],[receivingstoreid],[issuingstoreid],[issuingboid],[remarks],[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon],[fyid] from db_mm.hdr_stktransfer where stktransferid = @stktransferid 
							-- Rollback the transaction if there were any errors
							IF @@ERROR <> 0
								BEGIN
								-- Rollback the transaction
								ROLLBACK
								-- Raise an error and return
								RAISERROR ('Error while adding stktransfer data.', 16, 1)
								RETURN
	            End
		        End
				End
			
			select [stktransferid],[itemid],[quantity],[arno]
			from [db_mm].[dtl_stktransfer] where stktransferid =@stktransferid
			EXCEPT 
			SELECT [stktransferid],[itemid],[quantity],[arno]
			from @stktransferdetail
			union 
			SELECT [stktransferid],[itemid],[quantity],[arno]
			from @stktransferdetail
			EXCEPT 
			select [stktransferid],[itemid],[quantity],[arno]
			from [db_mm].[dtl_stktransfer] where stktransferid =@stktransferid
			
			       

			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- insert records in bkup and checking @@ERROR 
					insert into CloudERPbklog.db_mm.dtl_stktransfer ([stktransferid],[itemid],[quantity],[arno])
					SELECT @stktransferid,[itemid],[quantity],[arno] from db_mm.dtl_stktransfer where stktransferid = @stktransferid

					--print @sql

					--EXEC sp_executesql @sql

					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
					 BEGIN
						-- Rollback the transaction
						ROLLBACK
						-- Raise an error and return
						RAISERROR ('Error while updating log enteries.', 16, 1)
						RETURN
					 END
					 delete from db_mm.dtl_stktransfer where stktransferid = @stktransferid
				
                insert into db_mm.dtl_stktransfer([stktransferid],[itemid],[quantity],[arno])
					SELECT @stktransferid,[itemid],[quantity],[arno] from @stktransferdetail
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing stktransfer detail record.', 16, 1)
							RETURN
						END
				END -- end of row count
			end
								COMMIT
								
								
								END

GO
/****** Object:  StoredProcedure [db_mm].[pr_savevendorallocationlist]    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_savevendorallocationlist]
    @statementtype varchar(20),
	@userid int,
	@listheader [db_mm].[hdr_vendor_allocation_list_tvp] readonly,
	@listdetail [db_mm].[dtl_vendor_allocation_list_tvp] readonly
AS
BEGIN
	SET NOCOUNT ON;
	declare @listno bigint, @listid bigint;
	DECLARE @error VARCHAR(100);
	declare @coid int, @boid int;

	select @coid = coid, @boid = boid from @listheader

	If (@statementtype='Insert')
		Begin
			
			SELECT @listno= ISNULL(MAX(listno), 0) + 1 FROM db_mm.hdr_vendor_allocation_list

			insert into db_mm.hdr_vendor_allocation_list (listno,listdate,userid,valuecustorder,valuestkorder,remarks,coid,boid
			,isactive,createdon,createdby)
			select @listno,getdate(),@userid,valuecustorder,valuestkorder,remarks,coid,boid,1,getdate(),@userid from @listheader
			IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK     
				-- Raise an error and return
				RAISERROR ('Error while adding vendor allocation  header data.', 16, 1)
				SET @error = 'Error while adding vendor allocation header data.  error no: ' + CAST(@@error AS VARCHAR(3))
				RETURN @error 
				END
			select @listid = SCOPE_IDENTITY()

			insert into db_mm.dtl_vendor_allocation_list (indentid,itemid,suplid,itemquantity,itemrate,poid,brandid
			,listid,qtyapproved,laborrate,quoteno,quotedate,quoterate,remarks)
			select indentid,itemid,suplid,itemquantity,itemrate,poid,brandid,@listid,qtyapproved,
			laborrate,quoteno,quotedate,quoterate,remarks from @listdetail

		End
	Else
		Begin
			select @listid = listid from @listheader
			
			update db_mm.hdr_vendor_allocation_list set valuestkorder = a.valuestkorder, modifiedon = getdate(), modifiedby = @userid 
			from @listheader a where db_mm.hdr_vendor_allocation_list.listid = a.listid

			delete from db_mm.dtl_vendor_allocation_list where listid = @listid 
			and id not in (select id from @listdetail where id>0)

			insert into  db_mm.dtl_vendor_allocation_list (indentid,itemid,suplid,itemquantity,itemrate,poid,brandid
			,listid,qtyapproved,laborrate,quoteno,quotedate,quoterate,remarks)
			select indentid,itemid,suplid,itemquantity,itemrate,poid,brandid,@listid,qtyapproved,
			laborrate,quoteno,quotedate,quoterate,remarks from @listdetail where id = 0

		End
	
	exec [db_mm].[pr_getvendorallocationlistitems]  @coid,@boid,1,@listid

END
GO
/****** Object:  StoredProcedure [db_mm].[pr_savevendorallocationlistapprovals]    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_savevendorallocationlistapprovals]
    @coid int,
	@boid int,
	@userid int,
	@listid int,
	@level int,
	@dt_items [db_mm].[dtl_vendor_allocation_approval_list_tvp] readonly,
	@remarks varchar(max)='',
	@statementtype varchar(10)='save'
AS
BEGIN
	SET NOCOUNT ON;
	declare @approvalid int= 0;
	set @approvalid = (select top 1 approvalid from @dt_items)

	if (@statementtype='save')
	Begin
		if (@approvalid=0)
			Begin
				insert into db_mm.hdr_vendorallocation_approvals (listid,appvllevel,appvlauthorityid, approvaldate,remarks,coid,boid,isactive)
				values (@listid, @level,@userid,getdate(),isnull(@remarks,''),@coid,@boid,1)

				select @approvalid = Scope_identity()

				insert into db_mm.dtl_vendorallocation_approvals(approvalid,listid,itemid,qtyapproved,approvedrate,qtyrejected,remarksforappvl)
				select @approvalid, listid,itemid,qtyapproved,approvedrate,qtyrejected,remarksforappvl from @dt_items

			End
		else 
			Begin
				update db_mm.hdr_vendorallocation_approvals set remarks = @remarks where id = @approvalid
			
				delete from db_mm.dtl_vendorallocation_approvals where id not in 
				(select distinct id from @dt_items) and approvalid = @approvalid

				insert into db_mm.dtl_vendorallocation_approvals(approvalid,listid,itemid,qtyapproved,qtyrejected,approvedrate,remarksforappvl)
				select @approvalid, listid,itemid,qtyapproved,qtyrejected,approvedrate,remarksforappvl from @dt_items where id = 0

				update db_mm.dtl_vendorallocation_approvals set 
					qtyapproved = a.qtyapproved, qtyrejected = a.qtyrejected, approvedrate = a.approvedrate, remarksforappvl= a.remarksforappvl
				from @dt_items a where db_mm.dtl_vendorallocation_approvals.id = a.id 
			End

		update db_mm.dtl_vendor_allocation_list set qtyapproved = a.qtyapproved, approvedrate = a.approvedrate, 
		remarksforappvl=a.remarksforappvl, qtyrejected = a.qtyrejected from 
		@dt_items a where db_mm.dtl_vendor_allocation_list.id = a.id
	End
	else
	Begin
		update db_mm.hdr_vendorallocation_approvals set isconfirmed = 1, appvllevel = @level, remarks = @remarks  where id = @approvalid
		
		delete from db_mm.dtl_vendorallocation_approvals where id not in 
		(select distinct id from @dt_items) and approvalid = @approvalid

		insert into db_mm.dtl_vendorallocation_approvals(approvalid,listid,itemid,qtyapproved,qtyrejected,approvedrate,remarksforappvl)
		select @approvalid, listid,itemid,qtyapproved,qtyrejected,approvedrate,remarksforappvl from @dt_items where id = 0

		update db_mm.dtl_vendorallocation_approvals set 
			qtyapproved = a.qtyapproved, qtyrejected = a.qtyrejected, approvedrate = a.approvedrate, remarksforappvl= a.remarksforappvl
		from @dt_items a where db_mm.dtl_vendorallocation_approvals.id = a.id 

	End
END
GO
/****** Object:  StoredProcedure [db_mm].[pr_stockledger]    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_stockledger] 1,1,1,'550'
-- =============================================

CREATE PROCEDURE [db_mm].[pr_stockledger] 
@coid int,
@boid int,
@fyid int,
@itemid varchar(50),
@fromdate date=null,
@todate	date=null,
@userid int=null,
@accesstoken varchar(50)=null

AS
BEGIN
	SET NOCOUNT ON;
	select item.id,item.itemcode,item.itemname,item.oldcode,item.openingrate,ruom.uom receivingunit, iuom.uom issuingunit 
	from db_mm.mst_item item 
	join db_mm.mst_itemuom ruom on item.receivingunitid= ruom.id
	join db_mm.mst_itemuom iuom on item.issuingunitid= iuom.id 
	where item.id in (select * from dbo.fnSplitstring(@itemid,','))

	IF OBJECT_ID('tempdb..#tempstockledger') IS NOT NULL DROP TABLE #tempstockledger
	
	create table #tempstockledger 
	(
		id			bigint,
		itemid		bigint,
		stkdate		date,
		reference	varchar(200),
		refid		bigint,
		trntypeid	int,
		arnumber	varchar(100),
		particular	varchar(500),
		Rectqty		decimal(10,3),
		issqty		decimal(10,3),
		balanceqty	decimal(10,3),
		rowno		int
	);

-- check and insert opening stk i.e. transaction type=16
declare @opbalcount int =(select count(id) from db_mm.item_stk_trn where coid=@coid and boid=@boid and fyid=@fyid and trntypeid = 16
and itemid in (select * from dbo.fnSplitstring(@itemid,',')) group by itemid)
print @opbalcount
if (@opbalcount>0)
begin
insert into #tempstockledger (id,itemid,stkdate,reference,refid,trntypeid,arnumber,particular,rectqty,issqty,balanceqty,rowno)
select 0,itemid, @fromdate,'Op. Stock',0,16,0,'Op. Stock',sum(itemquantity),0,sum(itemquantity) , 0 
from db_mm.item_stk_trn where coid=@coid and boid=@boid and fyid=@fyid and trntypeid = 16  
and itemid in (select * from dbo.fnSplitstring(@itemid,',')) group by itemid
end
else 
begin 
insert into #tempstockledger(id,itemid,stkdate,reference,refid,trntypeid,arnumber,particular,rectqty,issqty,balanceqty)
values (0,0,getdate(),'opening stock',0,16,0,'opening stock',0,0,0)
end
--IF (NOT EXISTS(SELECT * FROM #tempstockledger WHERE trntypeid=16)) 
--Begin
--	insert into #tempstockledger(id,stkdate,reference,refid,trntypeid,arnumber,particular,rectqty,issqty,balanceqty)
--values (0,@fromdate,'opening stock',0,16,0,'opening stock',0,0,0)
--End	


-- get financial year start and end date in case from and to date are not supplied
declare @fystartdate date, @fyenddate date;
select @fystartdate = fystartdate, @fyenddate = fyenddate from db_masters.financialyears where id = @fyid

--udpate opening stock for transactions prior to that of from date
update #tempstockledger set rectqty = rectqty + a.stock, balanceqty= balanceqty + a.stock 
from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock 
from db_mm.item_stk_trn where fyid = @fyid and createdon < coalesce(@fromdate,@fystartdate) 
and coid=@coid and boid=@boid and trntypeid<>16 and itemid in (select * from dbo.fnSplitstring(@itemid,',')) group by itemid ) a 
where #tempstockledger.trntypeid=16 and #tempstockledger.itemid = a.itemid

--insert other stock transactions for items
insert into #tempstockledger (id,itemid, stkdate,reference,refid,trntypeid,arnumber,particular,rectqty,issqty,balanceqty,rowno)
select id,itemid, createdon,remarks,refid,trntypeid,arnumber,'',
case when trnoperator = '+' then itemquantity else 0 end,
case when trnoperator = '-' then itemquantity else 0 end,
case when trnoperator = '+' then itemquantity else itemquantity*-1 end,
ROW_NUMBER () OVER (order by id) as rowno
from db_mm.item_stk_trn where coid=@coid and boid=@boid and fyid=@fyid and trntypeid <> 16 
and itemid in (select * from dbo.fnSplitstring(@itemid,',')) order by id 

--update reference and particulars for trntypeid=2 i.e GRN
update #tempstockledger set reference = 'GRN No. : '+ cast(a.grnnumber as varchar(5)) + '/n Date : ' + cast(a.grndate as varchar(10)), 
particular = b.suplname +  ' /n Inv. No.: ' + cast(a.billno as varchar(5)) + ' PO No. : ' + cast(b.ordernumber as varchar(5))
from db_mm.hdr_grn a join db_mm.hdr_purchaseorder b on a.poid = b.orderid 
where #tempstockledger.refid = a.grnid and #tempstockledger.trntypeid = 2

--update reference and particulars for trntypeid=5 i.e Issuance
update #tempstockledger set reference = 'Iss. No. : '+ cast(a.issuanceno as varchar(5)), 
particular =b.deptname + ' /n Reqn. No : ' + cast(a.reqnno as varchar(5)) + ' Batch No. : ' + cast(a.batchno as varchar(10)) 
from db_mm.hdr_issuance a join db_masters.department b on a.deptid = b.id 
where #tempstockledger.refid = a.issuanceid and #tempstockledger.trntypeid = 5

--update reference and particulars for trntypeid=17 i.e dpr
update #tempstockledger set reference = 'DPR. No. : '+ cast(a.dprnumber as varchar(5)), 
particular =a.dprnumber 
from db_mm.hdr_dpr a join db_mm.dtl_dpr b on a.dprid = b.dprid 
where #tempstockledger.refid = a.dprid and #tempstockledger.trntypeid = 17


--update reference and particulars for trntypeid=10 i.e Sale
update #tempstockledger set reference = 'BILL Cancellation NO. : '+ cast(a.invno as varchar(5)),
particular =a. customername + ' /n O.A. : ' + cast(b.oano as varchar(5)) 
from db_sop.hdr_sale a join db_sop.hdr_saleorder b on a.oaids = b.oaid 
where #tempstockledger.refid = a.id and #tempstockledger.trntypeid = 1020


update #tempstockledger set reference = 'Inv. No. : '+ cast(a.invno as varchar(5)),
particular =a. customername + ' /n O.A. : ' + cast(b.oano as varchar(5)) 
from db_sop.hdr_sale a join db_sop.hdr_saleorder b on a.oaids = b.oaid 
where #tempstockledger.refid = a.id and #tempstockledger.trntypeid = 10


--update reference and particulars for trntypeid=20 i.e Sample for IQC
--update reference and particulars for trntypeid=5 i.e Issuance
update #tempstockledger set reference = 'IQC Iss. No. : '+ cast(a.issuanceno as varchar(5)), 
particular ='Reqn. No : ' + cast(a.reqnno as varchar(5)) + ' Batch No. : ' + cast(a.batchno as varchar(10)) 
from db_mm.hdr_issuance a  
where #tempstockledger.refid = a.issuanceid and #tempstockledger.trntypeid = 20


--update reference and particulars for trntypeid=11 i.e Sale Return

--update reference and particulars for trntypeid=3 i.e Purchase Return
declare @minid int, @maxid int;

select @maxid = max(rowno),@minid=min(rowno) from #tempstockledger;
-- update opening of group in #temptrial
if (@maxid > @minid)
BEGIN
	WAY: -- loop to update balance in result table
		update #tempstockledger set balanceqty = balanceqty + a.qty
		from (select itemid, balanceqty  qty from #tempstockledger where rowno=@minid ) a where #tempstockledger.itemid = a.itemid 
		and #tempstockledger.rowno = @minid+1;
		set @minid +=1;
	IF NOT(@minid = @maxid) GOTO WAY;
END
select id	,		itemid		,	convert(varchar, stkdate, 103)	stkdate		,
		reference	,
		refid		,
		trntypeid	,
		arnumber	,
		particular	,
		Rectqty		,
		issqty		,
		balanceqty  from #tempstockledger 
drop table #tempstockledger;


	
END










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

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

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

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

end
	

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

-- =============================================
-- Author:	<Author,,Amit>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_masters].[pr_getitemcategorylist_test] 1,1,1
-- =============================================
create PROCEDURE [db_mm].[pr_update_item_code_initemmaster] 
@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;

with ctc as (
SELECT  ROW_NUMBER() OVER(Partition by itemcategoryid ORDER BY id) AS RowNumber,* from db_mm.mst_item  
)
update db_mm.mst_item set itemimage =RowNumber 
from ctc  where ctc.id=db_mm.mst_item.id
-- 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 in (SELECT id from db_mm.mst_itemcategory)
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 

)
update db_mm.mst_item set accessories=categcode
FROM x where x.id=db_mm.mst_item.itemcategoryid



update db_mm.mst_item set accessories=
case
when  len(itemimage)=1 then accessories +'0000' +itemimage
when  len(itemimage)=2 then accessories +'000'+itemimage
when  len(itemimage)=3 then accessories +'00' +itemimage
when  len(itemimage)=4 then accessories +'0'  +itemimage
else  accessories+itemimage  end 

DROP TABLE #tree;
--select id,name from db_mm.mst_dimension
END







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


/****** Object:  StoredProcedure [db_mm].[pr_saveindentpassing]    Script Date: 2/15/2019 2:59:22 AM ******/

 
--- EXEC [db_mm].[pr_saveindentpassing]1,1,1,4,21,6.523,1
CREATE PROCEDURE [db_mm].[pr_updatepurchasefollowup]
  @statementtype nvarchar(50),
   @orderid int,
   @pofollowup [db_mm].[purchase_followup_tvp] READONLY

AS

BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
	 delete from db_mm.purchase_followup where orderid=@orderid
	 insert into [db_mm].[purchase_followup] ([orderid],[remarks],[date],[contactperson],[contactphone],[settled])
	 select @orderid,[remarks],[date],[contactperson],[contactphone],[settled] from @pofollowup
    
	
	end

GO
/****** Object:  StoredProcedure [db_mm].[pr_usageofiteminbom]    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_usageofiteminbom]  1,1,17
-- =============================================
CREATE PROCEDURE [db_mm].[pr_usageofiteminbom] 
@coid int,
@boid int,
@itemid bigint
AS
BEGIN
	select distinct(dt.pid),dt.quantity,im.itemname,im.itemcode,um.uom,im.specialcode from db_mm.dtl_bom dt
join db_mm.mst_item im on dt.pid = im.id
join db_mm.mst_itemuom um on im.receivingunitid=um.id  where dt.cid = @itemid  
END














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

-- exec [db_mm].[reports_dprregister]1,1,1,'04/01/2019','07/28/2019','','287,438'

CREATE  PROCEDURE [db_mm].[reports_dprregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@reportid int=0,
	@itemid varchar(200)=null,
	@deptid int=0,
	@brandid int= 0
	AS
BEGIN 
declare @sql nvarchar(max)
    begin
	set @sql=' select dprdate,dprnumber,deptname,dt.itemid,itemname,itemcode,quantity,batchno,mfgdate,expirydate,b.name brand
	from [db_mm].[hdr_dpr] h join [db_mm].[dtl_dpr] dt on h.dprid=dt.dprid
	join [db_mm].[mst_item] m on dt.itemid=m.id
	join [db_masters].[department] d on h.departmentid=d.id
	join [db_mm].[mst_brand] b on dt.brandid=b.id '
	
	set @sql +='  where h.coid = '+ cast(@coid as varchar(5)) +' and h.boid='+ cast(@boid as varchar(5))+' and h.dprdate >='''+ cast(@fromdate as varchar(20))+''' and h.dprdate <='''+ cast(@todate as varchar(20))+''''
	if(@itemid!='')
	 begin
	 set @sql+= ' and dt.itemid in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
	 end
	 if(@deptid!='')
	 begin
	 set @sql+= ' and h.deptid = '+ cast(@boid as varchar(5))+ ''
	 end
	  if(@brandid!='')
	 begin
	 set @sql+= ' and h.brandid = '+ cast(@brandid as varchar(5))+ ' '
	 end
	 set @sql +=' union all'

	 set @sql +=' select  '''' dprdate, '''' dprnumber, '''' deptname,'''' itemid,
	 ''Total'' itemname,'''' itemcode,cast(sum(quantity) as DECIMAL(18,2))quantity, '''' batchno,''''mfgdate,''''expirydate,'''' brand
	from [db_mm].[hdr_dpr] h join [db_mm].[dtl_dpr] dt on h.dprid=dt.dprid
	join [db_mm].[mst_item] m on dt.itemid=m.id
	join [db_masters].[department] d on h.departmentid=d.id
	join [db_mm].[mst_brand] b on dt.brandid=b.id '
	
	set @sql +='  where h.coid = '+ cast(@coid as varchar(5)) +' and h.boid='+ cast(@boid as varchar(5))+' and h.dprdate >='''+ cast(@fromdate as varchar(20))+''' and h.dprdate <='''+ cast(@todate as varchar(20))+''''
	--if(@itemid!='')
	-- begin
	-- set @sql+= ' and dt.itemid in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
	-- end
	 if(@deptid!='')
	 begin
	 set @sql+= ' and h.deptid = '+ cast(@boid as varchar(5))+ ''
	 end
	  if(@brandid!='')
	 begin
	 set @sql+= ' and h.brandid = '+ cast(@brandid as varchar(5))+ ''
	 end


	End
	 print @sql
	 
	 EXEC sp_executesql @sql

END


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

-- select * from [db_mm].[dtl_inwardadvice]
-- exec [db_mm].[reports_debitnote] 1,1,2,1,'C'

CREATE PROCEDURE [db_mm].[reports_drcradvice]
	@coid	  int,
	@boid	  int,
	@fyid	  int,
	@Drcrno   int,
	@Type     char(1)
AS
BEGIN

	select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info,b.gstno
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	where b.coid = @coid and b.boid = @boid

    select hdr.adviceno,format(hdr.advicedate,'dd-MM-yyyy') Dated,supl.name,
           isnull(supl.address1,'') + isnull(supl.address2,'') supladdr,hdr.amount
    from   [db_mm].[hdr_inwardadvice] hdr 
    inner join [db_masters].[supplier] supl on hdr.partyid=supl.id 
	where hdr.adviceno=@Drcrno and hdr.advicetype =@Type

    select itm.itemname,dtl.rate,dtl.quantity,dtl.amount,dtl.porate ,
	isnull(dtl.porate,0) - isnull(dtl.rate,0) as ratediff,
	cast(isnull(dtl.porate,0) - isnull(dtl.rate,0) as decimal) * cast(dtl.quantity as decimal) as calcamt,
	isnull(dtl.igstamount,0) igst,isnull(dtl.cgstamount,0) cgst,isnull(dtl.sgstamount,0) sgst
    from [db_mm].[dtl_inwardadvice] dtl
    inner join   [db_mm].[mst_item] itm on dtl.itemid=itm.id
	inner join   [db_mm].[hdr_inwardadvice] hdr on dtl.adviceid= hdr.adviceid
	where hdr.adviceno=@Drcrno and hdr.advicetype =@Type
	
	--INR added by mohit please replase INR with current Currency which using in this CR-advice
	SELECT db_general.NumberToWords(isnull(hdr.amount,0),'INR') NumberToWords 
	from [db_mm].[hdr_inwardadvice] hdr
	WHERE hdr.adviceno=@Drcrno and hdr.advicetype =@Type 

	select sum(isnull(dtl.igstamount,0)) igst,sum(isnull(dtl.cgstamount,0)) cgst,sum(isnull(dtl.sgstamount,0)) sgst 
	from  [db_mm].[dtl_inwardadvice] dtl
	inner join   [db_mm].[hdr_inwardadvice] hdr on dtl.adviceid= hdr.adviceid
	where hdr.adviceno=@Drcrno and hdr.advicetype =@Type 
	group by dtl.adviceid

END


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

-- select * from [db_mm].[dtl_inwardadvice]
-- exec [db_mm].[reports_drcrnote] 1,1,1,3

CREATE PROCEDURE [db_mm].[reports_drcrnote]
	@coid	  int,
	@boid	  int,
	@fyid	  int,
	@Drcrnoteid   int
AS
BEGIN

	select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info,b.gstno
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	where b.coid = @coid and b.boid = @boid

    select hdr.[noteno],format(hdr.[notedate],'dd-MM-yyyy') Dated,supl.name,
           isnull(supl.address1,'') + isnull(supl.address2,'') supladdr,hdr.amount,hdrgrn.billno
    from   [db_mm].[hdr_inwardnote] hdr 
    inner join [db_masters].[supplier] supl on hdr.[partyacid]=supl.id 
	join  [db_mm].[hdr_grn] hdrgrn on hdr.inwardid=hdrgrn.grnid
	where hdr.[noteid]=@Drcrnoteid 

    select itm.itemname,ROW_NUMBER() over(order by dtl.id) serialno,dtl.rate,dtl.quantity,dtl.amount,dtg.orderid,po.itemrate porate,dtl.rate-po.itemrate ratediff, pohdr.ordernumber,
	isnull(dtl.igstamount,0) igst,isnull(dtl.cgstamount,0) cgst,isnull(dtl.sgstamount,0) sgst
    from [db_mm].[dtl_inwardnote] dtl
    inner join   [db_mm].[mst_item] itm on dtl.itemid=itm.id
	join [db_mm].[hdr_inwardnote] hdr on dtl.noteid=hdr.noteid
	join [db_mm].[dtl_grn] dtg on dtl.itemid=dtg.itemid and hdr.inwardid=dtg.grnid
	join [db_mm].[dtl_purchaseorder] po on dtl.itemid=po.itemid and dtg.orderid=po.orderid 
	join [db_mm].[hdr_purchaseorder] pohdr on po.orderid=pohdr.orderid 
	where dtl.[noteid]= @Drcrnoteid

	--INR added by mohit please replase INR with current Currency which using in DR-NOTE
	SELECT db_general.NumberToWords(isnull(hdr.amount,0),'INR') NumberToWords 
   from [db_mm].[hdr_inwardnote] hdr
	WHERE hdr.noteid=@Drcrnoteid  

	select sum(isnull(hdr.igstamount,0)) igst,sum(isnull(hdr.cgstamount,0)) cgst,sum(isnull(hdr.sgstamount,0)) sgst 
	from  
	   [db_mm].[hdr_inwardadvice] hdr 
	where hdr.noteid=@Drcrnoteid 

END


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

CREATE PROCEDURE [db_mm].[reports_grnregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@status varchar(10)='',
	@partyid varchar(200)=null,
	@reportid int=0,
	@itemid varchar(200)=null
AS
BEGIN 

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

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

   --  exec [db_mm].[reports_grnregister] 1,1,1,'04/01/2019','07/28/2019','A','',7

  
   if @reportid=7
    EXEC [db_mktg].[reports_enquiryregister]  @coid,@boid,@fyid,@fromdate,@todate
	ELSE
	 EXEC @sql  @coid,@boid,@fyid,@fromdate,@todate

  
END

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

-- exec [db_mm].[reports_grnregister1] 1,1,2,'04/01/2019','07/28/2019','E'

CREATE PROCEDURE [db_mm].[reports_grnregister1]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@status varchar(10)='',
	@partyid bigint=0,
	@reportid int=1,
	@itemid bigint=0
AS
BEGIN 
declare @sql nvarchar(max)
    begin
	set @sql=' Select ih.[grnnumber],FORMAT(ih.[grndate],''dd/MM/yy'') grndate, (s.name+'' ''+ isnull(s.address1,'''')+''''+isnull(s.address2,'''')+''''+isnull(ct.cityname,'''')+'' GSTIN :''+isnull(s.gsTin,'''')+''''+isnull(s.pin,'''')+''''+s.pan) as partyname,
	           cast(ih.billno as varchar(MAX))+''/  '' + cast(format(ih.billdate,''dd/MM/yy'') as VARCHAR(MAX)) billno, 
			   '''' billdate,ih.poid as PO,
		   	   cast(ih.chalanno as varchar(max)) +'' / ''+ cast(Format(ih.chalandate,''dd/MM/yy'')as varchar(max)) as chalanno, 
			'''' chalandate,
			cast(cast(ih.billamount as decimal(15,2)) as VARCHAR(max)) billamount,
			cast(Cast(isnull(ih.igstamount,0.00) as decimal(15,2)) as varchar(max)) igstamount,
			cast(Cast(isnull(ih.cgstamount,0.00) as decimal(15,2)) as varchar(max)) cgstamount,
			cast(Cast(isnull(ih.sgstamount,0.00) as decimal(15,2)) as varchar(max)) sgstamount,
			cast(cast(ih.totaltaxamount as decimal(15,2)) as varchar(max)) totaltaxamount,
			cast(cast(ih.billpassamount as decimal(15,2)) as varchar(max)) billpassamount,
			cast(cast((select cast(Sum(quantitybilled * itemrate)as decimal(18,2))  taxableamount from db_mm.dtl_grn where grnid=ih.grnid GROUP by grnid) as decimal(18,2)) as VARCHAR(max)) taxableamount
	 FROM  [db_mm].[hdr_grn] ih 
	 inner join db_masters.supplier s on ih.suplid=s.id 
	 left join db_masters.statemaster st on s.state = st.id
	 left join db_masters.city ct on s.city = ct.id'
	 set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end

	 set @sql +=' union all'

	 set @sql +=' select  '''' as grnnumber , '''' grndate,''Total'' partyname ,'''' billno,'''' billdate, ''''PO, '''' chalanno, '''' chalandate,cast(sum(round(ih.billamount,2)) as decimal(18,2)) billamount,
	 cast(sum(ih.igstamount)as decimal(18,2)) igstamount,cast(sum(ih.cgstamount) as DECIMAL(18,2)) cgstamount,cast(sum(ih.sgstamount) as decimal(18,2)) sgstamount,cast(sum(ih.totaltaxamount) as decimal(18,2)) totaltaxamount,cast(sum(ih.billpassamount) as DECIMAL(18,2)) billpassamount,
	 cast(0 as DECIMAL(18,2)) as taxableamount
	 --sum((select cast(Sum(quantitybilled * itemrate)as decimal(18,2)) taxableamount from db_mm.dtl_grn where grnid=ih.grnid GROUP by grnid)) taxableamount
     from  [db_mm].[hdr_grn] ih 
	 inner join db_masters.supplier s on ih.suplid=s.id 
	 left join db_masters.statemaster st on s.state = st.id
	 left join db_masters.city ct on s.city = ct.id'
     set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end
	 End
	 print @sql
	 
	 EXEC sp_executesql @sql

END


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

-- exec [db_mm].[reports_supplierwisependingindent] 1,1,1,'184,185','2019-01-01','2019-12-12'

create PROCEDURE [db_mm].[reports_indentregster]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@type char(1)='p'
AS
BEGIN
 
select hdr.indentorid, hdr.indentnumber , format(indentdate,'dd-MM-yyyy') indentdate,isnull(u.firstname,'') indentorname ,
	(I.itemname +' ' + I.itemcode) itemname,Iu.uom,dtl.quantityrequired,dtl.quantityapproved,
	  isnull(dtl.quantityrequired,0)-isnull(dtl.quantityapproved,0)-isnull(dtl.quantitywoff,0) pendingqty,isnull(dtl.quantitywoff,0) woffqty,dtl.itemid,dtl.itemrate
       from   [db_mm].[hdr_indent]  hdr 
      inner JOIN [db_mm].[dtl_indent] dtl on hdr.indentid = dtl.indentid
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	    left join [db_mm].[mst_itemuom] Iu on dtl.itemid = Iu.id
	  inner join db_masters.users u on hdr.indentorid=u.userid
	  where hdr.coid =@coid and hdr.boid =@boid   and hdr.fyid=@fyid and hdr.indentdate between @fromdate and @todate
END


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

-- exec [db_mm].[reports_indetorwisependingindent] 1,1,1,'184,185','2019-01-01','2019-12-12'

CREATE PROCEDURE [db_mm].[reports_indetorwisependingindent]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@accountid nvarchar(max),
	@type char(1)='p'
AS
BEGIN
 select userid suplid,(firstname+' '+lastname) as Suplname from   [db_masters].users where userid in (select * from dbo.fnSplitString(@accountid , ',')  ) 
	 declare @sql nvarchar(max)
	 set @sql='select hdr.indentorid suplid, hdr.indentnumber , format(indentdate,''dd-MM-yyyy'') indentdate,isnull(u.firstname,'''') indentorname ,
	(I.itemname +'' '' + I.itemcode) itemname,Iu.uom,dtl.quantityrequired,dtl.quantityapproved,
	  isnull(dtl.quantityrequired,0)-isnull(dtl.quantityapproved,0)-isnull(dtl.quantitywoff,0) pendingqty,isnull(dtl.quantitywoff,0) woffqty,dtl.itemid,dtl.itemrate
     from   [db_mm].[hdr_indent]  hdr 
      inner JOIN [db_mm].[dtl_indent] dtl on hdr.indentid = dtl.indentid
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	    left join [db_mm].[mst_itemuom] Iu on on I.receivingunitid = Iu.id
	  inner join db_masters.users u on hdr.indentorid=u.userid
	  where hdr.coid ='+cast(@coid as varchar(5))+' and hdr.boid ='+cast(@boid as varchar(5))+'  
	   and hdr.indentorid in (select * from dbo.fnSplitString(''' + @accountid + ''', '','')  )'
	    
	  if (@type='p')
	  begin
	  set @sql+='and (isnull(dtl.quantityrequired,0)-(isnull(dtl.quantityapproved,0)+isnull(dtl.quantitywoff,0)))>0'
	  end
	   if (@type='w')
	  begin
	  set @sql+='and isnull(dtl.quantitywoff,0)>0'
	  end
	  if (@type='s')
	  begin
	  set @sql+='and (isnull(dtl.quantityrequired,0)-(isnull(dtl.quantityapproved,0)+isnull(dtl.quantitywoff,0)))=0'
	  end
	   --print @sql
	     --set @sql +=  ' and hdr.indentdate >= ''' + cast(@FromDate as varchar(10)) + '''
      --              AND hdr.indentdate <= '''+ cast(@ToDate as varchar(10)) + ''' '
	print @sql
		EXEC sp_executesql @SQL
	

END


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

-- exec [db_mm].[reports_intimationtoiqc] 1,1,1,7447,2931

--  select * from [db_mm].[hdr_grn]
--  select * from [db_mm].[dtl_grn] dtl

CREATE PROCEDURE [db_mm].[reports_intimationtoiqc]
	@coid	int,
	@boid	int,
	@fyid	int,
	@itemid bigint,
	@grnid  bigint
AS
BEGIN

select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info,b.gstno
from db_general.company_branches b
join db_masters.company c on  b.coid = c.coid
where b.coid = @coid and b.boid = @boid

select itm.itemname,dtl.quantityreceived,isnull(itm.packing,'') packsize,bch.batchno,bch.expirydate,bch.mfgdate,bch.arnumber,
isnull(brnd.name,'') brand,isnull(sup.name,'') SuplName,hdr.grnnumber,isnull(bch.sampleqty,0) sampleqty,hdr.grndate,itm.oldcode,u.uom
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
inner join [db_mm].[grnbatchwise] bch on hdr.grnid=bch.grnid  and dtl.itemid=bch.itemid 
inner join [db_masters].[supplier] sup on hdr.suplid = sup.id
left join [db_mm].[mst_brand] brnd on bch.brandid = brnd.id
join [db_mm].[mst_itemuom] u on itm.receivingunitid=u.id
where hdr.boid=@boid and dtl.itemid=@itemid and hdr.grnid=@grnid 

END




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

-- exec [db_mm].[reports_itemwisegrnregister] 1,1,2,'04/01/2019','07/28/2019','E','238'

CREATE PROCEDURE [db_mm].[reports_itemwisegrnregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@status varchar(10)='',
	@partyid varchar(200)=null,
	@reportid int=0,
	@itemid varchar(200)=null
AS
BEGIN 
declare @sql nvarchar(max)
    begin
	set @sql=' Select  itm.itemname,
         cast(ih.[grnnumber]as VARCHAR(20))+ '' - '' +cast(FORMAT(ih.[grndate],''dd/MM/yy'') as varchar(20)) grnno_date, 
         isnull(s.name,'''') + isnull(s.address1,'''') + isnull(s.address2,'''') Supplier,
         cast(Cast(isnull(id.quantitybilled,0.00) as decimal(15,2)) as varchar(max)) quantitybilled,
         cast(Cast(isnull(id.quantityreceived,0.00) as decimal(15,2)) as varchar(max)) quantityreceived,
         ''0.00'' as OKQty,
         cast(cast(isnull(id.quantityrejected,0) as decimal(15,2)) as varchar(max)) quantityrejected
         FROM  [db_mm].[hdr_grn] ih  
         left join db_mm.dtl_grn id on ih.grnid=id.grnid
         left join db_mm.mst_item itm on id.itemid=itm.id
         inner join db_masters.supplier s on ih.suplid=s.id 
         left join db_masters.statemaster st on s.state = st.id
         left join db_masters.city ct on s.city = ct.id'
	 set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end
	 if(@itemid!='')
	 begin
	 set @sql+= ' and id.itemid in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
	 end


	 set @sql +=' union all'

	 set @sql +=' select  '''' as itemname , ''Total'' grnno_date,
	 	   '''' Supplier,
	       cast(sum(id.quantitybilled) as DECIMAL(18,2)) quantitybilled,
	       cast(sum(id.quantityreceived) as decimal(18,2)) quantityreceived, 
		 '''' OkQty,
		 cast(sum(isnull(id.quantityrejected,0)) as decimal(15,2)) quantityrejected 
         from  [db_mm].[hdr_grn] ih 
	     left join db_mm.dtl_grn id on ih.grnid=id.grnid
	     left join db_mm.mst_item itm on id.itemid=itm.id
	     inner join db_masters.supplier s on ih.suplid=s.id 
	     left join db_masters.statemaster st on s.state = st.id
	     left join db_masters.city ct on s.city = ct.id'
     set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end
	 --if(@itemid!='')
	 --begin
	 --set @sql+= ' and id.itemid in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
	 --end
	 End
	 print @sql
	 
	 EXEC sp_executesql @sql

END


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

-- exec [db_mm].[reports_itemwiseindent] 1,1,1,'718,289','2019-01-01','2019-12-12','s'

CREATE PROCEDURE [db_mm].[reports_itemwiseindent]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@itemid nvarchar(max)='718,289',
	@type char(1)='p'
AS
BEGIN

 select id itemid,(itemname+',  Code: '+itemcode +',  Old Code: '+oldcode) as itemname from   [db_mm].[mst_item] where id in (select * from dbo.fnSplitString(@itemid , ',')  )   order by itemname
 declare @sql nvarchar(max)
  set @sql='select hdr.indentorid suplid, hdr.indentnumber , format(indentdate,''dd-MM-yyyy'') indentdate,isnull(u.firstname,'''') indentorname ,
	(I.itemname +'' '' + I.itemcode) itemname,Iu.uom,dtl.quantityrequired,dtl.quantityapproved,
	  isnull(dtl.quantityrequired,0)-isnull(dtl.quantityapproved,0)-isnull(dtl.quantitywoff,0) pendingqty,isnull(dtl.quantitywoff,0) woffqty,dtl.itemid,dtl.itemrate
     from   [db_mm].[hdr_indent]  hdr 
      inner JOIN [db_mm].[dtl_indent] dtl on hdr.indentid = dtl.indentid
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	    left join [db_mm].[mst_itemuom] Iu on I.receivingunitid = Iu.id
	  inner join db_masters.users u on hdr.indentorid=u.userid
	  where hdr.coid ='+cast(@coid as varchar(2))+' and hdr.boid ='+cast(@boid as varchar(2))+'  and hdr.fyid ='+cast(@fyid as varchar(2))+'
	   and dtl.itemid in (select * from dbo.fnSplitString(''' + @itemid + ''', '','')  )'
	    
	  if (@type='p')
	  begin
	  set @sql+='and (isnull(dtl.quantityrequired,0)-(isnull(dtl.quantityapproved,0)+isnull(dtl.quantitywoff,0)))>0'
	  end
	   if (@type='w')
	  begin
	  set @sql+='and isnull(dtl.quantitywoff,0)>0'
	  end
	  if (@type='s')
	  begin
	  set @sql+='and (isnull(dtl.quantityrequired,0)-(isnull(dtl.quantityapproved,0)+isnull(dtl.quantitywoff,0)))=0'
	  end
	  
	     --set @sql +=  ' and hdr.indentdate >= ''' + cast(@fromdate as varchar(10)) + '''
      --           AND hdr.indentdate <=  ''' + cast(@todate as varchar(10)) + ''''
	 
		print @sql
		
		--end 
		 --  and hdr.orderdate between '+@FromDate+' and '+@ToDate+'
		EXEC sp_executesql @SQL

		select hdr.indentorid suplid, hdr.indentnumber , format(indentdate,'dd-MM-yyyy') indentdate,isnull(u.firstname,'') indentorname ,
	(I.itemname +' ' + I.itemcode) itemname,Iu.uom,dtl.quantityrequired,dtl.quantityapproved,
	  isnull(dtl.quantityrequired,0)-isnull(dtl.quantityapproved,0)-isnull(dtl.quantitywoff,0) pendingqty,isnull(dtl.quantitywoff,0) woffqty,dtl.itemid,dtl.itemrate
     from   [db_mm].[hdr_indent]  hdr 
      inner JOIN [db_mm].[dtl_indent] dtl on hdr.indentid = dtl.indentid
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	    left join [db_mm].[mst_itemuom] Iu on I.receivingunitid = Iu.id
	  inner join db_masters.users u on hdr.indentorid=u.userid
	  where hdr.coid =1 and hdr.boid =1  and hdr.fyid =1
	   and dtl.itemid in (select * from dbo.fnSplitString('718,289', ',')  )and (isnull(dtl.quantityrequired,0)-(isnull(dtl.quantityapproved,0)+isnull(dtl.quantitywoff,0)))>0
	   
END


GO
/****** Object:  StoredProcedure [db_mm].[reports_item-wise-minmaxlevel]    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].[reports_item-wise-minmaxlevel]  9,1,1,30
-- =============================================

CREATE PROCEDURE [db_mm].[reports_item-wise-minmaxlevel]
	@reportid INT=0,
	@reportparameters [db_general].[pr_report_parameters] readonly
AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tbl') IS NOT NULL DROP TABLE #tbl
	create table #tbl 
	(	
	[id] int,
	[name] varchar(20),
	[value] nvarchar(max)
	);
	insert into #tbl select * from @reportparameters
	--exec [db_general].[pr_scriptupdate_report]
	--select * from tempreport
	

--	insert into [db_mm].[hdr_reportfilter_param] (coid,	boid,	id,	reportid,	paramname,	paravalue,	isactive)
--values (1,	1,	(select max(id)+1 from [db_mm].[hdr_reportfilter_param]),	9,	'itemtypeids',	1,	1)

declare @query1 as nvarchar(max);
DECLARE @cols AS NVARCHAR(MAX),@colsval AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(name) 
                   from @reportparameters
                    group by name, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')	
		
select @colsval = STUFF((SELECT ','+ QUOTENAME(name) +' varchar(50)' 
                   from @reportparameters
                    group by name, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')	
 set @query = N'SELECT ' + @cols + N' from 
             (
                select value, name
                from #tbl 
            ) x
            pivot 
            (
                max(value)
                for name in (' + @cols + N')
            ) p '
			
SET @query1 = 'IF OBJECT_ID(''tempdb..##tmpory'') IS NOT NULL DROP TABLE ##tmpory;
CREATE TABLE ##tmpory ( ' + @colsval  + ' );'
			exec sp_executesql  @query1 
insert into ##tmpory exec sp_executesql  @query 	

declare @sql nvarchar(max),@fyid int, @coid int,@boid int ,@itemid varchar(500),@storeid int ,@categoryid int,@itemtypeids varchar(100),@userid int

	select @fyid=fyid,@coid=coid,@boid=boid,@itemid=itemid,@storeid=storeid,@categoryid=categoryid,@itemtypeids=itemtypeids from ##tmpory
	
	--select @fyid=2,@coid=1,@boid=1,@itemid='55119,55101,55102',@storeid=2,@categoryid=218,@itemtypeids=1 from ##tmpory
	
		-- 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)
		);
		
	--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)
		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,'''')
		from db_mm.mst_item im
		inner join [db_mm].[mst_itemcategory] ct on ct.id = im.itemcategoryid
		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 @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)) 
			set @sql+= ' and im.id in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
		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
	
		print @sql
		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 * from #itemenquiry

		--For the timing to show reportname on Store Reports by Deepika
	    SELECT functionality  FROM [db_general].[erp_modules_functionalities] WHERE id=@reportid
		
	end











GO
/****** Object:  StoredProcedure [db_mm].[reports_item-wise-minmaxlevel_test]    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].[reports_item-wise-minmaxlevel_test]  9,1,1,30
-- =============================================

CREATE PROCEDURE [db_mm].[reports_item-wise-minmaxlevel_test]
	@reportid INT=0	
AS
BEGIN
	SET NOCOUNT ON;
	

declare @sql nvarchar(max),@fyid int, @coid int,@boid int ,@itemid varchar(500),@storeid int ,@categoryid int,@itemtypeids varchar(100),@userid int

	--select @fyid=fyid,@coid=coid,@boid=boid,@itemid=itemid,@storeid=storeid,@categoryid=categoryid,@itemtypeids=itemtypeids from ##tmpory
	
	select @fyid=2,@coid=1,@boid=1,@itemid='55119,55119,55102',@storeid=2,@categoryid=218,@itemtypeids=1 
	
		-- 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)
		);
		
	--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)
		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,'''')
		from db_mm.mst_item im
		inner join [db_mm].[mst_itemcategory] ct on ct.id = im.itemcategoryid
		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 @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)) 
			set @sql+= ' and im.id in (select * from dbo.fnSplitstring(''' + cast(@itemid as varchar(100)) + ''','','')) '
		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
	
		print @sql
		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 * from #itemenquiry
		
		
	end











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

-- exec [db_mm].[reports_itemwisependingpo] 1,1,1,'2019-01-01','2019-12-12','718,289','s'

CREATE PROCEDURE [db_mm].[reports_itemwisependingpo]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date,
	@todate date,
	@itemid nvarchar(max)='718,289',
	@type char(1)='p'
AS
BEGIN

 select id itemid,(itemname+',  Code: '+itemcode +',  Old Code: '+oldcode) as itemname from   [db_mm].[mst_item] where id in (select * from dbo.fnSplitString(@itemid , ',')  )   order by itemname
 declare @sql nvarchar(max)
  set @sql=' select hdr.suplid, hdr.ordernumber , format(orderdate,''dd-MM-yyyy'') orderdate,(hdr.suplname+'' ''+hdr.supladdress1+'' ''+hdr.supladdress2+'' ''+hdr.suplcity+'' ''+hdr.suplstate) as Suplname ,
	(I.itemname +'' ''+ I.itemcode) itemname,dtl.itemuom,dtl.orderedquantity,dtl.receivedquantity,
	  isnull(dtl.orderedquantity,0)-isnull(dtl.receivedquantity,0)-isnull(dtl.writeoffquantity,0) pendingqty,isnull(dtl.writeoffquantity,0) woffqty,dtl.itemid,dtl.itemrate
 from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id		
	  where hdr.coid ='+cast(@coid as varchar(5))+' and hdr.boid ='+cast(@boid as varchar(5))+'
	   and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))>0
	   and dtl.itemid in (select * from dbo.fnSplitString('''+@itemid+''', '','')  ) '

	    if (@type='p')
	  begin
	  set @sql+='and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))>0'
	  end
	   if (@type='w')
	  begin
	  set @sql+='and isnull(dtl.writeoffquantity,0)>0'
	  end
	  if (@type='s')
	  begin
	  set @sql+='and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))=0'
	  end
	  
	     set @sql +=  ' and hdr.orderdate >= ''' + cast(@fromdate as varchar(10)) + '''
                 AND hdr.orderdate <=  ''' + cast(@todate as varchar(10)) + ''''
	 -- if  @fromdate IS NOT NULL and @todate is not null 
	 -- begin
	  --set @sql +=  ' and hdr.orderdate >= ' + cast(@FromDate as datetime) + '
   --                 AND hdr.orderdate <= '+ cast(@ToDate as datetime) + ' '
		print @sql
		
		--end 
		 --  and hdr.orderdate between '+@FromDate+' and '+@ToDate+'
		EXEC sp_executesql @SQL


	   
END


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

-- select * from [db_mm].[dtl_inwardadvice]
-- exec [db_mm].[reports_nonmovingstock]1,1,1

CREATE PROCEDURE [db_mm].[reports_nonmovingstock]
	@coid	  int,
	@boid	  int,
	@fyid	  int
AS
BEGIN
    IF OBJECT_ID('tempdb..#tempnonmovingstock') IS NOT NULL DROP TABLE #tempstockledger
	
	create table #tempnonmovingstock 
	(
		id			bigint,
		itemid		bigint,
		itemcode	varchar(100),
		oldcode	    varchar(100),
		itemname	 varchar(300),
		brandname	 varchar(50),
		arnumber	varchar(100),
		lastpurchaserate decimal(7,3),
		lastpurchasedate date,
		lastissuedate date,
		stockinhand decimal(12,3),
		location    varchar(100),
		lastsaledate date



	);
	insert into #tempnonmovingstock(itemid,itemcode,oldcode,itemname,location)
	 select id, [itemcode],[oldcode],[itemname],location
	  from [db_mm].[mst_item]   
	
	update #tempnonmovingstock 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   #tempnonmovingstock.itemid = itemid),0)

update #tempnonmovingstock set lastpurchaserate=isnull(itemrate,0),lastpurchasedate= h.grndate from (select max(grndate) grndate,grnid  from db_mm.hdr_grn group by grndate,grnid)h 
 join db_mm.dtl_grn  d on h.grnid=d.grnid 
where #tempnonmovingstock.itemid=d.itemid 

update #tempnonmovingstock set lastissuedate=   h.issuancedate from (select max(issuancedate) issuancedate,issuanceid  from db_mm.hdr_issuance group by issuancedate,issuanceid)h 
join db_mm.dtl_issuance  d on h.issuanceid=d.issuanceid 
where #tempnonmovingstock.itemid=d.itemid

select * from #tempnonmovingstock 
END


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

-- exec [db_mm].[reports_purchaseRegister] 1,1,2

Create PROCEDURE [db_mm].[reports_pendingindentregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate datetime,
	@todate   datetime
	
AS
BEGIN
      select hdr.indentnumber,hdr.indentdate,dept.deptname,itm.itemname ,
   isnull(dtl.quantityapproved,0) - isnull(dtlpo.orderedquantity,0) pendingqty,
   dtl.quantitywoff,dtlpo.orderedquantity
   from [db_mm].[hdr_indent] hdr 
   inner join [db_mm].[dtl_indent] dtl on hdr.indentid = dtl.indentid
   inner join [db_mm].[dtl_purchaseorder] dtlpo on hdr.indentid = dtlpo.indentid
   inner join db_masters.department dept on hdr.departmentid =dept.id
   inner join db_mm.mst_item itm on dtl.itemid= itm.id
   inner join [db_mm].[mst_brand] brnd on dtl.brandid = brnd.id
   where hdr.coid=@coid and hdr.boid=@boid and hdr.indentdate= @fromdate and hdr.indentdate=@todate

END


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

-- exec [db_mm].[reports_purchaseRegister] 1,1,2

CREATE PROCEDURE [db_mm].[reports_purchase]
	@coid	int,
	@boid	int,
	@fyid	int,
	@reportid	int
AS
BEGIN 
 
 select columnname,displayname,displaywidth,alignment FROM db_mm.hdr_reportcolumn_definition h
  join db_mm.dtl_reportcolumn_definition d on h.id=d.headerid join
db_general.mst_reportcolumns m  on d.fieldid=m.id
where reportid=1

declare @sql1 nvarchar(max)
declare @sql nvarchar(max)=(select querylogic FROM db_mm.hdr_reportcolumn_definition)
set @sql1=@sql 
--set @sql+=(select conditionlogic FROM db_mm.hdr_reportcolumn_definition)
print @sql1
		EXEC sp_executesql @SQL1
		--set @sql+='where hdr.coid=' + cast(@coid as varchar(3)) + ' and hdr.boid='+ cast(@boid as varchar(3)) +''
	  select footer FROM            db_mm.hdr_reportcolumn_definition 
  
 
 select hdr.ordernumber , (hdr.orderdate) orderdate,(hdr.suplname) suplname ,(I.itemcode) itemname,dtl.itemuom,cast(dtl.orderedquantity as decimal(15,3)) orderedquantity,
	  round(dtl.receivedquantity,3) receivedquantity,cast(dtl.itemrate as decimal(18,2))  baserate,  cast(hdr.poamount as decimal(18,2)) totalamount ,
            cast(dtl.netrate as decimal(18,2)) netrate,
			
			cast(dtl.netrate * (dtl.orderedquantity - isnull(dtl.writeoffquantity,0)) as decimal(18,2)) amount
 from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id  
	  where hdr.coid=' + cast(@coid as varchar(3)) + ' and hdr.boid='+ cast(@boid as varchar(3)) +'
END


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

-- exec [db_mm].[reports_purchaseRegister] 1,1,1,'','','184,185',2,0

CREATE PROCEDURE [db_mm].[reports_purchaseRegister]
	@coid	int=1,
	@boid	int=1,
	@fyid	int=1,
	@fromdate datetime=null,
	@todate datetime=null,
	@partyid varchar(max)='184,185',
	@reportid int=2,
	@itemid bigint=0
	
AS
BEGIN    
 
 select columnname,displayname,displaywidth,alignment FROM db_mm.hdr_reportcolumn_definition h
  join db_mm.dtl_reportcolumn_definition d on h.id=d.headerid join
db_general.mst_reportcolumns m  on d.fieldid=m.id
where reportid=@reportid

--declare @param varchar(500)=(select   'Parameter_name' = name 

--  from sys.parameters where object_id = object_id('[db_mm].[reports_indentregster]'))



declare @sql nvarchar(max)=(select querylogic FROM db_mm.hdr_reportcolumn_definition where reportid=@reportid)
print @sql 
EXEC  @sql @coid,@boid,@fyid,@fromdate,@todate,@partyid,@reportid,@itemid 

select footer FROM            db_mm.hdr_reportcolumn_definition  where reportid=@reportid
  
END


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

-- exec [db_mm].[reports_purchaseRegister] 1,1,2

CREATE PROCEDURE [db_mm].[reports_purchaserRegister1]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@partyid bigint=0,
	@reportid int=1,
	@itemid bigint=0
AS
BEGIN  
 select hdr.ordernumber , format(hdr.orderdate,'dd-MM-yyyy') orderdate,(hdr.suplname) suplname ,(I.itemcode+' '+i.itemname) itemname,dtl.itemuom,cast(dtl.orderedquantity as decimal(15,3)) orderedquantity,
	  round(dtl.receivedquantity,3) receivedquantity,cast(dtl.itemrate as decimal(18,2))  baserate,  cast(hdr.poamount as decimal(18,2)) totalamount ,
            cast(dtl.netrate as decimal(18,2)) netrate,		
			cast(dtl.netrate * (dtl.orderedquantity - isnull(dtl.writeoffquantity,0)) as decimal(18,2)) amount
 from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id  
	  where hdr.coid=@coid and hdr.boid=@boid
	  union all
	  select  0 as ordernumber , '' orderdate,'Total' suplname ,'' itemname,'' itemuom,sum(dtl.orderedquantity) orderedquantity,
	  sum(round(dtl.receivedquantity,3)) receivedquantity,0  baserate,  sum(cast(hdr.poamount as decimal(18,2))) totalamount ,
           0 netrate,		
			sum(cast(dtl.netrate * (dtl.orderedquantity - isnull(dtl.writeoffquantity,0)) as decimal(18,2))) amount
 from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id  
	  where hdr.coid=@coid and hdr.boid=@boid
END


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

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

  CREATE PROCEDURE [db_mm].[reports_ResumeRegister]
  	@coid	int=1,
  	@boid	int=1,
  	@fyid	int=1,
  	@fromdate datetime=null,
  	@todate datetime=null,
  	@reportid int=2,
  	@itemid bigint=0  	
  AS
  BEGIN    
   
    select hdr.id,category = stuff((select ',' + cat.name from [db_hr].[dtl_resumecategory] dtl 
    join [db_hr].[mst_resumecategory] cat on dtl.categoryid = cat.id where dtl.resumeid = hdr.id 
    FOR XML PATH ('')), 1, 1, ''),hdr.name,hdr.currentlocation,hdr.phone as contact,hdr.totexpyy,hdr.currentsalary,
    st.name as status,st.colorcode,res.name as source,
    qualification=stuff((select ',' + mt.qualification from [db_hr].[dtl_resumequalification] dtl 
    join [db_hr].[mst_qualification] mt on dtl.qualificationid = mt.id where dtl.resumeid = hdr.id 
    FOR XML PATH ('')), 1, 1, ''),hdr.statusid,hdr.remarks
    from [db_hr].[hdr_resume] hdr
    left join [db_hr].[mst_resumecategory] cat on hdr.postappliedfor = cat.id
    left join [db_hr].[mst_resumesources] res on hdr.sourceid = res.id 
    left join [db_hr].[mst_skillsets] sks on hdr.skillsetid = sks.id
    left join [db_hr].[mst_resumestatus] st on hdr.statusid = st.id
    
  END


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

-- select * from [db_mm].[dtl_inwardadvice]
-- exec [db_mm].[reports_stockvaluation]1,1,1,''

CREATE PROCEDURE [db_mm].[reports_stockvaluation]
	@coid	  int,
	@boid	  int,
	@fyid	  int,
	@storeid int
AS
BEGIN
    IF OBJECT_ID('tempdb..#tempstockvaluation') IS NOT NULL DROP TABLE #tempstockvaluation
	
	create table #tempstockvaluation 
	(
		id			bigint,
		itemid		bigint,
		itemcode	varchar(100),
		oldcode	    varchar(100),
		itemname	 varchar(300),
		arnumber	varchar(100),
		lastpurchaserate decimal(7,3),
		stockinhand decimal(12,3),
		openingstock decimal(12,3),
		openingstockvalue decimal (12,3),
		receivedqty decimal(12,3),
		receivedqtyvalue decimal(12,3),
		issueqty   decimal(12,3),
		issueqtyvalue   decimal(12,3),
		closingvalue decimal(12,3),
		lastpurchasedate date

	);
	insert into #tempstockvaluation(itemid,itemcode,oldcode,itemname)
	 select id, [itemcode],[oldcode],[itemname]
	  from [db_mm].[mst_item]   
	
	update #tempstockvaluation 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   #tempstockvaluation.itemid = itemid),0)

	-- update opening stock from db_mm.item_stk_trn table, trytype = 16 for opening stock
		update #tempstockvaluation 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 #tempstockvaluation.itemid = stk.itemid 
		--update opening stock value

		
        update #tempstockvaluation 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 #tempstockvaluation.itemid = stk1.itemid


		 --issueqty 
		update #tempstockvaluation 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 #tempstockvaluation.itemid = stk2.itemid

 		update #tempstockvaluation set lastpurchaserate=isnull(d.itemrate,0) from (select max(grndate) grndate,h.grnid,d.itemrate,d.itemid from db_mm.hdr_grn h
        join db_mm.dtl_grn  d on h.grnid=d.grnid group by grndate,h.grnid,d.itemrate,d.itemid)d
        where #tempstockvaluation.itemid=d.itemid 
 
        update #tempstockvaluation set openingstockvalue=openingstock*lastpurchaserate,receivedqtyvalue=receivedqty*lastpurchaserate,issueqtyvalue=issueqty*lastpurchaserate,
        closingvalue=stockinhand*lastpurchaserate

         select * from #tempstockvaluation where closingvalue>0
END


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

-- exec [db_mm].[reports_supplierwisegrnregister] 1,1,2,'04/01/2019','07/28/2019','E'

CREATE PROCEDURE [db_mm].[reports_supplierwisegrnregister]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@status varchar(10)='',
	@partyid varchar(200)=null,
	@reportid int=0,
	@itemid varchar(200)=null
AS
BEGIN 
declare @sql nvarchar(max)
    begin
    set @sql=' Select  (s.name+'' ''+ isnull(s.address1,'''')+''''+isnull(s.address2,'''')+''''+isnull(ct.cityname,'''')+'' GSTIN :''+isnull(s.gsTin,'''')+''''+isnull(s.pin,'''')+''''+s.pan) as Supplier,
	        cast(ih.[grnnumber] as varchar(MAX))+'' - '' + cast(format(ih.[grndate],''dd/MM/yy'') as VARCHAR(MAX)) grnno_date,
	        cast(ih.billno as varchar(MAX))+'' - '' + cast(format(ih.billdate,''dd/MM/yy'') as VARCHAR(MAX)) billno_date,
		   	cast(ih.chalanno as varchar(max)) +'' - ''+ cast(Format(ih.chalandate,''dd/MM/yy'')as varchar(max)) as chalanno_date,
			cast(cast((select cast(Sum(quantitybilled * itemrate)as decimal(18,2))  taxableamount 
			from db_mm.dtl_grn where grnid=ih.grnid GROUP by grnid) as decimal(18,2)) as VARCHAR(max)) taxableamount,
			cast(Cast(isnull(ih.igstamount,0.00) as decimal(15,2)) as varchar(max)) igstamount,
			cast(Cast(isnull(ih.cgstamount,0.00) as decimal(15,2)) as varchar(max)) cgstamount,
			cast(Cast(isnull(ih.sgstamount,0.00) as decimal(15,2)) as varchar(max)) sgstamount,
			cast(cast(ih.totaltaxamount as decimal(15,2)) as varchar(max)) totaltaxamount,
			cast(cast(ih.billpassamount as decimal(15,2)) as varchar(max)) billpassamount,
			cast(cast(ih.billamount as decimal(15,2)) as VARCHAR(max)) billamount
	 FROM  [db_mm].[hdr_grn] ih 
	 inner join db_masters.supplier s on ih.suplid=s.id 
	 left join db_masters.statemaster st on s.state = st.id
	 left join db_masters.city ct on s.city = ct.id'
	 set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end

	 set @sql +=' union all'

	 set @sql +=' select '''' Supplier, '''' grnno_date,''Total'' billno_date ,'''' chalanno_date,
	 --cast(0 as DECIMAL(18,2)) as taxableamount,
	 cast(sum(id.quantitybilled * id.itemrate)as decimal(18,2)),
	 cast(sum(ih.igstamount)as decimal(18,2)) igstamount,cast(sum(ih.cgstamount) as DECIMAL(18,2)) cgstamount,cast(sum(ih.sgstamount) as decimal(18,2)) sgstamount,cast(sum(ih.totaltaxamount) as decimal(18,2)) totaltaxamount,cast(sum(ih.billpassamount) as DECIMAL(18,2)) billpassamount,	 
	 cast(sum(round(ih.billamount,2)) as decimal(18,2)) billamount
	 
     from  [db_mm].[hdr_grn] ih 
	 left join db_mm.dtl_grn id on ih.grnid=id.grnid
	 inner join db_masters.supplier s on ih.suplid=s.id 
	 left join db_masters.statemaster st on s.state = st.id
	 left join db_masters.city ct on s.city = ct.id'
     set @sql +='  where ih.coid = '+ cast(@coid as varchar(5)) +' and ih.boid='+ cast(@boid as varchar(5))+' and ih.grndate >='''+ cast(@fromdate as varchar(20))+''' and ih.grndate <='''+ cast(@todate as varchar(20))+''''
	 if(@status!='' and @status!='A')
	 begin 
	 set @sql +=' and ih.status='+''''+cast(@status as VARCHAR(10))+''''
	 end
	 End
	 print @sql
	 
	 EXEC sp_executesql @sql

END


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

-- exec [db_mm].[reports_supplierwisependingorders] 1,1,1,'184,185','2019-01-01','2019-12-12'

CREATE PROCEDURE [db_mm].[reports_supplierwisependingorders]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate datetime=null,
	@todate datetime=null,
	@partyid nvarchar(max)='184,185',
	@reportid int=2,
	@itemid bigint=0
AS
BEGIN

 select id suplid,0 ordernumber,'' orderdate, (name+' '+address1 +' '+address2+' '+gstin) as Suplname,0 itemid,(char(027)+char(064)+'  '+(name+' '+address1 +' '+address2+' '+gstin)) as itemname,'' itemuom
		,0 itemrate,0 orderedquantity,0 receivedquantity,0 pendingqty from   [db_masters].[supplier] where id in (select * from dbo.fnSplitString(@partyid , ',')  )
union all
   select hdr.suplid, hdr.ordernumber , orderdate,isnull(hdr.suplname,'') Suplname ,dtl.itemid,
	(I.itemname +' '+ I.itemcode) itemname,dtl.itemuom,dtl.itemrate,dtl.orderedquantity,dtl.receivedquantity,
	  isnull(dtl.orderedquantity,0)-isnull(dtl.receivedquantity,0)-isnull(dtl.writeoffquantity,0) pendingqty
      from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	  where hdr.coid =cast(@coid as varchar(5)) and hdr.boid =cast(@boid as varchar(5))
	   and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))>0
	   and hdr.suplid in (select * from dbo.fnSplitString(@partyid, ',')  ) order by suplid,ordernumber,Suplname
	   --print @sql
	     --set @sql +=  ' and hdr.orderdate >= ' + cast(@FromDate as datetime) + '
      --              AND hdr.orderdate <= '+ cast(@ToDate as datetime) + ' '
	 -- if  @fromdate IS NOT NULL and @todate is not null 
	 -- begin
	  --set @sql +=  ' and hdr.orderdate >= ' + cast(@FromDate as datetime) + '
   --                 AND hdr.orderdate <= '+ cast(@ToDate as datetime) + ' '
		--print @sql
		
		--end 

		--EXEC sp_executesql @SQL
	

	   
END


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

-- exec [db_mm].[reports_supplierwisependingorders1] 1,1,1,'2019-01-01','2019-12-12','180'

CREATE PROCEDURE [db_mm].[reports_supplierwisependingorders1]
	@coid	int,
	@boid	int,
	@fyid	int,
	@fromdate date=null,
	@todate date=null,
	@accountid nvarchar(max)='184,185',
	@type char(1)='p'
AS
BEGIN

update [db_mm].[dtl_purchaseorder] set receivedquantity=0 where receivedquantity is null

 select id suplid,(name+' '+address1 +' '+address2+' '+gstin) as Suplname from   [db_masters].[supplier] where id in (select * from dbo.fnSplitString(@accountid , ',')  ) 
	 declare @sql nvarchar(max)
	 set @sql='select hdr.suplid, hdr.ordernumber , format(orderdate,''dd-MM-yyyy'') orderdate,isnull(hdr.suplname,'''') Suplname ,
	(I.itemname +'' '' + I.itemcode) itemname,dtl.itemuom,isnull(dtl.orderedquantity,0),isnull(dtl.receivedquantity,0),
	  isnull(dtl.orderedquantity,0)-isnull(dtl.receivedquantity,0)-isnull(dtl.writeoffquantity,0) pendingqty,isnull(dtl.writeoffquantity,0) woffqty,dtl.itemid,isnull(dtl.itemrate,0)
      from   [db_mm].[hdr_purchaseorder]  hdr 
      inner JOIN [db_mm].[dtl_purchaseorder] dtl on hdr.orderid = dtl.orderid 
      inner join [db_mm].[mst_item] I on dtl.itemid = I.id	
	  where hdr.coid ='+cast(@coid as varchar(5))+' and hdr.boid ='+cast(@boid as varchar(5))+'	   
	   and hdr.suplid in (select * from dbo.fnSplitString(''' + @accountid + ''', '','')  )'
	  if (@type='p')
	  begin
	  set @sql+='and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))>0'
	  end
	   if (@type='w')
	  begin
	  set @sql+='and isnull(dtl.writeoffquantity,0)>0'
	  end
	  if (@type='s')
	  begin
	  set @sql+='and (isnull(dtl.orderedquantity,0)-(isnull(dtl.receivedquantity,0)+isnull(dtl.writeoffquantity,0)))=0'
	  end
	   --print @sql
	     set @sql +=  ' and hdr.orderdate >= ''' + cast(@FromDate as varchar(10)) + '''
                    AND hdr.orderdate <= '''+ cast(@ToDate as varchar(10)) + ''' '
	 -- if  @fdate IS NOT NULL and @tdate is not null 
	 -- begin
	 -- set @sql +=  ' and hdr.orderdate >= ' + cast(@fdate as datetime) + '
  --                  AND hdr.orderdate <= '+ cast(@tdate as datetime) + ' '		
		--end 
		--print @sql
		EXEC sp_executesql @SQL
	

	   
END


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

--exec [db_mt].[pr_commonapiticket] 1,1,1

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

	select isnull(max(mtno),0) as mtno from [db_mt].[tickets] 

	SELECT id,MCCatgName FROM [db_masters].[machinecategory]
	
	select id,MachineName from [db_masters].[mst_machine]

	SELECT id,rootcause FROM [db_mt].[mst_rootcause]

	SELECT id,teamleaderid,teamname FROM [db_mt].[mst_mt_team]

	SELECT id,mtstatus,mostatus FROM [db_mt].[mst_mostatus]

	SELECT id,empno,empname,designationid,current_address1,current_address2,current_state,current_city,current_country,deptid from [db_masters].[employee]

	SELECT id,deptname from db_masters.department

	SELECT id,mtpriority FROM [db_mt].[mst_Priority]

	SELECT id,freqname from [db_mt].[mst_Frequency]
end
	
GO
/****** Object:  StoredProcedure [db_mt].[pr_getticketdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- exec [db_mt].[pr_getticketdata] 1,1,1
CREATE PROCEDURE [db_mt].[pr_getticketdata] 
    @coid int,
	@boid int,	
	@id int
AS
BEGIN
	SET NOCOUNT ON;
	begin  
	 select t.id,t.mtno,t.mtdate,t.mttime,t.mttype,t.mtcatg,mc.id as mccatgid,mc.MCCatgName,t.mtdeptid,d.name as deptname,
	 t.mtassetid,m.MachineName,t.mtduedate,t.mtduetime,t.mttempid,t.mtassetlocation,t.mtpriorityid,p.mtpriority,
	 t.mtfreqid,f.freqname,t.mtownerid,e.name as empname,t.mtstatusid,mo.mtstatus,t.mtlastmaintdate,t.mtproblem,
	 t.mtdelaydays,t.mtdocuploaded,hdr.mono,hdr.modate,hdr.motime,hdr.mopriorityid,hdr.moqueueno,te.teamname
	 FROM [db_mt].[tickets] t
	 left JOIN [db_mt].[hdr_mo] hdr on t.id=hdr.mtid
	 left join [db_mt].[dtl_mo] dt on hdr.id=dt.moid
	 left join [db_mt].[mst_mt_team] te on dt.moassignedteamid=te.id
	 left join [db_masters].[mst_machine] m on t.mtassetid=m.id 
	 left JOIN [db_masters].[machinecategory] mc on m.MCCatgId=mc.id
	 left join db_general.master_employee e on t.mtownerid= e.empid
	 left join [db_mt].[mst_mostatus] mo on t.mtstatusid=mo.id
	 left join db_hr.mstDept d on t.mtdeptid=d.id
	 left JOIN [db_mt].[mst_Frequency] f on t.mtfreqid=f.id
	 LEFT JOIN [db_mt].[mst_Priority] p on t.mtpriorityid=p.id
	 where t.coid = cast(@coid as varchar(5)) and t.boid = cast(@boid as varchar(5)) and t.id=@id

	 SELECT id,MCCatgName FROM [db_masters].[machinecategory] where coid = cast(@coid as varchar(5)) and boid = cast(@boid as varchar(5))
	
	select id,MachineName from [db_masters].[mst_machine] where coid = cast(@coid as varchar(5)) and boid = cast(@boid as varchar(5))

	SELECT id,empno,empname,designationid,current_address1,current_address2,current_state,current_city,current_country 
	from [db_masters].[employee] where coid = cast(@coid as varchar(5)) and boid = cast(@boid as varchar(5))

	SELECT id,deptname from db_masters.department where coid = cast(@coid as varchar(5)) and boid = cast(@boid as varchar(5))

	SELECT id,mtpriority FROM [db_mt].[mst_Priority] where coid = cast(@coid as varchar(5)) and boid = cast(@boid as varchar(5))

	SELECT id,teamleaderid,teamname from [db_mt].[mst_mt_team]

	SELECT isnull(max(mono),0) as mono from [db_mt].[hdr_mo]
	 	
	END
end
GO
/****** Object:  StoredProcedure [db_mt].[pr_getticketslist]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Deepika>
-- Create date: <Create Date,13-01-2020>
-- Description:	<Description,Get Maintenance Ticket data>
-- [db_mt].[pr_getticketslist] 1,10,1,1,'id','desc','Y'
-- =============================================
CREATE PROCEDURE [db_mt].[pr_getticketslist]
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='t.id',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql = 'Select t.id,t.mtno,t.mtdate,t.mttime,t.mtduedate,t.mtmoid,t.mttype,t.mtcatg,m.MachineName,h.mono,
	 h.modate,t.mtstatusid,mo.mtstatus,mo.mostatus,t.mtdelaydays,te.teamname from [db_mt].[tickets] t 
	 left join [db_mt].[hdr_mo] h on t.mtmoid=h.id
	 left join [db_mt].[dtl_mo] dt on h.id=dt.moid
	 left join [db_mt].[mst_mt_team] te on dt.moassignedteamid=te.id
	 left join [db_masters].[mst_machine] m on t.mtassetid=m.id
	 left join [db_mt].[mst_mostatus] mo on t.mtstatusid=mo.id'
	 
		set @sql += ' where t.coid = ' + cast(@coid as varchar(5)) + ' and t.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and t.id = ' + 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(t.[id])records from [db_mt].[tickets] t	
	
END



GO
/****** Object:  StoredProcedure [db_mt].[pr_savemaintenanceticket]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE  PROCEDURE [db_mt].[pr_savemaintenanceticket] 
    @statementtype nvarchar(50),
	@coid int,
	@boid int,
	@header_tvp [db_mt].[hdr_ticket_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @id int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max) , @mtno int
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin

		set @mtno = (SELECT ISNULL(MAX(mtno), 0) + 1 as mtno from [db_mt].[tickets] where coid=@coid and boid=@boid) 

		    insert into [db_mt].[tickets] (mtno,mtdate,mttime,mtduedate,mtduetime,mtmoid,mttype,mtcatg,mttempid,mtdeptid,mtassetid,mtassetlocation,
			mtfreqid,mtpriorityid,mtownerid,mtstatusid,mtlastmaintdate,mtproblem,mtdelaydays,mtdocuploaded,[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon])
			Select @mtno,mtdate,mttime,mtduedate,mtduetime,mtmoid,mttype,mtcatg,mttempid,mtdeptid,mtassetid,mtassetlocation,
			mtfreqid,mtpriorityid,mtownerid,mtstatusid,mtlastmaintdate,mtproblem,mtdelaydays,mtdocuploaded,[coid],[boid],[createdby],GETDATE(),[modifiedby],[modifiedon]
			from @header_tvp
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding ticket data.', 16, 1)
				RETURN
				END
				SELECT @id= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting id.', 16, 1)
				RETURN
				END
				end 
	 else
		 Begin -- begin of update .
			select @id = id from @header_tvp
			select mtno,mtdate,mttime,mtduedate,mtduetime,mtmoid,mttype,mtcatg,mttempid,mtdeptid,mtassetid,mtassetlocation,
			mtfreqid,mtpriorityid,mtownerid,mtstatusid,mtlastmaintdate,mtproblem,mtdelaydays,mtdocuploaded,[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon]
				from [db_mt].[tickets] where id = @id
				 EXCEPT select mtno,mtdate,mttime,mtduedate,mtduetime,mtmoid,mttype,mtcatg,mttempid,mtdeptid,mtassetid,mtassetlocation,
			mtfreqid,mtpriorityid,mtownerid,mtstatusid,mtlastmaintdate,mtproblem,mtdelaydays,mtdocuploaded,[coid],[boid],[createdby],[createdon],[modifiedby],[modifiedon]
				 from @header_tvp
			SELECT @rowcnt = @@ROWCOUNT
			-- data needs to update if query returns a row  
			IF @rowcnt > 0
				BEGIN -- begin of row count
					-- updating existing records from Training Calender table and checking @@ERROR 
					UPDATE [db_mt].[tickets] set 
					          [mtno]= a.[mtno],
                              [mtdate]=a.[mtdate],
                              [mttime]=a.[mttime],
                              [mtduedate]=a.[mtduedate],
							  [mtduetime]=a.[mtduetime],
							  [mtmoid]=a.[mtmoid],
							  [mttype]=a.[mttype],
							  [mtcatg]=a.[mtcatg],
							  [mttempid]=a.[mttempid],
							  [mtdeptid]=a.[mtdeptid],
							  [mtassetid]=a.[mtassetid],
                              [mtassetlocation]=a.[mtassetlocation],
                              [mtfreqid]=a.[mtfreqid],
                              [mtpriorityid]=a.[mtpriorityid],
                              [mtownerid]=a.[mtownerid],
                              [mtstatusid]=a.[mtstatusid],
                              [mtlastmaintdate]=a.[mtlastmaintdate],
							  [mtproblem]=a.[mtproblem],
							  [mtdelaydays]=a.[mtdelaydays],
							  [mtdocuploaded]=a.[mtdocuploaded],
							  [coid]=a.[coid],
							  [boid]=a.[boid],
                              [createdby]=a.[createdby],
                              [createdon]=a.[createdon],
                              [modifiedby]=a.[modifiedby],
                              [modifiedon]=getdate()
					FROM   @header_tvp a
					WHERE [db_mt].[tickets].id =a.id 
					-- Rollback the transaction if there were any errors
					IF @@ERROR <> 0
						BEGIN
							-- Rollback the transaction
							ROLLBACK
							-- Raise an error and return
							RAISERROR ('Error while updating existing ticket record.', 16, 1)
							RETURN
					   END
				END -- end of row count
			end
	COMMIT
END

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

GO
/****** Object:  StoredProcedure [db_production].[batchwisegrossrequirement]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--[db_production].[batchwisegrossrequirement] 1,1,1,1
CREATE procedure [db_production].[batchwisegrossrequirement]
@coid int,
@boid int,
@fyid int,
@woid bigint = null,
@level int= 1,
@batchid bigint = null,
@userid int = 0,
@accesstoken varchar(200) = null
as 
Begin
	SET NOCOUNT ON;
	declare @msg varchar(200);
	IF @woid IS NULL  and @batchid is null
		BEGIN  
			set @msg = 'You must provide either workorder id or job id to calculate gross requirement'
			PRINT @msg  
			RETURN  @msg
		END  

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