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

		IF OBJECT_ID('tempdb..#grossrequirement') IS NOT NULL DROP TABLE #grossrequirement
		create table #grossrequirement 
		(
			itemid			bigint,
			itemname		varchar(500),
			itemcode		varchar(25),
			oldcode			varchar(20),
			itemtype		varchar(30),
			itemtypeid		int,
			quantity			decimal(15,3),
			stockinhand			decimal(15,3),
			minimumStk			decimal(15,3),
			pendingcustorder	decimal(15,3),
			onPO				decimal(15,3),
			atRect				decimal(15,3),
			underIQC			decimal(15,3),
			netReqd				decimal(15,3)
		)

		
		-- get items from work order detail table
		insert into #wodetails (itemid,bomid,quantity,bombatchsize,mfactor,rowno) 
		select wo.itemid, isnull(wo.bomid,0), sum(quantity) , 1,1, ROW_NUMBER() OVER(ORDER BY wo.itemid,wo.bomid) rownum 
		from db_production.dtl_workorder wo 
		where woid = coalesce(@woid,woid) and batchid = coalesce(@batchid,batchid) 
		group by wo.itemid,wo.bomid

		--update bom ids in #wodetails
		update #wodetails set bomid = a.bomid 
		from (select productid, max(bomid) bomid from  db_mm.hdr_bom group by productid) a 
		where #wodetails.itemid = a.productid and isnull(#wodetails.bomid,0)=0

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

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

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

		update #wodetails set chk = 1 where bomid = 0

		--select * from #grossrequirement

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

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

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

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

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


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

			end
			set @minrowid = @minrowid + 1
		end

        --select * from #tempbom

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

		-- updating itemname, itemcode, oldcode from item master
		update #grossrequirement set itemname = a.itemname, itemcode = a.itemcode,
		oldcode= a.oldcode from db_mm.mst_item a where #grossrequirement.itemid = a.id
		-- update itemtypeid from db_mm.item_types
		update #grossrequirement set itemtypeid = a.typeid from
		(select itemid, min(typeid) typeid from db_mm.item_types where typeid > 0  group by itemid) a 
		where #grossrequirement.itemid = a.itemid 
		-- update itemtype from db_mm.mst_itemtypes
		update #grossrequirement set itemtype = isnull(a.name,'') 
		from db_mm.mst_itemtypes a where #grossrequirement.itemtypeid = a.id
				

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

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

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

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

		select #grossrequirement.* from #grossrequirement join db_mm.mst_itemtypes t 
        on #grossrequirement.itemtypeid = t.id
        where itemtype != '' and t.includeingrossrqt=1
		order by itemtype
		

		-- item can be of multiple types

End






GO
/****** Object:  StoredProcedure [db_production].[batchwisenetrequirement]    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_production].[batchwisenetrequirement] 1,1,1,62,1
-- =============================================
CREATE procedure [db_production].[batchwisenetrequirement]
@coid int,
@boid int,
@fyid int,
@batchid bigint,
@level int= 1,
@userid int = 0,
@accesstoken varchar(200) = null
as 
Begin
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#netrequirement') IS NOT NULL DROP TABLE #netrequirement
	create table #netrequirement 
	(
		id			int identity(1,1) not null,
		itemid				bigint,
		parentid			bigint,
		itemname			varchar(500),
		itemcode			varchar(25),
		oldcode				varchar(20),
		itemtype			varchar(30),
		itemtypeid			int,
		quantity			decimal(15,3),
		stockinhand			decimal(15,3),
		minimumStk			decimal(15,3),
		wipqty				decimal(15,3),
		onPO				decimal(15,3),
		atRect				decimal(15,3),
		netReqd				decimal(15,3),
		unitid				int,
		unit				varchar(50),
		[level]				int,
		processed			bit default 0,
		bomid				int,
        toexplode           bit
	)

	declare @itemid int, @bomid int;
	declare @kitquantity decimal (13,2);
    declare @nlevel int; 
	set @nlevel = 0;
	--insert data for the product from batch detail
	insert into #netrequirement (itemid, parentid,quantity, netReqd, [level],processed, stockinhand, minimumStk,wipqty,onPO,atRect,toexplode)
	select itemid , 0, isnull(quantity,1),isnull(quantity,1), @nlevel,0,0,0,0,0,0,1 from db_production.dtl_batch where batchid = @batchid
	
	-- update itemtypeid 
	update #netrequirement set itemtypeid = a.itemtypeid from 
	(select dtlb.itemid, itemtypeid from db_production.dtl_workorder dtlwo join  db_production.dtl_batch dtlb on dtlwo.itemid = dtlb.itemid 
	JOIN db_production.hdr_batch hdr on dtlwo.woid = hdr.woid) a where #netrequirement.itemid= a.itemid

	-- update stock in hand
	update #netrequirement set stockinhand = isnull(stk.stock,0)
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn group by itemid) stk 
	where  #netrequirement.itemid = stk.itemid and processed = 0

	-- update wipqty for open kits
	update #netrequirement set wipqty = isnull(wip.wipqty ,0)
	from (select itemid,sum(dtl.quantity) wipqty from db_production.hdr_batch hdr 
	join db_production.dtl_batch dtl on hdr.batchid=dtl.batchid and hdr.batchid<>@batchid
	group by itemid) wip where #netrequirement.itemid = wip.itemid and processed = 0

	-- update wipqty for workorders for which batches not opened yet
	update #netrequirement set wipqty = isnull(wipqty,0)+isnull(wip.wipqty1,0)
	from (select itemid,sum(quantity) wipqty1 from db_production.dtl_workorder where woid not in (select distinct woid from db_production.hdr_batch) group by itemid) wip 
	where #netrequirement.itemid = wip.itemid and processed = 0

	-- update purchase quantity
	update #netrequirement set onPo = isnull(po.poqty,0) 
	from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0)) poqty from db_mm.dtl_purchaseorder
	group by itemid having sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0))>0 ) po 
	where #netrequirement.itemid = po.itemid and processed = 0
	
	--update atrect quantity 
	update #netrequirement set atRect = isnull(rect.rectqty,0)
	from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) rectqty from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid 
	where status != 'C'	group by itemid) rect where #netrequirement.itemid = rect.itemid and processed = 0

	--update net reqd
	update #netrequirement set netReqd = isnull(quantity,0) + isnull(minimumStk,0) - isnull(stockinhand,0) - isnull(wipqty,0) - isnull(onpo,0) - isnull(atrect,0)

	--update bomid
	update #netrequirement set bomid = isnull(a.bomid1,0)
	from (select productid, max(bomid) bomid1 from db_mm.hdr_bom group by productid) a where #netrequirement.itemid = a.productid and processed = 0

	update #netRequirement set processed = 1 

	declare @netReq decimal(13,2);
	declare @id int=0 ,@id1 int=0;
	declare @checkitemid bigint;
	select   netReqd , id, itemid,isnull([level],0) level,isnull(bomid,0) bomid from #netRequirement
	
	select top 1 @netReq =  netReqd , @id=id, @checkitemid = itemid, @level = isnull([level],0),@bomid = isnull(bomid,0) from #netRequirement where id >@id order by id
	if (@netReq>0 and @bomid >0)
		begin
			startagain:

			set @nlevel = @nlevel + 1

			update #netrequirement set quantity = isnull(quantity,0) + isnull(a.qty,0)
			from (select cid, @netReq*isnull(quantity,0) qty from db_mm.dtl_bom where bomid = @bomid) a where #netrequirement.itemid = a.cid

			insert into #netRequirement (itemid, parentid,quantity, [level],processed,
			 netReqd, stockinhand, minimumStk,wipqty,onPO,atRect,toexplode)
			select cid,@checkitemid,@netReq*isnull(quantity,1),@nlevel,0,0,0,0,0,0,0,toexplode from db_mm.dtl_bom where bomid = @bomid 
			and cid not in (select distinct itemid from #netrequirement)

            -- update itemtype 
            update #netrequirement set itemtypeid = a.itemtypeid from 
	(select dtl.itemid, isnull(max(typeid),0) itemtypeid from db_mm.item_types dtl group by dtl.itemid ) a where #netrequirement.itemid= a.itemid

			-- update stock in hand
			update #netrequirement set stockinhand = isnull(stk.stock,0)
			from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn group by itemid) stk 
			where  #netrequirement.itemid = stk.itemid and processed = 0

			-- update wipqty for open kits
			update #netrequirement set wipqty = isnull(wip.wipqty ,0)
			from (select itemid,sum(dtl.quantity) wipqty from db_production.hdr_batch hdr 
			join db_production.dtl_batch dtl on hdr.batchid=dtl.batchid and hdr.batchid <>@batchid 
			group by itemid) wip where #netrequirement.itemid = wip.itemid and processed = 0

			-- update wipqty for workorders for which batches not opened yet
			update #netrequirement set wipqty = isnull(wipqty,0)+isnull(wip.wipqty1,0)
			from (select itemid,sum(quantity) wipqty1 from db_production.dtl_workorder where woid not in (select distinct woid from db_production.hdr_batch) group by itemid) wip 
			where #netrequirement.itemid = wip.itemid and processed = 0

			-- update purchase quantity
			update #netrequirement set onPo = isnull(po.poqty,0) 
			from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0)) poqty from db_mm.dtl_purchaseorder
			group by itemid having sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0))>0 ) po 
			where #netrequirement.itemid = po.itemid and processed = 0
			
			--update atrect quantity 
			update #netrequirement set atRect = isnull(rect.rectqty,0)
			from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) rectqty from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid 
			where status != 'C'	group by itemid) rect where #netrequirement.itemid = rect.itemid and processed = 0
	
			--update net reqd
			update #netrequirement set netReqd = isnull(quantity,0) + isnull(minimumStk,0) - isnull(stockinhand,0) - isnull(wipqty,0) - isnull(onpo,0) - isnull(atrect,0)

			--update bomid
			update #netrequirement set bomid = isnull(a.bomid1,0)
			from (select productid, max(bomid) bomid1 from db_mm.hdr_bom group by productid) a where #netrequirement.itemid = a.productid and processed = 0 and toexplode=1

			checkbom:

			select top 1 @netReq =  netReqd , @id1=id, @checkitemid = itemid, @bomid = isnull(bomid,0) from #netRequirement where id>@id order by id
			
			set @id = @id1
			select @id1 = max(id) from #netrequirement 

			update #netRequirement set processed = 1 
			if (@bomid=0 and @id<@id1) GOTO checkbom
			IF (@bomid>0 and @nlevel<=@level+1) 
            begin
                if not exists(select 1 from db_mm.item_types where itemid = @checkitemid and typeid in (10,9))  GOTO startagain;
            end
		end
	else
	begin
		update #netRequirement set level = 1
	end
		-- update item master details
		update #netRequirement  set itemcode = a.itemcode, oldcode = a.oldcode, itemname = a.itemname , unitid = receivingunitid
		from db_mm.mst_item a where #netRequirement.itemid = a.id
		--update unit 
		update #netRequirement set unit = a.uom from db_mm.mst_itemuom a where a.id = #netRequirement.itemid 

		select itemid, itemname,itemcode,oldcode,quantity, isnull(itemtypeid,1) itemtypeid, stockinhand, minimumStk,wipqty,onPO,atRect,netReqd,unit,[level] 
		from #netRequirement where level > 0  and itemtypeid>0 order by  oldcode

		select a.typeid,a.itemid,mst.name from db_mm.item_types a join db_mm.mst_itemtypes mst on a.typeid=mst.id and itemid in (select distinct itemid from #netRequirement)
		union
		select isnull(itemtypeid,1) typeid, itemid, mst.name from #netRequirement join db_mm.mst_itemtypes mst on isnull(itemtypeid,1)=mst.id
End











GO
/****** Object:  StoredProcedure [db_production].[generaterequisition]    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_production].[generaterequisition] 1,1,1,1
-- =============================================
CREATE procedure [db_production].[generaterequisition]
@coid int,
@boid int,
@fyid int,
@userid bigint,
@calledfrom char(1),
@refid bigint,
@itemarray [db_production].[generaterequisition_tvp] readonly 
as 
Begin
	SET NOCOUNT ON;
	
	declare @reqno bigint,@reqid bigint, @batchno bigint,@batchid bigint;
	declare @level int, @srctypeid int;

	if (@calledfrom='B')
		BEGIN
			select @level = min(level) from @itemarray where level > 0
			set @batchid = @refid;
			set @srctypeid = 7;
		End
	ELSE
		Begin
			set @level=null
			set @srctypeid = 7;
			select @batchid = batchid from db_production.hdr_jobcard where jobid=@refid
		End

	select @reqno = isnull(max(reqnno),0)+1 from db_mm.hdr_requisition
	
	insert into db_mm.hdr_requisition (deptid,storeid,reqnno,batchno,reqndate,isconfirm,remarks,coid,boid,confirmedby,createdby,createdon,fyid,refid,srctypeid)
	values (1,1,@reqno, @batchno, getdate(),1,'Requisition generated automatically',@coid,@boid,@userid,@userid,getdate(),@fyid,
	@refid,@srctypeid)

	select @reqid = scope_identity()

	insert into db_mm.dtl_requisition (reqnid,itemid,brandid,requestedquantity,remarks)
	select @reqid,itemid,1,quantity, 'Requisition generated automatically' from @itemarray where quantity>0 and level = coalesce(@level,[level])

	
	if exists (select itemid from @itemarray where itemtypeid in (select id from db_mm.mst_itemtypes where blockjobcard = 0)  and isnull(netReqd,0) > 0 and [level] = coalesce(@level,[level]))
	Begin
		declare @jobno bigint,@jobid bigint;

		select @jobno = isnull(max(jobno),0)+1 from db_production.hdr_jobcard

		--create job cards from batch
		insert into db_production.hdr_jobcard (jobno,batchid,startdate,status,isactive,createdby,createdon,supervisorid)
		values (@jobno, @batchid,getdate(),1,1,@userid,getdate(),@userid)

		select @jobid = scope_identity()
		
		insert into db_production.dtl_jobcard (jobid,itemid,quantityrequested, quantitydelivered,stage,userid,status)
		select @jobid, itemid,quantity,0, 1,@userid, 1 from @itemarray where itemtypeid in (select id from db_mm.mst_itemtypes where typecode != 'P' and netReqd>0 and [level] = coalesce(@level,[level]))

	End
	
	if exists (select itemid from @itemarray where itemtypeid in (select id from db_mm.mst_itemtypes where typecode = 'P')  and netReqd>0  and [level] = coalesce(@level,[level]))
		begin
			declare @indentid bigint, @indentno bigint;

			select @indentno= max(indentnumber)+1 from db_mm.hdr_indent

			--select * from db_production.hdr_productionplan
			insert into db_mm.hdr_indent (fyid,departmentid,indentdate,indentnumber,indentorid,remarks,costcentreid,coid,boid,isactive,createdby,createdon)
			values (@fyid,1,getdate(), @indentno, @userid, 'indent created for batchid ' + cast(@batchno as varchar(10)), @batchid,@coid,@boid,1,@userid,getdate())
		
			select @indentid = scope_identity()

			insert into db_mm.dtl_indent (indentid,itemid,quantityrequired,quantityapproved,quantitywoff,coid,boid,remarks,brandid)
			select @indentid, itemid,quantity,quantity,0,@coid,@boid, 'indent created from release batch', 1	
			from @itemarray where itemtypeid in (select id from db_mm.mst_itemtypes where typecode = 'P') and netReqd>0  and [level] = coalesce(@level,[level])
		end	
End










GO
/****** Object:  StoredProcedure [db_production].[jobwisenetrequirement]    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_production].[batchwisenetrequirement] 1,1,1,1
-- =============================================
CREATE procedure [db_production].[jobwisenetrequirement]
@coid int,
@boid int,
@fyid int,
@jobid bigint,
@level int= 1,
@userid int = 0,
@accesstoken varchar(200) = null
as 
Begin
	SET NOCOUNT ON;
	
	IF OBJECT_ID('tempdb..#netrequirement') IS NOT NULL DROP TABLE #netrequirement
	create table #netrequirement 
	(
		id			int identity(1,1) not null,
		itemid				bigint,
		parentid			bigint,
		itemname			varchar(500),
		itemcode			varchar(25),
		oldcode				varchar(20),
		itemtype			varchar(30),
		itemtypeid			int,
		quantity			decimal(15,3),
		stockinhand			decimal(15,3),
		minimumStk			decimal(15,3),
		wipqty				decimal(15,3),
		onPO				decimal(15,3),
		atRect				decimal(15,3),
		netReqd				decimal(15,3),
		unitid				int,
		unit				varchar(50),
		[level]				int,
		processed			bit default 0,
		bomid				int
	)

	declare @itemid int, @bomid int, @batchid int;
	declare @kitquantity decimal (13,2);
    declare @nlevel int;
	set @nlevel = 0;

	select @batchid = batchid from db_production.hdr_jobcard where jobid =@jobid 

	--insert data for the product from batch detail
	insert into #netrequirement (itemid, parentid,quantity, netReqd, [level],processed, stockinhand, minimumStk,wipqty,onPO,atRect,itemtypeid)
	select itemid , 0, isnull(quantityrequested,1),isnull(quantityrequested,1), @nlevel,0,0,0,0,0,0,0 from db_production.dtl_jobcard where jobid = @jobid
	
	-- update stock in hand
	update #netrequirement set stockinhand = isnull(stk.stock,0)
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn group by itemid) stk 
	where  #netrequirement.itemid = stk.itemid and processed = 0


	-- update wipqty for open kits
	update #netrequirement set wipqty = isnull(wip.wipqty ,0)
	from (select itemid,sum(dtl.quantity) wipqty from db_production.hdr_batch hdr 
	join db_production.dtl_batch dtl on hdr.batchid=dtl.batchid and hdr.batchid<>@batchid
	group by itemid) wip where #netrequirement.itemid = wip.itemid and processed = 0

	-- update wipqty for workorders for which batches not opened yet
	update #netrequirement set wipqty = isnull(wipqty,0)+isnull(wip.wipqty1,0)
	from (select itemid,sum(quantity) wipqty1 from db_production.dtl_workorder where woid not in (select distinct woid from db_production.hdr_batch) group by itemid) wip 
	where #netrequirement.itemid = wip.itemid and processed = 0

	-- update purchase quantity
	update #netrequirement set onPo = isnull(po.poqty,0) 
	from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0)) poqty from db_mm.dtl_purchaseorder
	group by itemid having sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0))>0 ) po 
	where #netrequirement.itemid = po.itemid and processed = 0
	
	--update atrect quantity 
	update #netrequirement set atRect = isnull(rect.rectqty,0)
	from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) rectqty from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid 
	where status != 'C'	group by itemid) rect where #netrequirement.itemid = rect.itemid and processed = 0

	--update net reqd
	update #netrequirement set netReqd = isnull(quantity,0) + isnull(minimumStk,0) - isnull(stockinhand,0) - isnull(wipqty,0) - isnull(onpo,0) - isnull(atrect,0)

	--update bomid
	update #netrequirement set bomid = isnull(a.bomid1,0)
	from (select productid, max(bomid) bomid1 from db_mm.hdr_bom group by productid) a where #netrequirement.itemid = a.productid and processed = 0

	update #netRequirement set processed = 1 

	declare @netReq decimal(13,2);
	declare @id int=0 ,@id1 int=0;
	declare @checkitemid bigint;

	
	select top 1 @netReq =  netReqd , @id=id, @checkitemid = itemid, @level = isnull([level],0) +1,@bomid = isnull(bomid,0) from #netRequirement where id >@id order by id
	if (@netReq>0 and @bomid >0)
		begin
			startagain:

			set @nlevel = @nlevel + 1

			update #netrequirement set quantity = isnull(quantity,0) + isnull(a.qty,0)
			from (select cid, @netReq*isnull(quantity,0) qty from db_mm.dtl_bom where bomid = @bomid) a where #netrequirement.itemid = a.cid

			insert into #netRequirement (itemid, parentid,quantity, [level],processed,
			 netReqd, stockinhand, minimumStk,wipqty,onPO,atRect,itemtypeid)
			select cid,@checkitemid,@netReq*isnull(quantity,1),@nlevel,0,0,0,0,0,0,0,0 from db_mm.dtl_bom where bomid = @bomid 
			and cid not in (select distinct itemid from #netrequirement)

			-- update stock in hand
			update #netrequirement set stockinhand = isnull(stk.stock,0)
			from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn group by itemid) stk 
			where  #netrequirement.itemid = stk.itemid and processed = 0

			-- update wipqty for open kits
			update #netrequirement set wipqty = isnull(wip.wipqty ,0)
			from (select itemid,sum(dtl.quantity) wipqty from db_production.hdr_batch hdr 
			join db_production.dtl_batch dtl on hdr.batchid=dtl.batchid and hdr.batchid <>@batchid 
			group by itemid) wip where #netrequirement.itemid = wip.itemid and processed = 0

			-- update wipqty for workorders for which batches not opened yet
			update #netrequirement set wipqty = isnull(wipqty,0)+isnull(wip.wipqty1,0)
			from (select itemid,sum(quantity) wipqty1 from db_production.dtl_workorder where woid not in (select distinct woid from db_production.hdr_batch) group by itemid) wip 
			where #netrequirement.itemid = wip.itemid and processed = 0

			-- update purchase quantity
			update #netrequirement set onPo = isnull(po.poqty,0) 
			from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0)) poqty from db_mm.dtl_purchaseorder
			group by itemid having sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0))>0 ) po 
			where #netrequirement.itemid = po.itemid and processed = 0
			
			--update atrect quantity 
			update #netrequirement set atRect = isnull(rect.rectqty,0)
			from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) rectqty from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid 
			where status != 'C'	group by itemid) rect where #netrequirement.itemid = rect.itemid and processed = 0
	
			--update net reqd
			update #netrequirement set netReqd = isnull(quantity,0) + isnull(minimumStk,0) - isnull(stockinhand,0) - isnull(wipqty,0) - isnull(onpo,0) - isnull(atrect,0)

			--update bomid
			update #netrequirement set bomid = isnull(a.bomid1,0)
			from (select productid, max(bomid) bomid1 from db_mm.hdr_bom group by productid) a where #netrequirement.itemid = a.productid and processed = 0

			checkbom:

			select top 1 @netReq =  netReqd , @id1=id, @checkitemid = itemid, @bomid = isnull(bomid,0) from #netRequirement where id>@id order by id
			
			set @id = @id1
			select @id1 = max(id) from #netrequirement 

			update #netRequirement set processed = 1 
			if (@bomid=0 and @id<@id1) GOTO checkbom
			IF (@bomid>0) GOTO startagain;

			
		end

		-- update item master details
		update #netRequirement  set itemcode = a.itemcode, oldcode = a.oldcode, itemname = a.itemname , unitid = receivingunitid
		from db_mm.mst_item a where #netRequirement.itemid = a.id
		--update unit 
		update #netRequirement set unit = a.uom from db_mm.mst_itemuom a where a.id = #netRequirement.itemid
		select * from db_mm.mst_itemuom
		select itemid, itemname,itemcode,oldcode,quantity, stockinhand, minimumStk,wipqty,onPO,atRect,netReqd,unit,[level],itemtypeid from #netRequirement order by  oldcode


		select a.typeid,a.itemid,mst.name from db_mm.item_types a join db_mm.mst_itemtypes mst on a.typeid=mst.id and itemid in (select distinct itemid from #netRequirement)
		
End











GO
/****** Object:  StoredProcedure [db_production].[pr_allocatebatch]    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_production].[pr_allocatebatch] 1,1,3
-- =============================================
CREATE PROCEDURE [db_production].[pr_allocatebatch]
    @userid int,
	@dtlid int,
	@supervisorid int,
	@batchid bigint=0,
	@quantity decimal=0.00
AS
Begin
	
	update db_production.dtl_workorder set supervisorid = @supervisorid where id = @dtlid 

	update db_production.dtl_batch set supervisorid = @supervisorid,quantity = @quantity
	where batchid=@batchid

	select * from  db_production.dtl_workorder  where id = @dtlid

	declare @itemid bigint, @batchno bigint,@reqno bigint, @reqid bigint;
	declare @qty decimal(13,2) ;
	declare @coid int, @fyid int,@boid int;

	select @itemid= itemid, @qty = quantity from db_production.dtl_workorder where id = @dtlid
	select @batchno = batchno,@coid=coid,@fyid = fyid, @boid = boid from db_production.hdr_batch where batchid = @batchid
	
	-- generate requisitions for supervisor
	/*IF OBJECT_ID('tempdb..#itembom') IS NOT NULL DROP TABLE #itembom
	create table #itembom 
	(
		id bigint,
		itemid bigint,
		itemname varchar(500),
		itemcode varchar(50),
		oldcode varchar(20),
		quantity		decimal(15,3),
		stockinhand			decimal(15,3),
		minimumStk			decimal(15,3),
		wipqty				decimal(15,3),
		onPO				decimal(15,3),
		atRect				decimal(15,3),
		netReqd				decimal(15,3),
		typecode char(1),
		brandid int,
		toexplode bit,
		bomid bigint,
		uom varchar(20),
		uomid int
	)
	-- insert bom items for item in a kit/batch
	if exists(select id from db_mm.dtl_bom where pid=@itemid)
	Begin
		insert into #itembom (id,itemid,quantity,toexplode, brandid,uomid,typecode,bomid,stockinhand,minimumStk,wipqty,onPO,atRect,netReqd)
		select id,cid,isnull(@qty,1)*isnull(quantity,1),toexplode, brandid,unit,'P',bomid,0,0,0,0,0,0 from db_mm.dtl_bom where pid = @itemid
	end
	else
	begin
		insert into #itembom (id,itemid,quantity,toexplode, uomid, brandid,typecode,bomid,stockinhand,minimumStk,wipqty,onPO,atRect,netReqd)
		values( 0,@itemid,isnull(@qty,1),0,0, 0,'P',0 ,0,0,0,0,0,0)

		update #itembom set uomid = a.receivingunitid from db_mm.mst_item a where #itembom.itemid = a.id
	end
		--update typecode
		update #itembom set typecode = c.typecode from 
		(select a.itemid, a.typecode, a.name from
		(select dtl.id, itemid, Name, Typecode from db_mm.item_types dtl join db_mm.mst_itemtypes mst on dtl.typeid = mst.id where Typecode <> 'P') a join 
		(select itemid, isnull(min(dtl.id),0) id from db_mm.item_types  dtl join db_mm.mst_itemtypes mst on dtl.typeid = mst.id where Typecode <> 'P' group by itemid) b on
		a.id = b.id where a.id = b.id) c where #itembom.itemid = c.itemid

		--update item details
		update #itembom set itemname = a.itemname, itemcode= a.itemcode, oldcode = a.oldcode 
		from db_mm.mst_item a where #itembom.itemid = a.id

		-- update uom
		update #itembom set uom = a.uom
		from db_mm.mst_itemuom a where #itembom.uomid = a.id


		-- update stock in hand
		update #itembom set stockinhand = isnull(stk.stock,0)
		from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+1) as int)) stock from db_mm.item_stk_trn group by itemid) stk 
		where  #itembom.itemid = stk.itemid 

		-- update wipqty for open kits
		update #itembom set wipqty = isnull(wip.wipqty ,0)
		from (select itemid,sum(dtl.quantity) wipqty from db_production.hdr_batch hdr 
		join db_production.dtl_batch dtl on hdr.batchid=dtl.batchid and hdr.batchid<>@batchid
		group by itemid) wip where #itembom.itemid = wip.itemid 

		-- update wipqty for workorders for which batches not opened yet
		update #itembom set wipqty = isnull(wipqty,0)+isnull(wip.wipqty1,0)
		from (select itemid,sum(quantity) wipqty1 from db_production.dtl_workorder where woid not in (select distinct woid from db_production.hdr_batch) group by itemid) wip 
		where #itembom.itemid = wip.itemid 

		-- update purchase quantity
		update #itembom set onPo = isnull(po.poqty,0) 
		from (select itemid, sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0)) poqty from db_mm.dtl_purchaseorder
		group by itemid having sum(isnull(orderedquantity,0)-isnull(receivedquantity,0) - isnull(writeoffquantity,0))>0 ) po 
		where #itembom.itemid = po.itemid 

		--update atrect quantity 
		update #itembom set atRect = isnull(rect.rectqty,0)
		from (select itemid, sum(isnull(quantityreceived,0)-isnull(quantityrejected,0)-isnull(quantitybroken,0)) rectqty from db_mm.dtl_grn dtl join db_mm.hdr_grn hdr on dtl.grnid = hdr.grnid 
		where status != 'C'	group by itemid) rect where #itembom.itemid = rect.itemid 

		--update net reqd
		update #itembom set netReqd = isnull(quantity,0) + isnull(minimumStk,0) - isnull(stockinhand,0) - isnull(wipqty,0) - isnull(onpo,0) - isnull(atrect,0)

	
		-- create purchase indents from batch
		if exists(select id from #itembom where typecode = 'P' and isnull(netReqd,0)>0)
		begin
			declare @indentid bigint, @indentno bigint;

			select @indentno= max(indentnumber)+1 from db_mm.hdr_indent

			
			insert into db_mm.hdr_indent (fyid,departmentid,indentdate,indentnumber,indentorid,remarks,costcentreid,coid,boid,isactive,createdby,createdon,refid,srctypeid)
			values (@fyid,1,getdate(), @indentno, @userid, 'indent created for batch', @batchid,@coid,@boid,1,@userid,getdate(),@batchid,7)
		
			select @indentid = scope_identity()

			insert into db_mm.dtl_indent (indentid,itemid,quantityrequired,quantityapproved,quantitywoff,coid,boid,remarks,brandid)
			select @indentid, itemid,quantity,quantity,0,@coid,@boid, 'indent created for batch', brandid	from #itembom where typecode = 'P'
		end
		

		select @reqno = isnull(max(reqnno),0)+1 from db_mm.hdr_requisition
	
		insert into db_mm.hdr_requisition (deptid,storeid,reqnno,batchno,reqndate,isconfirm,remarks,coid,boid,confirmedby,createdby,createdon,fyid,productid,lotsize,bomid,
		refid,srctypeid)
		values (1,1,@reqno, @batchno, getdate(),1,'Requisition generated automatically for batch',@coid,@boid,@userid,@userid,getdate(),@fyid,@itemid,@qty,1,@batchid,7)

		select @reqid = scope_identity()

		insert into db_mm.dtl_requisition (reqnid,itemid,brandid,requestedquantity,remarks)
		select @reqid,itemid,brandid,quantity, 'Requisition generated automatically for batch' from #itembom

		drop table #itembom
		*/

End




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

CREATE PROCEDURE [db_production].[pr_commonapimovementcard]
	@coid int,
	@boid INT,
	@fyid INT,
	@userid INT,
	@accesstoken VARCHAR(100)
AS
BEGIN
	SET NOCOUNT ON;	    
		Select id,operationname from [db_production].[mst_operation_stage]  where coid=@coid and boid=@boid and isactive=1
end 
	

GO
/****** Object:  StoredProcedure [db_production].[pr_commonapiplan]    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_production].[pr_generatebatchno] 1,1,5,1
-- =============================================
CREATE PROCEDURE [db_production].[pr_commonapiplan]
    @coid int,
	@boid int,
	@fyid int,
	@planid bigint=0
AS
Begin
	
	select isnull(max(cast(planno as int)),0) lastplanno from db_production.hdr_productionplan



	select splitdata as status from dbo.fnSplitString('Unconfirmed,Confirmed,Approved,Work In Process',',')
	
	--exec [db_sop].[pr_getpendingorders] @coid,@boid,@fyid

--	select oaid,oano,oadate from db_sop.hdr_saleorder where oaid in (
--	select distinct oaid from (select oaid ,cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
--from db_sop.dtl_saleorder) a where chk not in (select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
--from db_production.dtl_productionplan))


select oaid,oano,oadate from db_sop.hdr_saleorder where oaid in (
	select distinct oaid from (select oaid ,cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
from db_sop.dtl_saleorder) a where chk not in (select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
from db_production.dtl_productionplan ) or chk in  (select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
from db_production.dtl_productionplan WHERE planid =@planid))


select dtl.oaid,oano,oadate,1 bomid,dtl.itemid,uom,itemcode,oldcode,itemname, isnull(orderedquantity,0) orderqty, 
isnull(orderedquantity,0) - isnull(qtyalreadydispatched,0) pendingqty from db_sop.dtl_saleorder dtl 
join db_sop.hdr_saleorder hdr on dtl.oaid = hdr.oaid 
join db_mm.mst_item mst on dtl.itemid = mst.id 
join (select oaid ,cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk , itemid
from db_sop.dtl_saleorder where cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) not in 
(select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk from db_production.dtl_productionplan)) a on dtl.itemid = a.itemid and dtl.oaid = a.oaid

	

End



GO
/****** Object:  StoredProcedure [db_production].[pr_confirmplan]    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_production].[pr_confirmplan] 1,1,10075
-- =============================================
CREATE PROCEDURE [db_production].[pr_confirmplan]
    @coid int,
	@boid int,
	@planid bigint,
	@userid int,
	@statementtype varchar(1)
AS
Begin
	If (@statementtype='C')
		Begin
			update db_production.hdr_productionplan set confirmedon = getdate(), confirmedby = @userid where planid = @planid and coid =@coid and boid=@boid
		End
	else	
		Begin
			update db_production.hdr_productionplan set approvedon = getdate(), approvedby = @userid where planid = @planid and coid =@coid and boid=@boid
		End
End
select * from db_production.hdr_productionplan


GO
/****** Object:  StoredProcedure [db_production].[pr_generatebatchno]    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_production].[pr_generatebatchno] 1,1,1,1,1,3
-- =============================================
CREATE PROCEDURE [db_production].[pr_generatebatchno]
    @coid int,
	@boid int,
	@fyid int,
	@supervisorid int,
	@userid int,
	@dtlid int
AS
Begin
	declare @batchno varchar(20)='';
	declare @batchid bigint, @woid bigint;
	declare @woquantity decimal, @batchquantity decimal;

	select @woid = isnull(woid,0) from db_production.dtl_workorder where id = @dtlid -- and isnull(batchid,0) = 0
	
	if (@woid >0)
	begin
		
		/*if exists(select hdr.batchid from db_production.hdr_batch hdr where woid = @woid and supervisorid = @supervisorid)
			begin
				select @batchid = batchid from db_production.hdr_batch hdr where woid = @woid and supervisorid = @supervisorid

				insert into db_production.dtl_batch (batchid,itemid,quantity,bomid,supervisorid)
				select @batchid, itemid, 0, bomid,@supervisorid from db_production.dtl_workorder where id = @dtlid

				select @batchno = batchno from db_production.hdr_batch where batchid = @batchid
			end
		else
		begin*/
			select  @batchno = isnull(max(cast(batchno as int)),0)+1 from db_production.hdr_batch
		
			select @batchquantity = sum(isnull(quantity,0)) from db_production.dtl_batch 
			where batchid in (select distinct batchid from db_production.hdr_batch where woid = @woid)

			insert into db_production.hdr_batch (batchdate, batchno, coid,boid,isactive,createdby,createdon,fyid,woid
			,supervisorid,wodetailid)
			values (getdate(),@batchno, @coid,@boid,1,@userid,getdate(),@fyid,@woid,@supervisorid,@dtlid)

		
			select @batchid =  SCOPE_IDENTITY()

			insert into db_production.dtl_batch (batchid,itemid,quantity,bomid,supervisorid)
			select @batchid, itemid, 0, bomid,@supervisorid 
			from db_production.dtl_workorder where id = @dtlid

			update db_production.dtl_workorder set batchid =@batchid, batchdate = getdate() where id = @dtlid;
			
			--According to mohit
			--first insert record in  db_mm.hdr_requisition  with bomid  then insert bom item in db_mm.dtl_requisition

			declare @reqno int,@reqid int;

			select @reqno = isnull(max(reqnno),0)+1 from db_mm.hdr_requisition
	
			insert into db_mm.hdr_requisition (deptid,storeid,reqnno,reqndate,isconfirm,remarks,coid,boid,confirmedby,createdby,createdon,refid,srctypeid,batchno)
			values (1,1,@reqno,  getdate(),1,'Requisition generated automatically for work order' ,@coid,@boid,@userid,@userid,getdate(),@woid,2,@batchno)

			select @reqid = scope_identity()

			insert into db_mm.dtl_requisition (reqnid,itemid,brandid,requestedquantity,remarks)
			select @reqid,itemid,1,quantity, 'Requisition generated automatically for work order'  from db_production.dtl_workorder where id = @dtlid

			
		
			select @batchno batchno 
		--end	
	end
	else
	begin
		select 0 batchno
	end
End




GO
/****** Object:  StoredProcedure [db_production].[pr_generatewoandpo]    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_production].[pr_generatewoandpo] 1,1,6,1
-- =============================================
CREATE PROCEDURE [db_production].[pr_generatewoandpo]
    @coid int,
	@boid int,
	@planid bigint,
	@userid int
AS
Begin
	declare @wono bigint=1, @woid bigint;
	declare @chk bit;
	declare @msg varchar(300);
	select @chk= wopogenerated from db_production.hdr_productionplan where planid = @planid
	if (@chk=1)
	Begin
		set @msg = 'Work Order/ Purchase Indent already generated for this plan'
		print @msg
		Return 
	End

	

	if exists(select * from db_production.dtl_productionplan where planid = @planid and itemtypeid in (select id from db_mm.mst_itemtypes where typecode != 'P'))
		Begin
			select @wono = isnull(max(wono),0)+1 from db_production.hdr_workorder
			--create workorders from production plan
			insert into db_production.hdr_workorder (fyid,wodate,wono,wocategoryid, remarks,status,boid,coid,isactive,createdby,createdon)
			select fyid,getdate(),@wono, 1, remarks, status, @boid,@coid,1,@userid, getdate() from db_production.hdr_productionplan where planid = @planid

			select @woid = scope_identity()

			--select @woid, oaid,itemid,bomid, finalqty,planid, itemtypeid from db_production.dtl_productionplan where planid = @planid 
			--and itemtypeid in (select id from db_mm.mst_itemtypes where typecode != 'P')

			insert into db_production.dtl_workorder (woid,oaid,itemid,bomid,quantity,planid,itemtypeid)
			select @woid, oaid,coalesce(b.cid,pp.itemid) itemid,pp.bomid, finalqty*isnull(b.quantity,1) finalqty,planid, itemtypeid from db_production.dtl_productionplan pp
			left join db_mm.dtl_bom b on pp.itemid = b.pid  where planid = @planid 
			and itemtypeid in (select id from db_mm.mst_itemtypes where typecode != 'P')

		End
	-- create purchase indents from production plan
	if exists(select * from db_production.dtl_productionplan where planid = @planid and (itemtypeid in (select id from db_mm.mst_itemtypes where typecode = 'P') or itemtypeid = 0))
	begin
		declare @indentid bigint, @indentno bigint;
		select @indentno= max(indentnumber)+1 from db_mm.hdr_indent

		--select * from db_production.hdr_productionplan
		insert into db_mm.hdr_indent (fyid,departmentid,indentdate,indentnumber,indentorid,remarks,costcentreid,coid,boid,isactive,createdby,createdon,refid,srctypeid)
		select fyid,1,getdate(), @indentno, createdby, remarks , 1,@coid,@boid,1,@userid,getdate(), @planid,6 from db_production.hdr_productionplan
		where planid = @planid

		select @indentid = scope_identity()

		insert into db_mm.dtl_indent (indentid,itemid,quantityrequired,quantityapproved,quantitywoff,coid,boid,remarks,brandid)
		select @indentid, itemid,finalqty,0,0,@coid,@boid, instructioninfo, 1 
		from db_production.dtl_productionplan where planid = @planid 
		and (itemtypeid in (select id from db_mm.mst_itemtypes where typecode = 'P') or itemtypeid = 0)
	end
	
	/*declare @reqno int,@reqid int;

	select @reqno = isnull(max(reqnno),0)+1 from db_mm.hdr_requisition
	
	insert into db_mm.hdr_requisition (deptid,storeid,reqnno,reqndate,isconfirm,remarks,coid,boid,confirmedby,createdby,createdon,refid,srctypeid)
	values (1,1,@reqno,  getdate(),1,'Requisition generated automatically for plan id ' + cast(@planid as varchar(10)),@coid,@boid,@userid,@userid,getdate(),@planid,6)

	select @reqid = scope_identity()

	insert into db_mm.dtl_requisition (reqnid,itemid,brandid,requestedquantity,remarks)
	select @reqid,itemid,1,finalqty, 'Requisition generated automatically for plan id ' + cast(@planid as varchar(10)) from db_production.dtl_productionplan*/


update db_production.hdr_productionplan set wopogenerated =1 where planid = @planid;
End




GO
/****** Object:  StoredProcedure [db_production].[pr_getbatchdata]    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_production].[pr_getuserbatches] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_production].[pr_getbatchdata]
    @userid int,
	@batchid int
AS
Begin
	
	select batchid,batchdate,batchno,batchreleasedate,batchreleasedby,batchstartdate,batchenddate,remarks, woid 
	from db_production.hdr_batch where batchid = @batchid -- and supervisorid = @userid

	select id,batchid,itemid,quantity,bomid,supervisorid from db_production.dtl_batch where batchid = @batchid 
	and supervisorid = @userid

	select * from db_production.dtl_releasebatch where batchid = @batchid
End




GO
/****** Object:  StoredProcedure [db_production].[pr_getcustomerorderitemsforWO]    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_production].[pr_getcustomerorderitemsforWO] 1,1,null,54734
-- =============================================
CREATE PROCEDURE [db_production].[pr_getcustomerorderitemsforWO]
    @coid int,
	@boid int,
	@oaid varchar(100) = null,
	@itemid bigint = 0
AS
Begin
	declare @msg varchar(200);
	IF @oaid IS NULL  and @itemid =0
		BEGIN  
			set @msg = 'You must provide either oa id or item id'
			PRINT @msg  
			RETURN  @msg
		END 

	IF OBJECT_ID('tempdb..#tempwodetail') IS NOT NULL DROP TABLE #tempwodetail
	create table #tempwodetail 
	(
		oaid bigint,
		oano bigint,
		planid bigint,
		itemid int,
		itemcode varchar(20),
		oldcode varchar(20),
		itemname varchar(200),
		uom varchar(20),
		domqty decimal(12,3),
		expqty decimal(12,3),
		stock			decimal(12,3),
		costprice		decimal(12,3),
		onwo			decimal(12,3),
		wip			    decimal(12,3),
		finalqty		decimal(12,3),
		itemtypeid int,
		pendingqty decimal(12,3),
		rowno			int,
		minrowno		int,
		
	)


	if (@oaid is not null)
		Begin
			insert into #tempwodetail (oaid,oano,itemid, domqty,expqty, pendingqty,stock,onwo,wip,costprice,rowno,finalqty)
			select hdr.oaid,hdr.oano,dtl.itemid,isnull(dtl.orderedquantity,0),0, isnull(dtl.orderedquantity,0)-isnull(dtl.qtyalreadydispatched,0), 0,0,0,0,
			ROW_NUMBER() OVER(ORDER BY hdr.oaid,dtl.itemid) rownum, isnull(dtl.orderedquantity,0) 
			from [db_sop].[dtl_saleorder] dtl
			join [db_sop].[hdr_saleorder] hdr on dtl.oaid = hdr.oaid 
			where hdr.oaid  in (select * from dbo.fnSplitString(@oaid,',')) 
		End
	else if (@itemid >0)
		Begin
			insert into #tempwodetail (oaid,oano,itemid, domqty,expqty, pendingqty,stock,onwo,wip,costprice,rowno,finalqty) 
			select hdr.oaid,hdr.oano,mst.id,isnull(dtl.orderedquantity,0),0,(isnull(dtl.orderedquantity,0)-isnull(dtl.qtyalreadydispatched,0)), 0,0,0,0,
			ROW_NUMBER() OVER(ORDER BY hdr.oaid,mst.id) rownum, isnull(dtl.orderedquantity,0)  
			from db_mm.mst_item mst 
			left join [db_sop].[dtl_saleorder] dtl on mst.id = dtl.itemid
			left join [db_sop].[hdr_saleorder] hdr on dtl.oaid = hdr.oaid 
			where mst.id = @itemid order by itemid
		End

	-- updating minrowno
	update #tempwodetail set minrowno = a.rowno
	from (select itemid, min(rowno) rowno from #tempwodetail group by itemid) a 
	where #tempwodetail.itemid = a.itemid

	-- updating item details from item master 
	update #tempwodetail set itemcode = m.itemcode,oldcode = m.oldcode, itemname = m.itemname,uom = m.receivingunitid  
	from [db_mm].[mst_item] m where #tempwodetail.itemid = m.id
	-- update unit 
	update #tempwodetail set uom = a.uom
	from db_mm.mst_itemuom a where #tempwodetail.uom = a.id 
	-- update stock in hand
	update #tempwodetail set stock = isnull(a.stock,0) , finalqty = finalqty - isnull(a.stock,0) 
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+ cast(1 as char)) as int)) stock from db_mm.item_stk_trn 
	where boid = @boid and coid = @coid 
	group by itemid) a where #tempwodetail.itemid = a.itemid and minrowno = rowno

 	
	-- update onwo, we have to write separate query for wip but for now just updated this column with same value
	update #tempwodetail set onwo = a.onwo, wip = a.onwo,  finalqty = finalqty - isnull(a.onwo,0) 
	from (select itemid, sum(quantity) onwo from  db_production.dtl_workorder 
	group by itemid) a where #tempwodetail.itemid = a.itemid and minrowno = rowno

	update #tempwodetail set finalqty = a.finalqty
	from (select itemid, minrowno, sum(finalqty) finalqty from #tempwodetail group by  itemid, minrowno) a 
	where #tempwodetail.itemid = a.itemid and #tempwodetail.minrowno = rowno
	
	update #tempwodetail set finalqty = 0 where rowno > minrowno

	select * from #tempwodetail
    declare @itemtype varchar(500);
    select @itemtype = name from db_mm.mst_itemtypes where id = 1
	select distinct w.itemid,isnull(typeid,1) typeid,isnull(name, @itemtype) typename from #tempwodetail w 
	left join db_mm.item_types t on w.itemid = t.itemid 
	left join db_mm.mst_itemtypes tp on t.typeid = tp.id

	drop table #tempwodetail

End




GO
/****** Object:  StoredProcedure [db_production].[pr_getjobcards]    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_production].[pr_getjobcards] 1,1,1,10,'jobid','desc','',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getjobcards] 
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='jobid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@searchtype varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select hdr.[jobid],hdr.[jobno],hdr.startdate,isnull(hdr.enddate,'''') enddate,hdr.supervisorid,hdr.batchid,
	batch.batchno, a.username from db_production.hdr_jobcard hdr join db_production.hdr_batch batch on hdr.batchid = batch.batchid 
	left join db_masters.users a on hdr.supervisorid = a.userid'
	set @sql += ' where hdr.isActive=1 and isnull(hdr.coid,1) = ' + cast(@coid as varchar(5)) + ' and 
	isnull(hdr.boid,1) = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and hdr.jobno = ' + cast(@search as varchar(5)) 
		end
		set @sql +=' order by hdr.' + 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(hdr.jobid) records from db_production.hdr_jobcard hdr
	 join db_production.hdr_batch bat on hdr.batchid = bat.batchid where isnull(hdr.coid,1) = @coid and isnull(hdr.boid,1) = @boid and hdr.isactive= 1
 
					
	
	
END



GO
/****** Object:  StoredProcedure [db_production].[pr_getjobdata]    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_production].[pr_getjobdata] 1,1
-- =============================================
CREATE PROCEDURE [db_production].[pr_getjobdata]
    @userid int,
	@jobid int
AS
Begin
	
	select jobid,batchid,supervisorid,startdate,enddate,status,isactive, jobno from db_production.hdr_jobcard where jobid = @jobid-- and supervisorid = @userid

	select dtl.id,jobid,itemid,quantityrequested,quantitydelivered,stage,userid,status,itemcode,itemname,oldcode from db_production.dtl_jobcard dtl join db_mm.mst_item mst on dtl.itemid = mst.id 
	where jobid = @jobid
	
	
End


GO
/****** Object:  StoredProcedure [db_production].[pr_getjobmovementcarddata]    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 Job Movement Card data>
--[db_production].[pr_getmovementtemplatedata] 1,1,3
-- =============================================
CREATE PROCEDURE [db_production].[pr_getjobmovementcarddata] 
	@coid int,
	@boid int,
	@id int

AS
BEGIN
	SET NOCOUNT ON;
	
	--template details
	select hdr.id,hdr.jobid,hdr.batchid,b.batchno as KitNo,b.batchdate,hdr.supervisorid,emp.empname AS supervisorname,hdr.templateid,hdr.fromstageid,hdr.tostageid,hdr.dateofrelease,
	hdr.timeofrelease,hdr.isactive,hdr.createdby,hdr.createdon,hdr.modifiedby,hdr.modifiedon,hdr.coid,hdr.boid,hdr.fyid,b.remarks
	from [db_production].[hdr_jobqtymovement] hdr
	LEFT JOIN [db_masters].[employee] emp ON hdr.supervisorid= emp.id
	join [db_production].[hdr_batch] b on hdr.batchid=b.batchid
	where hdr.id = @id and hdr.coid= @coid and hdr.boid = @boid


	SELECT dtl.id,dtl.qtyofferedtoqc,dtl.isrework,dtl.okqty,dtl.toreworkqty,dtl.rejqty,
	dtl.qcdate,dtl.qctime, im.itemname,um.uom,rew.reworkreason,rej.rejectionreason
	FROM [db_production].[dtl_job_qty_movement] dtl
	LEFT JOIN [db_mm].[mst_item] im ON dtl.itemid=im.id
	LEFT JOIN [db_mm].[mst_itemuom] um ON im.issuingunitid=um.id
	LEFT JOIN [db_production].[dtl_rework_rejection_reasons] reqrej ON im.id=reqrej.itemid
	LEFT JOIN [db_production].[mst_rework_reason] rew ON reqrej.reworkreasonid= rew.id
	LEFT JOIN [db_production].[mst_rejection_reason] rej ON reqrej.rejreasonid=rej.id

	SELECT dtl.machineid,mc.MachineName,dtl.operatorid,op.name,dtl.actualtimetaken,emp.empname
	FROM [db_production].[dtl_job_qty_movement] dtl
	LEFT JOIN [db_masters].[mst_machine] mc ON dtl.machineid=mc.id
	LEFT JOIN [db_masters].[operationmaster] op ON dtl.operatorid=op.id
	LEFT JOIN [db_masters].[employee] emp ON dtl.qcbyid= emp.id
	
END
	
	


GO
/****** Object:  StoredProcedure [db_production].[pr_getjobmovementcards]    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 Job Movement Card list>
--[db_production].[pr_getjobcards] 1,1,1,10,'jobid','desc','',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getjobmovementcards] 
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='jobid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' SELECT hdr.id as MovementNo,hdr.jobid,job.jobno,hdr.createdon,hdr.supervisorid,emp.empname as supervisorname,hdr.batchid,b.batchno as KitNo,wo.wono FROM [db_production].[hdr_jobqtymovement] hdr
	join [db_production].[hdr_batch] b on hdr.batchid=b.batchid
	left join [db_production].[dtl_workorder] wod on hdr.batchid=wod.batchid
	left join [db_production].[hdr_workorder] wo on wod.woid=wo.woid
	left join [db_production].[hdr_jobcard] job on hdr.jobid=job.jobid
	LEFT JOIN [db_masters].[employee] emp ON hdr.supervisorid= emp.id'
	set @sql += ' where hdr.isActive=1 and isnull(hdr.coid,1) = ' + cast(@coid as varchar(5)) + ' and 
	isnull(hdr.boid,1) = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and hdr.jobid = ' + cast(@search as varchar(5)) 
		end
		set @sql +=' order by hdr.' + 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(hdr.id) records from [db_production].[hdr_jobqtymovement] hdr
	 where isnull(hdr.coid,1) = @coid and isnull(hdr.boid,1) = @boid and hdr.isactive= 1
 
					
	
	
END



GO
/****** Object:  StoredProcedure [db_production].[pr_getmovementtemplatedata]    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_production].[pr_getmovementtemplatedata] 1,1,3
-- =============================================
CREATE PROCEDURE [db_production].[pr_getmovementtemplatedata] 
	@coid int,
	@boid int,
	@templateid int

AS
BEGIN
	SET NOCOUNT ON;
	
	--template details
	select * from db_production.mst_template_movementcard where id = @templateid and coid= @coid and boid = @boid

	--template items
	select items.id,items.templateid, items.itemid, mst.itemname,mst.itemcode,itemum.uom, mst.oldcode, items.effectivefromdate  
	from [db_production].[template_movement_items] items 
	join db_mm.mst_item mst on items.itemid = mst.id
	LEFT join db_mm.mst_itemuom itemum on mst.issuingunitid = itemum.id
	where templateid = @templateid
		
	--template parameters 
	select * from db_production.template_parameters_movementcard where templateid = @templateid
	
	--template machines
	select * from db_production.template_equipments_movementcard where templateid = @templateid

	Select id,operationname from [db_production].[mst_operation_stage]  where coid=@coid and boid=@boid and isactive=1
	
END
	
	


GO
/****** Object:  StoredProcedure [db_production].[pr_getmovementtemplates]    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_production].[pr_getmovementtemplates] 1,1,1,10,'id','desc',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getmovementtemplates] 
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='id',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@id Int = NULL
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql= 'SELECT distinct(mst.id),mst.coid,mst.boid,mst.templatename,mst.isactive,mst.createdon,
	( SELECT top 1 item.itemname FROM  db_mm.mst_item item join [db_production].[template_movement_items] items on mst.id = items.templateid WHERE  items.itemid = item.id) AS itemname,
	( SELECT top 1 item.itemcode FROM  db_mm.mst_item item join [db_production].[template_movement_items] items on mst.id = items.templateid WHERE  items.itemid = item.id) AS itemcode,
	( SELECT top 1 item.oldcode FROM  db_mm.mst_item item join [db_production].[template_movement_items] items on mst.id = items.templateid WHERE  items.itemid = item.id) AS oldcode,
	items.effectivefromdate
	FROM  db_production.mst_template_movementcard mst
	join [db_production].[template_movement_items] items on mst.id = items.templateid '
	
	set @sql += ' where mst.isactive=1 and mst.coid = ' + cast(@coid as varchar(5)) + ' and 
	mst.boid = ' + cast(@boid as varchar(5))
	if (@id <>0)
		begin
		set @sql+=' and mst.id =  '+  cast(@id as varchar(5)) +'' 
		PRINT @sql
		end
		if(@search!='')
		begin
		set @sql += ' and mst.templatename like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
		set @sql +=' order by mst.' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		if(isnull(@PageNumber,0)>0)
			begin
			set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
			FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
			end
	print @sql
	EXEC sp_executesql @SQL

	 set @sql= 'select count(mst.id) records from db_production.mst_template_movementcard mst '
	 --join [db_production].[template_movement_items] items on mst.id = items.templateid 
	 --join db_mm.mst_item item on items.itemid = item.id'
	set @sql += ' where mst.isactive=1 and mst.coid = ' + cast(@coid as varchar(5)) + ' and 
	mst.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		set @sql += ' and mst.templatename like '+'''%'+cast(@search as varchar(50)) + '%'''
		end
		
	print @sql
	EXEC sp_executesql @SQL
 
					
	
	
END



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

-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_production].[pr_getplandata]  1,1,'1010'
-- =============================================
CREATE PROCEDURE [db_production].[pr_getplandata] 
	@coid int,
	@boid int,
	@planid varchar(50)

AS
BEGIN
	SET NOCOUNT ON;
	
	
	SELECT [planid],[planno],[plandate],remarks,status,confirmedby,confirmedon,approvedby,approvedon, coid,boid,isactive, fyid, considerschedule,
	wopogenerated from db_production.hdr_productionplan WHERE planid in  (select * from dbo.fnSplitString(@planid,','))  
	
	 /*SELECT p.oaid, oa.oano, planid,p.itemid,im.itemcode,im.oldcode,im.itemname,uom.uom,domqty,expqty, stockqty,productcp,isnull(bomid,0) bomid,
	 p.instructioninfo,finalqty, p.itemtypeid from [db_production].[dtl_productionplan] p
	 JOIN [db_mm].[mst_item] im ON p.itemid=im.id
	 join [db_mm].[mst_itemuom] uom on im.receivingunitid = uom.id
	 left join [db_sop].[hdr_saleorder] oa on p.oaid = oa.oaid
    where planid in  (select * from dbo.fnSplitString(@planid,','))  */

	IF OBJECT_ID('tempdb..#tempwodetail') IS NOT NULL DROP TABLE #tempwodetail
	create table #tempwodetail 
	(
		id bigint,
		oaid bigint,
		oano bigint,
		planid bigint,
		itemid int,
		itemcode varchar(20),
		oldcode varchar(20),
		itemname varchar(200),
		uom varchar(20),
		domqty decimal(12,3),
		expqty decimal(12,3),
		stockqty decimal(12,3),
		stock			decimal(12,3),
		costprice		decimal(12,3),
		onwo			decimal(12,3),
		wip			    decimal(12,3),
		finalqty		decimal(12,3),
		itemtypeid int,
		pendingqty decimal(12,3),
		rowno			int,
		minrowno		int,
		bomid			int,
		instructioninfo	varchar(500)
	)

	insert into #tempwodetail (id,oaid,planid,itemid,domqty,expqty,stockqty, costprice,finalqty,itemtypeid,bomid, instructioninfo,rowno)
	                    SELECT id, oaid, planid,itemid,isnull(domqty,0),isnull(expqty,0), isnull(stockqty,0), isnull(productcp,0), isnull(domqty,0) + isnull(expqty,0)+isnull(stockqty,0) , itemtypeid, bomid, instructioninfo, 
	ROW_NUMBER() OVER(ORDER BY oaid,itemid) rownum from [db_production].[dtl_productionplan] 
	where planid in  (select * from dbo.fnSplitString(@planid,',')) 

	-- update item details in tempwodetail
	update #tempwodetail set itemcode = im.itemcode,oldcode= im.oldcode,itemname = im.itemname,uom = uom.uom
	from [db_mm].[mst_item] im 
	left join [db_mm].[mst_itemuom] uom on im.receivingunitid = uom.id
	where #tempwodetail.itemid=im.id
	
	update #tempwodetail set minrowno = a.rowno 
	from (select itemid, min(rowno) rowno from #tempwodetail group by itemid) a
	where #tempwodetail.itemid = a.itemid
	
	-- update stock in hand
	update #tempwodetail set stock = isnull(a.stock,0) , finalqty = finalqty - isnull(a.stock,0) 
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+ cast(1 as char)) as int)) stock 
	from db_mm.item_stk_trn where boid = @boid and coid = @coid group by itemid) a 
	where #tempwodetail.itemid = a.itemid and minrowno = rowno


	-- update onwo, we have to write separate query for wip but for now just updated this column with same value
	update #tempwodetail set onwo =  isnull(a.onwo,0), wip = isnull(a.onwo,0),  finalqty = finalqty - isnull(a.onwo,0) 
	from (select itemid, sum(quantity) onwo from  db_production.dtl_workorder 
	group by itemid) a where #tempwodetail.itemid = a.itemid and minrowno = rowno

	update #tempwodetail set finalqty = a.finalqty
	from (select itemid, minrowno, sum(finalqty) finalqty from #tempwodetail group by  itemid, minrowno) a 
	where #tempwodetail.itemid = a.itemid and #tempwodetail.minrowno = rowno
	
	update #tempwodetail set finalqty = 0 where rowno > minrowno

	update #tempwodetail set oano = oa.oano 
	from [db_sop].[hdr_saleorder] oa where #tempwodetail.oaid = oa.oaid


	SELECT id,oaid, oano, planid,itemid,itemcode,oldcode,itemname,uom,domqty,expqty, stockqty ,costprice productcp,
	isnull(bomid,0) bomid,instructioninfo,finalqty, itemtypeid,stock,onwo,wip from #tempwodetail 

	declare @itemtype varchar(500);
    select @itemtype = name from db_mm.mst_itemtypes where id = 1

	select distinct w.itemid,isnull(typeid,1) typeid,isnull(name,@itemtype) typename from #tempwodetail w 
	left join db_mm.item_types t on w.itemid = t.itemid 
	left join db_mm.mst_itemtypes tp on t.typeid = tp.id

	select itemid, getdate() deliverydate, 50 quantity from #tempwodetail
	union
	select itemid, getdate()+100 deliverydate, 50 quantity from #tempwodetail

	drop table #tempwodetail
end
--	select oaid,oano,oadate from db_sop.hdr_saleorder where oaid in (
--	select distinct oaid from (select oaid ,cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
--from db_sop.dtl_saleorder) a where chk not in (select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
--from db_production.dtl_productionplan ) or chk in  (select cast(oaid as varchar(10)) + ':::' + cast(itemid as varchar(10)) chk 
--from db_production.dtl_productionplan WHERE planid in  (select * from dbo.fnSplitString(1025,','))))
	


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

-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_production].[pr_getplanlist] 1,1,1,10,'planid','desc',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getplanlist] 
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='planid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select hdr.[planid],hdr.[planno],hdr.plandate,hdr.remarks,hdr.status,hdr.considerschedule,
	hdr.confirmedon,hdr.confirmedby,hdr.approvedon,hdr.approvedby,hdr.wopogenerated 
	from db_production.hdr_productionplan hdr join (select distinct planid from db_production.dtl_productionplan) dtl on hdr.planid = dtl.planid '
	set @sql += ' where hdr.isActive=1 and hdr.coid = ' + cast(@coid as varchar(5)) + ' and 
	hdr.boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and hdr.planno = ' + cast(@search as varchar(5)) 
		end
		set @sql +=' order by hdr.' + 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(hdr.planid) records from db_production.hdr_productionplan hdr
	 join (select distinct planid from db_production.dtl_productionplan) dtl on hdr.planid = dtl.planid
	 where hdr.coid = @coid and hdr.boid = @boid and hdr.isactive= 1
 
					
	
	
END



GO
/****** Object:  StoredProcedure [db_production].[pr_getuserbatches]    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_production].[pr_getuserbatches] 1,1,1,1,1,20,'batchid','','',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getuserbatches]
    @coid int,
	@boid int,
	@fyid int,
	@userid int,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='batchid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@searchtype varchar(50)='batchno'
AS
Begin
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	set @sql = 'select hdr.batchid, batchdate,batchno,batchreleasedate, hdr.remarks, wono, targetdate, dtl.quantity , mst.itemname,mst.itemcode,mst.oldcode 
	from db_production.hdr_batch hdr 
	join db_production.dtl_batch dtl on hdr.batchid = dtl.batchid 
	join db_production.hdr_workorder wo on hdr.woid = wo.woid 
	join db_mm.mst_item mst on dtl.itemid = mst.id '
	set @sql += ' where dtl.supervisorid = ' + cast(@userid as varchar(5)) + ' 
	 and hdr.coid = ' + cast(@coid as varchar(5)) + ' and hdr.boid = ' + cast(@boid as varchar(5)) + ' 
	 and hdr.fyid = ' + cast(@fyid as varchar(5)) + ' and hdr.isactive = 1'
	
	if (@searchtype = 'batchno' and @search!='') 
	begin
		set @sql += ' and hdr.batchno = ' + @search
	end
	else if (@searchtype = 'itemid' and @search!='')
	begin
		set @sql += ' and dtl.itemid = ' + @search 
	end
	if (@sort ='' or @sort = null) 
	begin
		set @sql +=' order by batchid desc '
	end
	else
	begin
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
	end
		if(isnull(@PageNumber,0)>0)
			begin
			set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
			FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
			end
	print @sql
	EXEC sp_executesql @SQL

	select count(hdr.batchid) records from db_production.hdr_batch hdr 
	join db_production.dtl_batch dtl on hdr.batchid = dtl.batchid 
	join db_production.hdr_workorder wo on hdr.woid = wo.woid 
	where dtl.supervisorid = @userid and hdr.coid = @coid and hdr.boid = @boid and hdr.fyid = @fyid 
	and hdr.isActive = 1
 
			
End


GO
/****** Object:  StoredProcedure [db_production].[pr_getwodata]    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_production].[pr_getwodata]  1,1,3
-- =============================================
CREATE PROCEDURE [db_production].[pr_getwodata] 
	@coid int,
	@boid int,
	@woid int

AS
BEGIN
	SET NOCOUNT ON;
	declare @oaid bigint;
	
	SELECT [woid],[wono],[wodate],wocategoryid,remarks,status,expectedstartdate,expectedcompletiondate,
	actualstartdate,actualcompletiondate from db_production.hdr_workorder WHERE woid=@woid

	 SELECT p.id, p.[itemid],[oaid],isnull(p.[bomid],1) bomid,p.woid, im.itemname,im.itemcode,im.oldcode,im.itemdescription, 
	 p.quantity woquantity,isnull(bdtl.quantity,0) quantity ,uom.uom,isnull(bdtl.batchid,0) batchid,
	 isnull(batchno,0) batchno, b.batchdate, isnull(bdtl.supervisorid,0) supervisorid,
	  u.firstname + ' ' + u.lastname supervisor , isnull(p.itemtypeid,0) itemtypeid
	 from db_production.dtl_workorder p
	 left join db_production.hdr_batch b on p.woid = b.woid and p.id = b.wodetailid 
	 left join db_production.dtl_batch bdtl on b.batchid= bdtl.batchid 
	 JOIN [db_mm].[mst_item] im ON p.itemid=im.id 
	 left join [db_mm].[mst_itemuom] uom on im.receivingunitid = uom.id
	 left join db_masters.users u on bdtl.supervisorid = u.userid
    where p.woid = @woid order by batchid 

	select itemid, deliverydate, qtytobedispatch,orderid from db_sop.order_deliveryschedule 
	where orderid in (select distinct oaid from db_production.dtl_workorder where woid = @woid) and itemid >0

	/*select distinct p.itemid, itype.typeid, mst.name from db_production.dtl_workorder p 
	join db_mm.item_types itype on p.itemid = itype.itemid 
	join db_mm.mst_itemtypes mst on itype.typeid = mst.id
	where p.woid = @woid */

    select p.itemid,p.itemtypeid,mst.name from db_production.dtl_workorder p 
	join db_mm.mst_itemtypes mst on p.itemtypeid = mst.id where p.woid = @woid
    union 
    select itype.itemid, itype.typeid,mst.name from db_mm.item_types itype 
	join db_mm.mst_itemtypes mst on itype.typeid = mst.id 
    where itype.itemid in (select itemid from db_production.dtl_workorder where woid =@woid)


end
	




GO
/****** Object:  StoredProcedure [db_production].[pr_getwolist]    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_production].[pr_getwolist] 1,1,1,10,'woid','desc',''
-- =============================================
CREATE PROCEDURE [db_production].[pr_getwolist] 
	@coid int = 1,
	@boid int = 1,
	@PageNumber INT = 1,
	@PageSize INT = 20,
	@sort nvarchar(100)='woid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = ' Select [woid],[wono],wodate,remarks,status,expectedstartdate,expectedcompletiondate 
	from db_production.hdr_workorder'
	set @sql += ' where isActive=1 and coid = ' + cast(@coid as varchar(5)) + ' and boid = ' + cast(@boid as varchar(5))
		if(@search!='')
		begin
		 set @sql += ' and wono = ' + 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(woid) records from db_production.hdr_workorder  where coid = @coid and boid = @boid and isactive= 1
 
				
	
	
	
END



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

CREATE PROCEDURE [db_production].[pr_jobmovementcardcommanapi]
	@coid int,
	@boid INT,
	@fyid INT,
	@userid INT,
	@accesstoken VARCHAR(100)
AS
BEGIN
	SET NOCOUNT ON;	    

	 select isnull(max(id),0) as LastId FROM [db_production].[hdr_jobqtymovement]

	 SELECT id,operationname FROM [db_production].[mst_operation_stage]

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

	 SELECT id,machinedowntimereason FROM [db_production].[mst_mc_dtime_reasons]

	 SELECT id,reworkreason FROM [db_production].[mst_rework_reason]

	 SELECT id, rejectionreason FROM [db_production].[mst_rejection_reason]

	 SELECT id,MachineName FROM [db_masters].[mst_machine]

	 SELECT id,name FROM [db_masters].[operationmaster]

end 
	

GO
/****** Object:  StoredProcedure [db_production].[pr_releasebatch]    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,release batch and genereate jobcard or purchase indent>
-- =============================================
CREATE PROCEDURE [db_production].[pr_releasebatch]
    @releasebatch [db_production].[dtl_releasebatch_tvp] readonly,
	@userid int
AS
Begin
	declare @batchid bigint, @itemid bigint, @coid bigint, @boid bigint,@fyid bigint, @batchno bigint
	declare @qty decimal(13,2) 
	declare @releasedate datetime

	select top 1 @batchid = batchid, @qty=qtytobereleased, @releasedate=releasedate from @releasebatch where id = 0
	
	select top 1 @itemid = dtl.itemid,@coid = coid,@boid = boid,@fyid=fyid, @batchno = batchno from db_production.hdr_batch hdr 
	join db_production.dtl_batch dtl on hdr.batchid = dtl.batchid where hdr.batchid = @batchid
	

-- delete records for missing ids in tvp 
	delete from [db_production].[dtl_releasebatch] where batchid = @batchid and id not in (select id from @releasebatch) and itemid = @itemid
	
	-- update existing enteries in 	[db_production].[dtl_releasebatch]	
	update [db_production].[dtl_releasebatch] set qtytobereleased = a.qtytobereleased, releasedate = a.releasedate 
	from @releasebatch a where [db_production].[dtl_releasebatch].id = a.id and  [db_production].[dtl_releasebatch].batchid = a.batchid 

	-- insert new records
	insert into [db_production].[dtl_releasebatch] (batchid,qtytobereleased,releasedate,userid,itemid)
	select @batchid,qtytobereleased,releasedate,@userid,@itemid from @releasebatch where id = 0

	declare @mfactor decimal(5,2), @batchqty decimal(15,5), @releaseqty DECIMAL(15,5);

	select @batchqty=isnull(quantity,0) from db_production.dtl_batch where batchid =@batchid and itemid =@itemid  
	select @releaseqty=sum(isnull(qtytobereleased,0)) from db_production.dtl_releasebatch where  batchid =@batchid and itemid =@itemid  
	
	set @mfactor = @releaseqty/@batchqty

	update db_mm.dtl_requisition set maxissuanceallowed = isnull(@mfactor,1)*isnull(requestedquantity,1) 
	where reqnid = (select reqnid from db_mm.hdr_requisition where batchid = @batchid and itemid = @itemid)

	/*IF OBJECT_ID('tempdb..#itembom') IS NOT NULL DROP TABLE #itembom
	create table #itembom 
	(
		id bigint,
		itemid bigint,
		itemname varchar(500),
		itemcode varchar(50),
		oldcode varchar(20),
		quantity decimal(13,2),
		typecode char(1),
		brandid int,
		toexplode bit,
		bomid bigint,
		uom varchar(20),
		uomid int
	)
	-- insert bom items for item in a kit/batch
	if exists(select id from db_mm.dtl_bom where pid=@itemid)
	Begin
		insert into #itembom (id,itemid,quantity,toexplode, brandid,uomid,typecode,bomid)
		select id,cid,isnull(@qty,1)*isnull(quantity,1),toexplode, brandid,unit,'P',bomid from db_mm.dtl_bom where pid = @itemid
	end
	else
	begin
		insert into #itembom (id,itemid,quantity,toexplode, uomid, brandid,typecode,bomid)
		values( 0,@itemid,isnull(@qty,1),0,0, 0,'P',0 )

		update #itembom set uomid = a.receivingunitid from db_mm.mst_item a where #itembom.itemid = a.id
	end
		--update typecode
		update #itembom set typecode = c.typecode from 
		(select a.itemid, a.typecode, a.name from
		(select dtl.id, itemid, Name, Typecode from db_mm.item_types dtl join db_mm.mst_itemtypes mst on dtl.typeid = mst.id where Typecode <> 'P') a join 
		(select itemid, isnull(min(dtl.id),0) id from db_mm.item_types  dtl join db_mm.mst_itemtypes mst on dtl.typeid = mst.id where Typecode <> 'P' group by itemid) b on
		a.id = b.id where a.id = b.id) c where #itembom.itemid = c.itemid

		--update item details
		update #itembom set itemname = a.itemname, itemcode= a.itemcode, oldcode = a.oldcode 
		from db_mm.mst_item a where #itembom.itemid = a.id

		-- update uom
		update #itembom set uom = a.uom
		from db_mm.mst_itemuom a where #itembom.uomid = a.id
	
		-- create purchase indents from production plan
		if exists(select id from #itembom where typecode = 'P')
		begin
			declare @indentid bigint, @indentno bigint;

			select @indentno= max(indentnumber)+1 from db_mm.hdr_indent

			--select * from db_production.hdr_productionplan
			insert into db_mm.hdr_indent (fyid,departmentid,indentdate,indentnumber,indentorid,remarks,costcentreid,coid,boid,isactive,createdby,createdon)
			values (@fyid,1,getdate(), @indentno, @userid, 'indent created from release batch ' + cast(@batchno as varchar(10)), @batchid,@coid,@boid,1,@userid,getdate())
		
			select @indentid = scope_identity()

			insert into db_mm.dtl_indent (indentid,itemid,quantityrequired,quantityapproved,quantitywoff,coid,boid,remarks,brandid)
			select @indentid, itemid,quantity,quantity,0,@coid,@boid, 'indent created from release batch', brandid	from #itembom where typecode = 'P'
		end
	
		if exists(select id from #itembom where typecode != 'P')
			Begin
				declare @jobno bigint,@jobid bigint,@reqid bigint,@reqno bigint;

				if not exists(select jobid from db_production.hdr_jobcard where batchid = @batchid)
				begin
					select @jobno = isnull(max(jobno),0)+1 from db_production.hdr_jobcard
					--create workorders from production plan
					insert into db_production.hdr_jobcard (jobno,batchid,startdate,status,isactive,createdby,createdon,supervisorid)
					select @jobno, @batchid,releasedate,1,1,@userid,getdate(),@userid from @releasebatch where id = 0

					select @jobid = scope_identity()
				end
				else 
				begin
					select @jobid = jobid from db_production.hdr_jobcard where batchid = @batchid
				end

				insert into db_production.dtl_jobcard (jobid,itemid,quantityrequested, quantitydelivered,stage,userid,status)
				select @jobid, itemid,quantity,0, 1,@userid, 1 from #itembom where typecode != 'P'

			End

		select @reqno = isnull(max(reqnno),0)+1 from db_mm.hdr_requisition
	
		insert into db_mm.hdr_requisition (deptid,storeid,reqnno,batchno,reqndate,isconfirm,remarks,coid,boid,confirmedby,createdby,createdon,fyid,productid,lotsize,bomid)
		values (1,1,@reqno, @batchno, @releasedate,1,'Requisition generated automatically for batchid ' + cast(@batchid as varchar(10)),@coid,@boid,@userid,@userid,getdate(),@fyid,@itemid,@qty,1)

		select @reqid = scope_identity()

		insert into db_mm.dtl_requisition (reqnid,itemid,brandid,requestedquantity,remarks)
		select @reqid,itemid,brandid,quantity, 'Requisition generated automatically for batchid ' + cast(@batchid as varchar(10)) from #itembom

		drop table #itembom*/
	

End

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



CREATE PROCEDURE [db_production].[pr_savejobmovementcard] 
	@statementtype nvarchar(50),
	@jobheader [db_production].[jobheader_tvp] readonly,
	@itemparameters [db_production].[itemparameters_tvp] readonly,
	@machineparameters [db_production].[machineparameters_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @id int, @jobmovementid INT,
		@machineid INT,@operatorid INT,@actualtimetaken INT, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@wono int;

	BEGIN TRANSACTION;
	If (@statementtype='Insert')
		Begin
			
			insert INTO [db_production].[hdr_jobqtymovement] (coid,boid,fyid,batchid,supervisorid,templateid,fromstageid,
			tostageid,dateofrelease,timeofrelease, isactive,createdby,createdon,modifiedby,modifiedon)
			SELECT coid,boid,fyid,batchid,supervisorid,templateid,fromstageid,
			tostageid,dateofrelease,timeofrelease, isactive,createdby,getdate(),modifiedby,modifiedon from @jobheader
			IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK;
			-- Raise an error and return
			RAISERROR ('Error while adding header data.', 16, 1);
			RETURN;
			END;
			
			SELECT @jobmovementid= SCOPE_IDENTITY();

			SELECT @machineid=machineid ,@operatorid=operatorid ,@actualtimetaken=actualtimetaken  FROM @machineparameters

			--INSERT INTO [db_production].[dtl_job_qty_movement] (jobmovementid,itemid,qtyofferedtoqc,isrework,okqty,toreworkqty,rejqty,machineid,operatorid,actualtimetaken,qcbyid,qcdate,qctime,isactive,createdby,createdon,modifiedby,modifiedon)
			--SELECT @jobmovementid,itemid,qtyofferedtoqc,isrework,okqty,toreworkqty,rejqty,@machineid,@operatorid,@actualtimetaken,qcbyid,qcdate,qctime,1,createdby,getdate(),modifiedby,modifiedon FROM @itemparameters

			--IF @@ERROR <> 0
			--BEGIN
			---- Rollback the transaction
			--ROLLBACK;
			---- Raise an error and return
			--RAISERROR ('Error while adding detail data.', 16, 1);
			--RETURN;
			--END;

			--INSERT INTO [db_production].[dtl_rework_rejection_reasons] (jobmovementid,itemid,reworkreasonid,rejreasonid,isactive,createdby,createdon,modifiedby,modifiedon)
			--SELECT  @jobmovementid,itemid, reworkreasonid,rejreasonid,1,createdby,getdate(),modifiedby,modifiedon FROM @itemparameters

			--	IF @@ERROR <> 0
			--BEGIN
			---- Rollback the transaction
			--ROLLBACK;
			---- Raise an error and return
			--RAISERROR ('Error while adding rejection rework data.', 16, 1);
			--RETURN;
			--END;
			
		end; 
	else
		Begin -- begin of update 
						
			UPDATE [db_production].[hdr_jobqtymovement]  set 
			[coid]=a.[coid],
			boid=a.boid,
			fyid=a.fyid,
			batchid=a.batchid,
			supervisorid=a.supervisorid,
			templateid=a.templateid,
			fromstageid=a.fromstageid,
			tostageid=a.tostageid,
			dateofrelease=a.dateofrelease,
			timeofrelease=a.timeofrelease,
			isactive=a.isactive,
			createdby=a.createdby,
			createdon=a.createdon,
			modifiedby=a.modifiedby,
			modifiedon = getdate()
			FROM   @jobheader a
			where [db_production].[hdr_jobqtymovement].id  = a.id;
							
		end;
	
	Commit;
End;			
GO
/****** Object:  StoredProcedure [db_production].[pr_savemovementcardtemplate]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [db_production].[pr_savemovementcardtemplate] 
	@statementtype nvarchar(50),
	@templateheader [db_production].[mst_template_movementcard_tvp] readonly,
	@itemparameters [db_production].[template_item_movementcard_tvp] readonly,
	@templateparameters [db_production].[template_parameters_movementcard_tvp] readonly,
	@templatemachines [db_production].[template_equipments_movementcard_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @templateid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@wono int
		declare @templatename varchar(100)

	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
			
			insert into db_production.mst_template_movementcard (coid,boid,templatename,isactive,createdby,createdon)
			SELECT coid,boid,templatename,1,@userid,getdate() from @templateheader
			IF @@ERROR <> 0
			BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding template header data.', 16, 1)
			RETURN
			END
			
			SELECT @templateid= SCOPE_IDENTITY()
			
			-- insert items
			insert into [db_production].[template_movement_items] (templateid,itemid,effectivefromdate) 
			select @templateid,itemid, effectivefromdate from @itemparameters 
			where itemid > 0
	
			-- insert template parameters		
			insert into db_production.template_parameters_movementcard (templateid,activityid,activity,operationsequence,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks)
			select @templateid,activityid,activity,operationsequence,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks from @templateparameters
			where activityid > 0 

			-- insert template equipments/machines
			insert into db_production.template_equipments_movementcard (templateid,machineid,activityid,sequenceorder,machine,toolsconsumable,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks,alternateofmachineid)
			select @templateid,machineid,activityid,sequenceorder, machine,toolsconsumable,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks,alternateofmachineid from @templatemachines 
			where machineid > 0	

		end 
	else
		Begin -- begin of update 
			-- fetching plan id from table type
			declare @isactive bit;
			
			select @templateid = id,@templatename=templatename, @isactive= isactive from @templateheader where id >0
			
			update db_production.mst_template_movementcard set 
				templatename = @templatename
				, isactive = @isactive
				, modifiedby = @userid
				, modifiedon = getdate()
				where id = @templateid

			-- update item information
			delete from [db_production].[template_movement_items] WHERE templateid = @templateid  
						
			insert into [db_production].[template_movement_items] (templateid,itemid,effectivefromdate) 
			select @templateid,itemid, effectivefromdate from @itemparameters 
			where itemid > 0

			-- update template parameters
			delete from db_production.template_parameters_movementcard where templateid = @templateid 

			-- insert template parameters		
			insert into db_production.template_parameters_movementcard (templateid,activityid,activity,operationsequence,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks)
			select @templateid,activityid,activity,operationsequence,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks from @templateparameters
			where activityid > 0 

			-- update template machines
			delete from db_production.template_equipments_movementcard where templateid = @templateid 

			-- insert template equipments/machines
			insert into db_production.template_equipments_movementcard (templateid,machineid,activityid,sequenceorder,machine,toolsconsumable,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks,alternateofmachineid)
			select @templateid,machineid,activityid,sequenceorder, machine,toolsconsumable,stdtimehrs,stdtimemins,stdtimesecs,costperhour,remarks,alternateofmachineid from @templatemachines 
			where machineid > 0	

			
		end
	
	Commit
End			
GO
/****** Object:  StoredProcedure [db_production].[pr_saveproductionplan]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



CREATE PROCEDURE [db_production].[pr_saveproductionplan] 
	@statementtype nvarchar(50),
	@planheader [db_production].[hdr_productionplan_tvp] readonly,
	@plandetail [db_production].[dtl_productionplan_tvp] readonly,
	@userid int=1,
	@coid int = 1,
	@boid int = 1,
	@fyid int =1 
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @planid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@planno int
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
			set @planno = (SELECT ISNULL(MAX(cast(planno as int)),0) + 1 FROM db_production.hdr_productionplan)
		
		
		insert into db_production.hdr_productionplan ([planno],plandate,remarks,[status],boid,coid,isactive,createdby,createdon,fyid )
			SELECT @planno,plandate,remarks,[status],@boid,@coid,1,@userid,getdate(),@fyid 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_production.dtl_productionplan ([planid],[itemid],[oaid],[bomid],domqty,expqty,stockqty,finalqty,instructioninfo,productcp,itemtypeid)
				select @planid,[itemid],[oaid],[bomid],domqty,expqty,stockqty,finalqty,instructioninfo,productcp,itemtypeid	from @plandetail
				
		end 
	else
		Begin -- begin of update 
			-- fetching plan id from table type
			select top 1 @planid = planid from @planheader

			select * from db_production.hdr_productionplan
			-- updating existing records from supplier table and checking @@ERROR 
			UPDATE db_production.hdr_productionplan set 
			[plandate]=a.[plandate],
			[planno]=a.[planno],
			[remarks]=a.[remarks],
			[status]=a.[status],
			[considerschedule]=a.[considerschedule],
			[modifiedby]=@userid,
			[modifiedon]=getdate(),
			[isactive] = a.isactive
            FROM   @planheader a
			WHERE db_production.hdr_productionplan.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 order record.', 16, 1)
					RETURN
				END
			
			-- delete item records from detail table which are not there in tvp for planrk order
			delete from db_production.dtl_productionplan where planid = @planid and id not in (select id from @plandetail) 

			-- insert new record
			insert into db_production.dtl_productionplan ([planid],[itemid],[oaid],[bomid],domqty,expqty,stockqty,finalqty,instructioninfo,productcp,itemtypeid)
				select @planid,[itemid],[oaid],[bomid],domqty,expqty,stockqty,finalqty,instructioninfo,productcp,itemtypeid	
			from @plandetail where id = 0

			select * from db_production.dtl_productionplan 
			-- update existing records
			update db_production.dtl_productionplan set
			itemid = a.itemid,
			oaid = a.oaid,
			bomid = a.bomid,
			domqty = a.domqty,
			expqty = a.expqty,
			stockqty = a.stockqty,
			finalqty = a.finalqty,
			instructioninfo = a.instructioninfo,
			productcp = a.productcp,
			itemtypeid = a.itemtypeid
			from @plandetail a 
			where db_production.dtl_productionplan.id = a.id 


	End
	--Commit the transaction....
		COMMIT
End			
GO
/****** Object:  StoredProcedure [db_production].[pr_savewo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO



create PROCEDURE [db_production].[pr_savewo] 
	@statementtype nvarchar(50),
	@woheader [db_production].[hdr_wo_tvp] readonly,
	@wodetail [db_production].[dtl_wo_tvp] readonly,
	@userid int=1
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON; 
	SET NOCOUNT ON;
		declare @woid int, @rowcnt int, @colstring nvarchar(max),@sql nvarchar(max),@wono int
		
	BEGIN TRANSACTION
	If (@statementtype='Insert')
		Begin
		
			set @wono = (SELECT ISNULL(MAX(wono),0) + 1 FROM db_production.hdr_workorder)
		
		select * from db_production.hdr_workorder
		insert into db_production.hdr_workorder ([wono],wodate,wocategoryid,remarks,[status],expectedstartdate,expectedcompletiondate,
		actualstartdate,actualcompletiondate,boid,coid,isactive,createdby,createdon,fyid )
			SELECT @wono,wodate,wocategoryid,remarks,[status],expectedstartdate,expectedcompletiondate,
		actualstartdate,actualcompletiondate,boid,coid,1,@userid,getdate(),fyid from @woheader
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while adding wo header data.', 16, 1)
				RETURN
				END
				SELECT @woid= SCOPE_IDENTITY()
				IF @@ERROR <> 0
				BEGIN
				-- Rollback the transaction
				ROLLBACK
				-- Raise an error and return
				RAISERROR ('Error while getting wo id.', 16, 1)
				RETURN
				END
				
					
				insert into db_production.dtl_workorder ([woid],[itemid],[oaid],[bomid],[quantity],[expectedcompletiondate],[deliverypromised],wipstage,wipcost,itemtypeid)
				select @woid,itemid,oaid,bomid,quantity,expectedcompletiondate,deliverypromised,wipstage,wipcost , itemtypeid from @wodetail
		end 
	else
		Begin -- begin of update 
			-- fetching plan id from table type
			select top 1 @woid = woid from @woheader

			-- updating existing records from supplier table and checking @@ERROR 
			UPDATE db_production.hdr_workorder set 
			[wodate]=a.[wodate],
			[wocategoryid]=a.[wocategoryid],
			[remarks]=a.[remarks],
			[status]=a.[status],
			[expectedstartdate]=a.[expectedstartdate],
			[expectedcompletiondate]=a.[expectedcompletiondate],
			[actualstartdate]=a.[actualstartdate],
			[actualcompletiondate]=a.[actualcompletiondate],
			[modifiedby]=@userid,
			[modifiedon]=getdate()
            FROM   @woheader a
			WHERE db_production.hdr_workorder.woid= a.woid 
		
			-- 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 work order record.', 16, 1)
					RETURN
				END
			
			-- delete item records from detail table which are not there in tvp for work order
			delete from db_production.dtl_workorder where woid = @woid and  
			itemid not in (select itemid from @wodetail)

			-- insert new record
			insert into db_production.dtl_workorder ([woid],[itemid],[oaid],[bomid],[quantity],[expectedcompletiondate],[deliverypromised],wipstage,wipcost,itemtypeid)
			select @woid,itemid,oaid,bomid,quantity,expectedcompletiondate,deliverypromised,wipstage,wipcost, itemtypeid from @wodetail where id = 0

			-- update existing records
			update db_production.dtl_workorder set
			itemid = a.itemid,
			oaid = a.oaid,
			bomid = a.bomid,
			quantity = a.quantity,
			expectedcompletiondate = a.expectedcompletiondate,
			deliverypromised = a.deliverypromised,
			wipstage = a.wipstage,
			wipcost = a.wipcost,
			itemtypeid = a.itemtypeid 
			from @wodetail a where db_production.dtl_workorder.id = a.id and db_production.dtl_workorder.woid=@woid


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

CREATE PROCEDURE [db_qc].[pr_commonapiinspectionrpt]
	@coid int,
	@boid int,
	@groupid int = null	
AS
BEGIN
	SET NOCOUNT ON;	

	select isnull(max(qcintimationno),0) intimationno from [db_qc].[hdr_qc_transactions]

    select id,type from [db_qc].[mst_qctype]

	select userid,firstname from [db_masters].[users]
    
	select id,qctestgroupid,qctest from [db_qc].[mst_qc_parameters] where coid=@coid and boid=@boid 

	select id,unitgroupid,unit from [db_qc].[mst_qcunits] where coid=@coid and boid=@boid 

end 
	

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

CREATE PROCEDURE [db_qc].[pr_commonapiqc]
	@coid int,
	@boid int,
	@groupid int = null	
AS
BEGIN
	SET NOCOUNT ON;	    
		Select id,colour from [db_qc].[mst_qccolours] where coid=@coid and boid=@boid and isactive=1
		Select id,lablocations from [db_qc].[mst_qclablocations] where coid=@coid and boid=@boid and isactive=1
		Select id,operators from [db_qc].[mst_qcoperators] where coid=@coid and boid=@boid and isactive=1
		Select id,sign from [db_qc].[mst_qcsigns]     where coid=@coid and boid=@boid and isactive=1
		Select id,smells from [db_qc].[mst_qcsmells]  where coid=@coid and boid=@boid and isactive=1
		Select id,tastes from [db_qc].[mst_qctastes]  where coid=@coid and boid=@boid and isactive=1
		Select id,qcgroup,groupfields from [db_qc].[mst_qc_parametergroups]  where coid=@coid and boid=@boid and isactive=1
		Select id,qctestgroupid,qctest from [db_qc].[mst_qc_parameters]where coid=@coid and boid=@boid 
		Select id,textures from [db_qc].[mst_qctextures]  where coid=@coid and boid=@boid and isactive=1
		Select id,type from [db_qc].[mst_qctype]  where coid=@coid and boid=@boid and isactive=1
		Select id,unitgroup from [db_qc].[mst_qcunitgroups] where coid=@coid and boid=@boid and isactive=1
        Select id,unitgroupid,unit from [db_qc].[mst_qcunits] where coid=@coid and boid=@boid 
		Select id,valuetype,fields from [db_qc].[mst_qcvaluetypes] where coid=@coid and boid=@boid and isactive=1
		select id,type from [db_qc].[mst_qctype]
		select isnull(max(testno),0)  testno from db_qc.hdr_qctests		
end 
	

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

 -- exec [db_qc].[pr_getintimationdetails] 1,1,1,104,1

CREATE PROCEDURE [db_qc].[pr_getintimationdetails]
	@coid int,
	@boid int,
	@fyid int,
	@id  bigint,
	@intimationno  bigint
AS
BEGIN
SET NOCOUNT ON;

  
    select hdr.coid,hdr.boid,hdr.id,hdr.testid,hdr.testno,hdr.qcintimationno,hdr.qcintimationdate,
	       hdr.qclablocationid,hdr.arno,hdr.date,hdr.grnno,hdr.grndate,hdr.grnid,hdr.grnqty,
		   hdr.itemid,hdr.brandid,hdr.mfgdate,hdr.expirydate,hdr.batchno,hdr.qty,hdr.sampleqty,
		   hdr.samplecollectedon,hdr.qcby,hdr.nextqcdate,hdr.releasedate,hdr.okqty,hdr.quantityrejected,
		   hdr.remarks,hdr.generalobservations,hdr.isdeviation,hdr.deviationrefno,hdr.deviationrefdt,
		   hdr.deviationapprovedby,hdr.deviationapprovedon,hdr.createdby,hdr.createdon,hdr.modifiedby,
		   hdr.modifiedon,hdr.supplierid,hdr.ref_no,hdr.ref_date,hdr.aprvl_remarks,hdr.qctype,hdr.fyid,
		   itm.itemname,supl.name
	from db_qc.hdr_qc_transactions hdr
	left join db_mm.mst_item itm  on hdr.itemid = itm.id
	left join db_masters.supplier supl on hdr.supplierid = supl.id 	
	where hdr.id = @id and hdr.qcintimationno = @intimationno


	select * from db_qc.dtl_qc_transactions where testid = @id

    select id,type from [db_qc].[mst_qctype]

	select userid,firstname from [db_masters].[users]
    
	select id,qctestgroupid,qctest from [db_qc].[mst_qc_parameters] where coid=@coid and boid=@boid 

	select id,unitgroupid,unit from [db_qc].[mst_qcunits] where coid=@coid and boid=@boid 

	
	

end


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

-- exec [db_qc].[pr_getQcintimationList] 1,200,1,1,''

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

	begin
	set @sql= 'select hdr.id,hdr.qcintimationno,Format(hdr.qcintimationdate,''dd-MM-yyyy'') qcintimationdate,
       itm.itemname,hdr.grnno,qc.type,hdr.testid
       from [db_qc].[hdr_qc_transactions] hdr
       inner join db_mm.mst_item itm on hdr.itemid=itm.id
       inner join db_qc.mst_qctype qc on hdr.qctype = qc.id'
	set @sql += ' where hdr.coid = '+ cast(@coid as varchar(5)) +' and hdr.boid='+ cast(@boid as varchar(5))+''
	end

	--if(@search!='')
	--begin
		 --set @sql += 'and hdr.quoteno like '+'''%'+cast(@search as varchar(50)) + '%'''
	--end 

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

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

	select  count(hdr.[id])records 
    from [db_qc].[hdr_qc_transactions] hdr
    inner join db_mm.mst_item itm on hdr.itemid=itm.id
    inner join db_qc.mst_qctype qc on hdr.qctype = qc.id

END

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

-- exec [db_qc].[pr_getqctestlist] 1,200,1,1,'trainee','hdr.id','desc'

   CREATE PROCEDURE [db_qc].[pr_getqctestlist]
    @PageNumber int =1,
	@Pagesize int=200,
    @coid int,
	@boid int,
	@search varchar(100)='',
	@sort nvarchar(100)='hdr.id',
	@sortorder nvarchar(100)='',
	@resumestatus varchar(20)=''

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

	begin
	set @sql=' select itm.itemname,hdr.testno,itm.itemcode,itm.oldcode,qctype.type,hdr.id,itmtest.itemid,
               format(itm.createdon,''dd/MM/yyyy'') createdon,format(hdr.modifiedon,''dd/MM/yyyy'') modifiedon
               from  [db_qc].hdr_qctests hdr
               inner join [db_qc].[mst_qctype] qctype on hdr.qctypeid = qctype.id
               left join  db_qc.itemwise_qctests itmtest on hdr.id = itmtest.testid
               inner join db_mm.mst_item itm  on itmtest.itemid = itm.id '
	 set @sql +=' where hdr.coid = '+ cast(@coid as varchar(5)) +' and hdr.boid='+ cast(@boid as varchar(5))+''

	-- set @sql +=' GROUP by itm.itemname,itm.oldcode,itm.itemcode,qc.qcid,qc.itemid,itm.modifiedon'
	 
	 set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ''
	 if(isnull(@PageNumber,0)>0)
	 begin
	 set @sql +=' OFFSET ' + cast(@Pagesize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
     FETCH NEXT ' + cast(@Pagesize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	 End
	
	print @SQL
	 
	EXEC sp_executesql @SQL

	set @totalcount = '  select count(hdr.id) records 
    from  [db_qc].hdr_qctests hdr
    inner join [db_qc].[mst_qctype] qctype on hdr.qctypeid = qctype.id
    left join  db_qc.itemwise_qctests itmtest on hdr.id = itmtest.testid
    inner join db_mm.mst_item itm  on itmtest.itemid = itm.id' 
	               
	end

	print @totalcount

	EXEC sp_executesql @totalcount

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

CREATE PROCEDURE [db_qc].[pr_getsetupqcdetails] 
	@coid int,
	@boid int,
	@fyid int,
	@itemid  bigint,
	@testid  bigint
AS
BEGIN
SET NOCOUNT ON;

    select * from db_qc.hdr_qctests where id = @testid
	-- select * from db_qc.dtl_qctests where testid=@testid

	select dtl.id,dtl.coid,dtl.boid,dtl.testid,grp.qcgroup,dtl.qcgroupid,prm.id,prm.qctest,
	vlu.valuetype,dtl.qcstdvalue1,dtl.qcstdvalue2,opr.operators,dtl.operatorid,un.unit,dtl.unitid
	from db_qc.dtl_qctests dtl
	inner join [db_qc].[mst_qc_parametergroups] grp on dtl.qcgroupid = grp.id
	inner join [db_qc].mst_qc_parameters prm on dtl.qcparameterid = prm.id
	inner join [db_qc].[mst_qcoperators] opr on dtl.operatorid = opr.id
	inner join [db_qc].[mst_qcvaluetypes] vlu on dtl.qcvaluetypeid = vlu.id
	inner join [db_qc].[mst_qcunits] un on dtl.unitid = un.id

	select qcitm.itemid,itm.itemname,itm.itemcode,itm.oldcode,uom.uom,qcitm.coid,qcitm.boid
	from db_qc.itemwise_qctests qcitm
	left join db_mm.mst_item itm on qcitm.itemid = itm.id
	left join db_mm.[mst_itemuom] uom on itm.issuingunitid = uom.id
	where testid =@testid  

	-- select * from db_qc.itemwise_qctests where testid=@testid	   
    -- common api data

    Select id,colour from [db_qc].[mst_qccolours]  where coid=@coid and boid=@boid and isactive=1
	Select id,lablocations from [db_qc].[mst_qclablocations] where coid=@coid and boid=@boid and isactive=1
	Select id,operators from [db_qc].[mst_qcoperators] where coid=@coid and boid=@boid and isactive=1
	Select id,sign from [db_qc].[mst_qcsigns]   where coid=@coid and boid=@boid and isactive=1
	Select id,smells from [db_qc].[mst_qcsmells]  where coid=@coid and boid=@boid and isactive=1
	Select id,tastes from [db_qc].[mst_qctastes]  where coid=@coid and boid=@boid and isactive=1
	Select id,qcgroup,groupfields from [db_qc].[mst_qc_parametergroups]  where coid=@coid and boid=@boid and isactive=1
	Select id,qctestgroupid,qctest from [db_qc].[mst_qc_parameters] where coid=@coid and boid=@boid 
	Select id,textures from [db_qc].[mst_qctextures] where coid=@coid and boid=@boid and isactive=1
	Select id,type from [db_qc].[mst_qctype]     where coid=@coid and boid=@boid and isactive=1
	Select id,unitgroup from [db_qc].[mst_qcunitgroups]  where coid=@coid and boid=@boid and isactive=1
    Select id,unitgroupid,unit from [db_qc].[mst_qcunits] where coid=@coid and boid=@boid 
	Select id,valuetype,fields from [db_qc].[mst_qcvaluetypes]  where coid=@coid and boid=@boid and isactive=1

end

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

 CREATE PROCEDURE [db_qc].[pr_saveqcinspectionrpt] 
    @statementtype nvarchar(50),
	@hdr_qctrn    [db_qc].[hdr_qc_transactions_tvp] readonly,
	@hdr_qctrndtl [db_qc].[dtl_qc_transactions_tvp] readonly
 AS
 BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @testno bigint,@testid bigint,@qcintimationno bigint

	If (@statementtype='Insert')
	BEGIN
			
	    set @qcintimationno =(SELECT ISNULL(MAX(qcintimationno), 0) + 1 from [db_qc].[hdr_qc_transactions]) 

        insert into [db_qc].[hdr_qc_transactions]
        (coid,boid,fyid,testid,testno,qcintimationno,qcintimationdate,qclablocationid,arno,[date],grnno,grndate,grnid,grnqty,itemid,brandid,mfgdate,expirydate,batchno,qty,sampleqty,samplecollectedon,qcby,nextqcdate,releasedate,okqty,quantityrejected,remarks,generalobservations,isdeviation,deviationrefno,deviationrefdt,deviationapprovedby,deviationapprovedon,createdby,createdon,supplierid,ref_no,ref_date,aprvl_remarks,qctype)
        select coid,boid,fyid,testid,testno,@qcintimationno,qcintimationdate,qclablocationid,arno,[date],grnno,grndate,grnid,grnqty,itemid,brandid,mfgdate,expirydate,batchno,qty,sampleqty,samplecollectedon,qcby,nextqcdate,releasedate,okqty,quantityrejected,remarks,generalobservations,isdeviation,deviationrefno,deviationrefdt,deviationapprovedby,deviationapprovedon,createdby,createdon,supplierid,ref_no,ref_date,aprvl_remarks,qctype
	    from @hdr_qctrn 

	    SELECT @testid= SCOPE_IDENTITY()		
			  
		insert into [db_qc].[dtl_qc_transactions]
		(coid,boid,fyid,testid,qcparameterid,qcparametername,qcstdvalue1,qcstdvalue2,qcobservedvalue1,qcobservedvalue2,createdby,createdon)
		 select coid,boid,fyid,@testid,qcparameterid,qcparametername,qcstdvalue1,qcstdvalue2,qcobservedvalue1,qcobservedvalue2,createdby,getdate() 
		 from @hdr_qctrndtl

      End

	    If (@statementtype='Update')
		  BEGIN
		  		             
			set @testid =(select top(1) id from @hdr_qctrn)

                 Update [db_qc].[hdr_qc_transactions] 
			      set 
                     testid = a.testid,
                     testno = a.testno,
                     qcintimationno = a.qcintimationno,
                     qcintimationdate = a.qcintimationdate,
                     qclablocationid = a.qclablocationid,
                     arno = a.arno,
                     [date] = a.[date], 
                     grnno = a.grnno ,
                     grndate = a.grndate,
                     grnid = a.grnid,
                     grnqty = a.[grnqty],
                     itemid = a.itemid,
                     brandid = a.brandid,
                     --mfgdate = a.mfgdate,
                     --expirydate = a.expirydate,
                     batchno = a.batchno,
                     qty = a.qty,
                     sampleqty = a.[sampleqty],
                     samplecollectedon = a.[samplecollectedon],
                     qcby = a.qcby,
                     nextqcdate = a.nextqcdate,
                     releasedate = a.releasedate,
                     okqty = a.okqty,
                     quantityrejected = a.quantityrejected,
                     remarks = a.remarks,
                     generalobservations = a.generalobservations,
                     isdeviation = a.isdeviation,
                     deviationrefno = a.deviationrefno,
                     deviationrefdt = a.deviationrefdt,
                     deviationapprovedby = a.deviationapprovedby,
                     deviationapprovedon = a.deviationapprovedon,
                     modifiedby = a.modifiedby,
                     modifiedon = getdate(),
                     supplierid = a.supplierid,
                     ref_no = a.ref_no,
                     ref_date = a.ref_date,
                     aprvl_remarks = a.aprvl_remarks,
                     qctype = a.qctype
			    FROM  @hdr_qctrn  a	
				where [db_qc].[hdr_qc_transactions].id = a.id

		  delete from [db_qc].[dtl_qc_transactions] where testid = @testid

		  insert into [db_qc].[dtl_qc_transactions]
		  (coid,boid,fyid,testid,qcparameterid,qcparametername,qcstdvalue1,qcstdvalue2,qcobservedvalue1,qcobservedvalue2,createdby,createdon)
		  select coid,boid,fyid,@testid,qcparameterid,qcparametername,qcstdvalue1,qcstdvalue2,qcobservedvalue1,qcobservedvalue2,createdby,getdate() 
		  from @hdr_qctrndtl

	 End	
 END

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

CREATE PROCEDURE [db_qc].[pr_saveqcsetup] 
    @statementtype nvarchar(50),
	@hdr_qcsetup  [db_qc].[hdr_qctest_tvp] readonly,
	@hdr_qcdtl    [db_qc].[dtl_qctest_tvp] readonly,
	@itemwise_qctest [db_qc].[itemwise__tvp] readonly	
AS
BEGIN 
SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;   
	SET NOCOUNT ON;
	declare @testno bigint,@testid bigint

		If (@statementtype='Insert')
		 BEGIN
			
			set @testno = (SELECT ISNULL(MAX(testno), 0) + 1 from db_qc.hdr_qctests) 
 
		    insert into [db_qc].hdr_qctests
			(coid,boid,fyid,qctypeid,testno,testdate,createdby,createdon,qctestname)
		     select coid,boid,fyid,qctypeid,@testno,testdate,userid,getdate(),qctestname from @hdr_qcsetup

			 SELECT @testid= SCOPE_IDENTITY()		
			  
			 insert into [db_qc].dtl_qctests
		     (coid,boid,testid,qcgroupid,qcparameterid,qcvaluetypeid,qcstdvalue1,qcstdvalue2,operatorid,unitid,createdby,createdon)
				select coid,boid,@testid,groupid,qctestid,qcvaluetypeid,qcstdvalue1,qcstdvalue2,operatorid,unitid,userid,getdate()
				from @hdr_qcdtl

               insert into db_qc.itemwise_qctests 
			     (coid,boid,testid,itemid,createdby,createdon)
			      select coid,boid,@testid,itemid,userid,getdate()from @itemwise_qctest
          End

		 If (@statementtype='Update')
		  BEGIN
		             
			set @testid =(select top(1) id  from  @hdr_qcsetup)

            Update [db_qc].hdr_qctests 
			  set testdate = a.testdate,
			      qctypeid = a.qctypeid
			 FROM  @hdr_qcsetup a	where [db_qc].hdr_qctests.id = a.id

			 delete from [db_qc].dtl_qctests where testid =@testid

			 insert into [db_qc].dtl_qctests
		        (coid,boid,testid,qcgroupid,qcparameterid,qcvaluetypeid,qcstdvalue1,qcstdvalue2,operatorid,unitid,createdby,createdon)
				select coid,boid,@testid,groupid,qctestid,qcvaluetypeid,qcstdvalue1,qcstdvalue2,operatorid,unitid,userid,getdate()
				from @hdr_qcdtl


			   delete from db_qc.itemwise_qctests  where testid =@testid

			   insert into db_qc.itemwise_qctests (coid,boid,testid,itemid,createdby,createdon)
			   select coid,boid,@testid,itemid,userid,getdate()from @itemwise_qctest

		 End	
 END

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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_confirminvoice]1,1,1,10022
-- =============================================
CREATE PROCEDURE [db_sop].[pr_cancelinvoice]
    @coid int,
	@boid int,
	@userid int,
	@invid VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	--update saleheader
	update [db_sop].[hdr_sale]  set  
	cancelledon=getdate(),
	cancelledbyuserid=@userid
	where id =@invid
	--update stocktrn
	INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[refid],[itemquantity],[trntypeid],[trnoperator],[coid],[boid],isactive,createdby,createdon,batch,mfgdate,expdate)
				SELECT (itemid),(itemid),(1),(@invid),(qty),1020,'+',@coid,@boid,1,@userid,getdate(),batch,mfgdate,expdate  from [db_sop].[dtl_sale_batches] where invid=@invid
				and [db_sop].[dtl_sale_batches].qty > 0
	
	----update [db_sop].[dtl_saleorder] i.e qtyalreadydispatched
update dtsaleodr  set dtsaleodr.qtyalreadydispatched=isnull(dtsaleodr.qtyalreadydispatched,0)- dtlsale.qtytodispatch from [db_sop].[dtl_saleorder] dtsaleodr 
inner join  [db_sop].[dtl_sale] dtlsale  on
 dtlsale.oaid=dtsaleodr.oaid where   dtsaleodr.itemid=dtlsale.itemid and dtlsale.invid=@invid

 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 @voucherno ,1,getdate(),(select invamt from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + ' ),''J'',''P'',
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1
				union all select @voucherno,2,getdate(),(select billamount-igstamount-cgstamount-sgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select sum(isnull(basicamount,0))  from	[db_sop].[dtl_sale]	h inner join 
               [db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=' + cast(@invid as varchar(5)) + ' group by h.invid,h.gstid),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1'
			   ---if (@igstamt>0)
			   begin 
				set @sql += ' union all  select @voucherno,3,getdate(),(select igstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 '
				end 
				--else 
				begin
				set @sql += ' union all  select @voucherno,4,getdate(),(select cgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 
				 union all  select @voucherno,5,getdate(),(select sgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 '
				end

	END
 



GO
/****** Object:  StoredProcedure [db_sop].[pr_commonapicustomerorder]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
  
--exec [db_sop].[pr_commonapicustomerorder] 1,1,1  
  
  
  
CREATE PROCEDURE [db_sop].[pr_commonapicustomerorder]  
 @coid int,  
 @boid int,  
 @fyid int = null  
  
AS  
  
BEGIN  
  
 SET NOCOUNT ON;  
  
 -- get max oano  
  
  select (isnull(max(oano),0)) oano  from [db_sop].[hdr_saleorder] where coid=@coid and boid=@boid  
 -- get docs. required  
  
 SELECT id, name as documentinfo  
  
    FROM    db_sop.mst_documentsreqd x where coid= @coid and boid=@boid  order by srno  
 -- get pyt terms  
  
 SELECT  id, name as paymentterm  
    FROM    db_sop.mst_paymentterms x where coid= @coid and boid=@boid  order by srno  
 -- get terms and conditions  
  
 SELECT    id, name as termsandcondition  
    FROM      db_sop.mst_termsandconditions x where coid= @coid and boid=@boid  order by srno  
 ---get indentor  
  
  select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))  
  ---get gst list   
  
  -- change by mohit (12-06-2019)  
  
 Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]  
  
 from [db_mm].[mst_gst] h join   
  
    db_mm.mst_hsn g on h.gstid=g.gstid  
  
 where h.coid = @coid and h.boid = @boid   
  
 order by hsncode asc  
  
  ---get packing  instructions  
  
 select id,name  from db_sop.mst_packinginstructions where  coid= @coid and boid=@boid  
  
  
  
    ---get installation info  
  
 select  id,name  from db_sop.mst_installationinfo where  coid= @coid and boid=@boid  
  
  
  
 --get customer order type  
  
 select id,ordertype from db_sop.mst_ordertype where isactive =1  and fyid=@fyid and coid= @coid and boid=@boid  
  
  
  
 -- get levies detail  
  
 select id,groupid,levyname,hsncode,accountidforpurchase,accountidforsale,gstid from db_masters.levies where isactive=1 and groupid = 1  
  
   
  
 --get UOM master  
  
 select id, uom from [db_mm].[mst_itemuom] where isactive=1  
  
 ---get Currency master  
  
 select  id, code , name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency  

 select id,[name] from db_sop.mst_discsummary_desc
  
end  
  
   
GO
/****** Object:  StoredProcedure [db_sop].[pr_confirminvoice]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_confirminvoice]1,1,1,5
-- =============================================
CREATE PROCEDURE [db_sop].[pr_confirminvoice]
    @coid int,
	@boid int,
	@userid int,
	@invid VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max),@voucherno bigint,@igstamt decimal(15,5)
	--update saleheader
	update [db_sop].[hdr_sale]  set invno= (SELECT ISNULL(MAX(invno), 0) + 1  from [db_sop].[hdr_sale]),
	confirmedbyuserid=@userid,
	invdate=getdate(),
	confirmedon=getdate()
	where id =@invid
	--update stocktrn
	INSERT INTO [db_mm].[item_stk_trn] ([itemid],[reqditemid],[brandid],[refid],[itemquantity],[trntypeid],[trnoperator],[coid],[boid],isactive,createdby,createdon,batch,mfgdate,expdate)
				SELECT (itemid),(itemid),(1),(@invid),(qty),10,'-',@coid,@boid,1,@userid,getdate(),batch,mfgdate,expdate  from [db_sop].[dtl_sale_batches] where invid=@invid
				and [db_sop].[dtl_sale_batches].qty > 0
	
	----update [db_sop].[dtl_saleorder] i.e qtyalreadydispatched
update dtsaleodr  set dtsaleodr.qtyalreadydispatched=isnull(dtsaleodr.qtyalreadydispatched,0)+ dtlsale.qtytodispatch from [db_sop].[dtl_saleorder] dtsaleodr 
inner join  [db_sop].[dtl_sale] dtlsale  on
 dtlsale.oaid=dtsaleodr.oaid where   dtsaleodr.itemid=dtlsale.itemid and dtlsale.invid=@invid
     select @igstamt=isnull((igstamt),0) from db_sop.hdr_sale where id=@invid
	select @voucherno= isnull(max(voucherno),0)+1 from [db_accounts].[voucher] where vouchercategory='S' ----and trntype=5
 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 @voucherno ,1,getdate(),(select invamt from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + ' ),''J'',''P'',
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''D'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1
				union all select @voucherno,2,getdate(),(select billamount-igstamount-cgstamount-sgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select sum(isnull(basicamount,0))  from	[db_sop].[dtl_sale]	h inner join 
               [db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=' + cast(@invid as varchar(5)) + ' group by h.invid,h.gstid),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1'
			   if (@igstamt>0)
			   begin 
				set @sql += ' union all  select @voucherno,3,getdate(),(select igstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 '
				end 
				else 
				begin
				set @sql += ' union all  select @voucherno,4,getdate(),(select cgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 
				 union all  select @voucherno,5,getdate(),(select sgstamount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''J'',''P'',
				(select purchaseaccount from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),''C'',''purchase voucher'',' + cast(@invid as varchar(5)) + ',0,123,
				(select suplid from db_sop.hdr_sale where id=' + cast(@invid as varchar(5)) + '),1,1,1,1 '
				end
				
	           EXEC sp_executesql @SQL



	END
 



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

	@userid int,
    @sopdeliveryschedule [db_sop].[order_deliveryschedule_tvp] READONLY,
	@flag char(1) 
	-------save S check yet to be done while save we have to only update deliverydetail and in P we have to save and confirm production date
AS
BEGIN
	SET NOCOUNT ON;
	declare @orderid int
	--update saleheader
	select top 1 @orderid=orderid from @sopdeliveryschedule
	if (@flag='P')
	begin
	delete from [db_sop].[order_deliveryschedule] where orderid=@orderid
	insert into [db_sop].[order_deliveryschedule] ([orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon],[deliverydatebyproduction])
    select [orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon],[deliverydatebyproduction] from @sopdeliveryschedule
	update [db_sop].[hdr_saleorder] set approvedbyproductiondate=getdate(),approvedbyproductionuserid=@userid where oaid=@orderid
	end 
	if (@flag='M')
	begin 
	update [db_sop].[hdr_saleorder] set  [approvedbymarketingheaddate]=getdate(),approvedbymarketingheaduserid=@userid where oaid in (select orderid from @sopdeliveryschedule)
	end 
	if (@flag='C')
	begin 
	update [db_sop].[hdr_saleorder] set [approvedbyceodate]=getdate(),approvedbyceouserid=@userid where oaid in (select orderid from @sopdeliveryschedule)
    end 
	END
 



GO
/****** Object:  StoredProcedure [db_sop].[pr_getcontractreviewdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [db_sop].[pr_getcontractreviewdata] 
	@coid int,
	@boid int,
	@orderid bigint
	
AS
BEGIN
	SET NOCOUNT ON;
	
	-- sale order header data
	Select ih.oaid,	[oano], [oadate],[customerid],[customername],[customeraddr1],[customeraddr2],ih.[city],ih.[state],ih.[pin],[customergstno],
	[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],
	[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],
	[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],
	[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],isnull([basicamt],0) basicamt,
	isnull([discamt],0) discamt,isnull([netamt],0) netamt,
	isnull([igstamt],0) igstamt,isnull([cgstamt],0) cgstamt,isnull([sgstamt],0) sgstamt,isnull([orderamt],0) orderamt,[remarks],[ordertype],
	[ih].[marketexecutive],[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo]
	,c.mobile_number,c.email,c.gstin,c.pan
	from [db_sop].[hdr_saleorder] ih
	inner join db_masters.customer c on ih.customerid=c.id
	 where ih.oaid =@orderid

	 -- sale order item detail
	 select [itemcode],(im.[itemname]+' ('+ [oldcode]+')') as itemname,[itemid],id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],u.[uom],id.[gstid],
	 [igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]
	 ,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],im.hsncode,id.[remarks],id.[mrp],id.[focqty]
	 from [db_sop].[dtl_saleorder] 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_hsn] h on g.gstid=h.gstid and id.gstid=g.gstid
	   where id.oaid =@orderid

	-- payment terms of customer order
	 select [paymenttermid], [paymentterm], [percent], [amount] from  [db_sop].[order_paymentterms] t2 
	 where t2.orderid =@orderid


	 -- contract review data
	SELECT [id],[oaid],[crdate],case when len([dealerexpenses])>0 then 1 else 0 end dealerexpensesrequired,[dealerexpenses]
		,[emddetailrequired],[emddetail],[emddate],[securitydepositrequired],[securitydepositdetail]
		,case when [securitydepositdate] = '1900-01-01T00:00:00' then '' else [securitydepositdate] end [securitydepositdate]
		,case when len([ldclause])>0 then 1 else 0 end ldclauserequired, [ldclause]
		,case when len([agreement])>0 then 1 else 0 end agreementrequired, [agreement]
		,case when len([inspection])>0 then 1 else 0 end inspectionrequired, [inspection]
		,case when [deliveryrequestedbycustomer] = '1900-01-01T00:00:00' then '' else [deliveryrequestedbycustomer] end [deliveryrequestedbycustomer]
		,case when [datecommittedbyproduction] = '1900-01-01T00:00:00' then '' else [datecommittedbyproduction] end [datecommittedbyproduction]
		,case when [qcandpackingdate] = '1900-01-01T00:00:00' then '' else [qcandpackingdate] end [qcandpackingdate]
		,case when cast([receivedbycustomerdate] as varchar(10)) = '1900-01-01' then '' else [receivedbycustomerdate] end [receivedbycustomerdate]
		,case when len([stockorder])>0 then 1 else 0 end stockorderrequired,[stockorder]
		,case when len([technicalquery])>0 then 1 else 0 end technicalqueryrequired,[technicalquery]
		,case when len([installationInfo])>0 then 1 else 0 end installationInforequired,[installationInfo]
		,case when len([exciseexemption])>0 then 1 else 0 end exciseexemptionrequired,[exciseexemption]
		,[ewaybillrequired]
		,case when len([customerpendency])>0 then 1 else 0 end customerpendencyrequired, [customerpendency]
		,case when len([companypendency])>0 then 1 else 0 end companypendencyrequired, [companypendency]
		,[contactuser],[freight],[remarks],[review1] reviewone,[review2] reviewtwo,[review3] reviewthree FROM [db_sop].[contractreview_saleorder] ih
	 where ih.oaid =@orderid

	
end
GO
/****** Object:  StoredProcedure [db_sop].[pr_getcustomerorderdata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
  
-- =============================================  
-- Author:  <Author,Amit>  
-- Create date: <Create Date,03-12-2018>  
-- Description: <Description,Get supplier data>  
-- exec [db_sop].[pr_getcustomerorderdata] 1,1,10107  
-- =============================================  
CREATE PROCEDURE [db_sop].[pr_getcustomerorderdata]   
 @coid int,  
 @boid int,  
 @orderid int  
  
AS  
BEGIN  
 SET NOCOUNT ON;  
   
   
 Select ih.oaid, [oano], [oadate],[customerid],[customername],[customeraddr1],[customeraddr2],ih.[city],ih.[state],ih.[pin],[customergstno],  
 [customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],  
 isnull([billtocustomerid],ih.customerid) billtocustomerid, isnull([billtocustomerid],ih.customerid) billtocustomerid1,[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],  
 [billtocustomergstno],isnull([consigneecustomerid],ih.customerid) consigneecustomerid,[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],  
 [consigneestate],[consigneepin],[consigneecustomergstno],isnull([custPoNo],ih.ourquoteno) [custPoNo],isnull([custPodate],ih.ourquotedate) [custPodate],  
 [ourquoteno],[ourquotedate],isnull([basicamt],0) basicamt,  
 isnull([discamt],0) discamt,isnull([netamt],0) netamt,  
 isnull([igstamt],0) igstamt,isnull([cgstamt],0) cgstamt,isnull([sgstamt],0) sgstamt,isnull([orderamt],0) orderamt,  
 [remarks],ih.ordertype,[ih].[marketexecutive],[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo],c.[state] stateid,totalamtinfc ,conversionrate,currency  
 from [db_sop].[hdr_saleorder] ih   
 left join  db_masters.customer c on ih.customerid=c.id  
 where ih.oaid =@orderid  
  
    
  select [itemcode],[oldcode],im.[itemname],[itemid],id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],u.[uom],id.[gstid],  
  [igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt]  
  ,[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],im.hsncode,id.[remarks],id.[mrp],id.[focqty],h.id hsnid,totalamtinfc,rateinfc  
  from [db_sop].[dtl_saleorder] id  
  left join [db_mm].[mst_item] im  on id.itemid= im.id  
    left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id  
   left  join [db_mm].[mst_gst] g on id.gstid=g.gstid  
   left  join [db_mm].[mst_hsn] h on im.gstid=h.gstid and im.hsncode=h.hsncode  
    where id.oaid = @orderid  
     
   select termsandconditionsid id,termsandconditionsid,t1.termsandcondition from [db_sop].[order_termsandconditions] t1   
   where t1.orderid =@orderid  
     
   select [paymenttermid], [paymentterm], [percent], [amount] from  [db_sop].[order_paymentterms] t2   
   where t2.orderid =@orderid  
  
   select d.itemid, im.itemcode,im.itemname, d.[qtytobedispatch], d.deliverydate as date, row_number() over(order by d.id asc) as id, u.uom as uom  
   from [db_sop].[order_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 t2.[id],[documentinfo]  from [db_sop].[order_documentsreqd] t2   
   where t2.orderid =@orderid  
  
  
    select t1.[accesorieid],[t1].[itemid] from [db_sop].[mst_accessories] t1   
   left join [db_sop].[order_itemaccessories] t2 on t1.accesorieid = t2.accessorieid  
   where t2.orderid =@orderid  
  
 -- get packinginstructions   
   select srno,instruction,instructionid from db_sop.order_packinginstructions where orderid =@orderid  
  
   -- get installation info   
   select srno,installationinfo,installationid from db_sop.order_installationinfo where orderid =@orderid  
    
   ---get market executive  
  select userid,firstname  from db_masters.users where  coid=+cast(@coid as varchar(5))  and boid=+cast(@coid as varchar(5))  
  
  ---get gst list   
  -- change by mohit (13-06-2019)  
 Select g.id hsnid, h.gstid, h.[description],g.[hsncode],h.[igst],h.[sgst],h.[cgst]  
 from [db_mm].[mst_gst] h join   
    db_mm.mst_hsn g on h.gstid=g.gstid  
 where h.coid = @coid and h.boid = @boid   
 order by hsncode asc  
  
  --get customer order type  
 select id,ordertype from db_sop.mst_ordertype where isactive =1   
  
 ---get Currency master  
 select  id, code , name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency  
 end  

 select * from [db_sop].[order_discountsummary] where orderid=@orderid

 select id,[name] from db_sop.mst_discsummary_desc

 ---- suplid check yet to be done.  
 ------- whether to use left join on brand or make it mandatory in ui.  
  
  
  
GO
/****** Object:  StoredProcedure [db_sop].[pr_getcustomerorderdatabyno]    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_sop].[pr_getcustomerorderdatabyno] 1,1,45
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getcustomerorderdatabyno] 
	@coid int,
	@boid int,
	@orderno varchar(10)

AS
BEGIN
	SET NOCOUNT ON;
	declare @orderid int;
	
	select @orderid = oaid from [db_sop].[hdr_saleorder] where oano = @orderno and coid = @coid and boid = @boid
	--print @orderid
	exec [db_sop].[pr_getcustomerorderitems] @coid, @boid,@orderid
	
	end
	


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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_getcustomerorderitems] 1,1,'10062'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getcustomerorderitems]
    @coid int,
	@boid int,
	@oaid varchar(100)
AS
Begin
	Select c.mobile_number,c.pan, c.gstin,c.email,	ih.oaid,[oano], [oadate],[customerid],[customername],[customeraddr1],[customeraddr2],ih.city,ih.state,ih.pin,[customergstno],
	[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],
	[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],
	[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],
	[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],isnull([basicamt],0) basicamt,
	isnull([discamt],0) discamt,isnull([netamt],0) netamt,
	isnull([igstamt],0) igstamt,isnull([cgstamt],0) cgstamt,isnull([sgstamt],0) sgstamt,isnull([orderamt],0) orderamt,
	[remarks],[ordertype],[ih].[marketexecutive],[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo],conversionrate,currency,totalamtinfc
	from [db_sop].[hdr_saleorder] ih
	join [db_masters].customer c on ih.customerid = c.id
	 where ih.oaid in (select * from dbo.fnSplitString(@oaid,','))

	IF OBJECT_ID('tempdb..#tempoadetail') IS NOT NULL DROP TABLE #tempoadetail
	create table #tempoadetail 
	(
		oaid bigint,
		itemid int,
		itemcode varchar(20),
		oldcode varchar(20),
		itemname varchar(200),
		hsncode	varchar(20),
		oadate	date,
		pendingquantity decimal(10,3),
		orderedquantity decimal(10,3),
		qtyalreadydispatched decimal(12,3),
		gstid	int,
		rate	decimal(12,3),
		netrate decimal(12,3),
		itemdiscpercent decimal(12,3),
		itemdiscamt decimal(12,3),
		igstrate decimal(12,3),
		sgstrate decimal(12,3),
		cgstrate decimal(12,3),
		cessrate decimal(12,3),
		uom varchar(20),
		focqty decimal(12,3),
		custPoNo varchar(20),
		bomid int,
		stock decimal(12,3),
        totalamtinfc decimal(15,2),
		rateinfc decimal(15,2)
	)
	insert into #tempoadetail (oaid,itemid, orderedquantity, pendingquantity,qtyalreadydispatched,gstid,focqty,rate,netrate,itemdiscpercent,itemdiscamt,igstrate,
	sgstrate,cgstrate,cessrate,uom,bomid,stock,totalamtinfc,rateinfc)
	select oaid,itemid,isnull(orderedquantity,0), isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0),
	isnull(qtyalreadydispatched,0), gstid,focqty,rate,
	netrate, itemdiscpercent,itemdiscamt,igstrate,sgstrate,cgstrate,cessrate,uom,0,0 ,totalamtinfc,rateinfc
	from [db_sop].[dtl_saleorder] where oaid in (select * from dbo.fnSplitString(@oaid,',')) 

	update #tempoadetail set itemcode = m.itemcode,oldcode = m.oldcode, itemname = m.itemname,hsncode = m.hsncode  
	from [db_mm].[mst_item] m where #tempoadetail.itemid = m.id

	update #tempoadetail set oadate = h.oadate, custPoNo = h.custPoNo
	from [db_sop].[hdr_saleorder] h where #tempoadetail.oaid = h.oaid

	update #tempoadetail set bomid = isnull(b.bomid,0) 
	from ( select productid, max(bomid) bomid from db_mm.hdr_bom group by productid) b where #tempoadetail.itemid = b.productid 
	
	update #tempoadetail set stock = isnull(a.stock,0) 
	from (select itemid, sum(isnull(itemquantity,0)*cast((trnoperator+ cast(1 as char)) as int)) stock from db_mm.item_stk_trn 
	where boid = @boid and coid = @coid 
	group by itemid) a where #tempoadetail.itemid = a.itemid

	select * from #tempoadetail where isnull(pendingquantity,0) > 0 
	
 	
	
	  select distinct termsandconditionsid,t1.termsandcondition from [db_sop].[order_termsandconditions] t1 
	  where t1.orderid in (select * from dbo.fnSplitString(@oaid,','))
	  
	  select distinct id,[paymenttermid], [paymentterm], [percent], [amount] from  [db_sop].[order_paymentterms] t2 
	  where t2.orderid in (select * from dbo.fnSplitString(@oaid,','))

	  select d.orderid, d.itemid, im.itemcode,im.itemname, d.[qtytobedispatch], d.deliverydate as date, row_number() over(order by d.id asc) as id, u.uom as uom
	  from [db_sop].[order_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 in (select * from dbo.fnSplitString(@oaid,','))

	  select distinct t2.[id],[documentinfo]  from [db_sop].[order_documentsreqd] t2 
	  where t2.orderid in (select * from dbo.fnSplitString(@oaid,','))


    select distinct t1.[accesorieid],[t1].[itemid] from [db_sop].[mst_accessories] t1 
	  left join [db_sop].[order_itemaccessories] t2 on t1.accesorieid = t2.accessorieid
	  where t2.orderid in (select * from dbo.fnSplitString(@oaid,','))

	-- get packinginstructions 
	  select distinct instruction,instructionid from db_sop.order_packinginstructions where orderid in (select * from dbo.fnSplitString(@oaid,','))

	  -- get installation info 
	  select distinct installationinfo,installationid from db_sop.order_installationinfo where orderid in (select * from dbo.fnSplitString(@oaid,','))
End

GO
/****** Object:  StoredProcedure [db_sop].[pr_getcustomerorderlist]    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_sop].[pr_getcustomerorderlist]  1,50,1,1,'oano','asc','INDUSTRIES','M','customername'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getcustomerorderlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='oano',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)='',
	@flag char(1)='',
	@searchtype varchar(20)= ''   --------C=confirmedbyceo,M=confirmedbymarktng,P=confirmedbyprdn
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);

	IF OBJECT_ID('tempdb..#temporders') IS NOT NULL DROP TABLE #temporders
	create table #temporders
	(
		oaid bigint,
		oano	varchar(10),
		oadate	date,
		createdby	int,
		username	varchar(100),
		customername varchar(300),
		custpono	varchar(200),
		orderamt	decimal(15,2),
		ourquoteno	varchar(20),
		ordertype	varchar(100) null,
		despatched	varchar(10),
		approvedbymarkethead char(1)
	)
	
	
	set @sql = 'insert into #temporders (oaid,oano,oadate,createdby,username,customername,custpono,orderamt,ourquoteno,ordertype,approvedbymarkethead) 
	Select [oaid],[oano],[oadate],h.[createdby],u.username,[customername],[custpono],[orderamt],[ourquoteno],ot.ordertype,
	case when h.approvedbymarketingheaddate is null then 0 else 1 end   from [db_sop].[hdr_saleorder] h
	left join  db_sop.mst_ordertype ot on h.ordertype=ot.id
	join [db_masters].[users] u on h.createdby = u.userid '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
	if (@searchtype = 'oano' and @search!='') 
	begin
		set @sql += ' and h.oano = ' + @search
	end
		if(@flag='P')
		begin
		 set @sql += ' and h.approvedbyproductiondate is null '
		end
		if(@flag='C')
		begin
		 set @sql += 'and h.approvedbyceodate is null  and h.approvedbyproductiondate is  not null '
		end
		if(@flag='M')
		begin
		 set @sql += 'and h.approvedbymarketingheaddate is null  '
		end
		 if (@searchtype = 'customername' and @search!='')
	begin
		set @sql += ' and  h.customername like ''%' + cast(@search as varchar(50)) + '%'''
		 set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',customername)asc, LEN(customername)' + @sortorder + ' '
		 end
		 else
		 begin 
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		end
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	--update #temporder for despatched -- set all to No
	update #temporders set despatched = 'No' 

	-- update #temporder for despatched -- set despatched = 'partial' where qtyalreadydispatched >0
	update #temporders set despatched = 'Partial'
	from (select oaid, sum(isnull(qtyalreadydispatched,0)) cnt from [db_sop].[dtl_saleorder] group by oaid having sum(qtyalreadydispatched)>0 ) a
	where #temporders.oaid = a.oaid

	-- update #temporder for despatched -- set despatched = 'Full' where qtyalreadydispatched =0
	update #temporders set despatched = 'Full'
	from (select oaid, sum(isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0)) cnt from [db_sop].[dtl_saleorder] group by oaid 
	having sum(isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0))=0 ) a 	where #temporders.oaid = a.oaid

	select * from #temporders order by oaid desc; 

	set @sql ='select count(h.oaid) records from [db_sop].[hdr_saleorder]  h
	join [db_masters].[users] u on h.createdby = u.userid '
	set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
	if (@searchtype = 'orderno' and @search!='') 
	begin
		set @sql += ' and h.oano = ' + @search
	end
	else if (@searchtype = 'customername' and @search!='')
	begin
		set @sql += ' and  h.customername like ''%' + cast(@search as varchar(50)) + '%'''
	end
		if(@flag='P')
		begin
		 set @sql += ' and h.approvedbyproductiondate is null '
		end
		if(@flag='C')
		begin
		 set @sql += 'and h.approvedbyceodate is null  and h.approvedbyproductiondate is  not null '
		end
		if(@flag='M')
		begin
		 set @sql += 'and h.approvedbymarketingheaddate is null  '
		end
		print @sql
	EXEC sp_executesql @SQL
	drop table #temporders;
	
END



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

-- =============================================
-- Author:		<Author,suk>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_getcustomerorderprintppc] 1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getcustomerorderprintppc] 
	@coid int,
	@boid int,
	@fyid int,
	@userid int=0,
	@accesstoken varchar(20)=null


AS
BEGIN
	SET NOCOUNT ON;
Select 	[oano], [oadate],[ih].[custPoNo],[id].[orderedquantity] batchsize,[customerid],[customername],[orderamt],im.itemname,[id].[mrp]
	from [db_sop].[hdr_saleorder] ih
	join [db_sop].[dtl_saleorder] id on ih.oaid=id.oaid
	join [db_mm].[mst_item] im on id.itemid=im.id
	where ih.fyid=@fyid and ih.coid=@coid and ih.boid=@boid

end

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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_getcustomersinvoice] 1,1,1
-- =============================================


CREATE PROCEDURE [db_sop].[pr_getcustomersinvoice] 
 @coid int,
 @boid int,
 @custid int
AS
BEGIN

	
	select id [invid],invno,invdate,customerid from [db_sop].[hdr_sale] where coid=@coid and boid=@boid and customerid=@custid	and invno>0 and (cancelledbyuserid=0 or cancelledbyuserid is null) order by invdate, invno desc

END 



GO
/****** Object:  StoredProcedure [db_sop].[pr_getdeliveryscheduledata]    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_sop].[pr_getdeliveryscheduledata] 1,1,10066
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getdeliveryscheduledata] 
	@coid int,
	@boid int,
	@oaid int

AS
BEGIN
	SET NOCOUNT ON;

	  select  d.orderid,d.itemid,d.remarks, im.itemcode,im.itemname, d.[qtytobedispatch], d.deliverydate, row_number() over(order by d.id asc) as id, u.uom as uom,d.deliverydatebyproduction
	  from [db_sop].[order_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 =@oaid

	 end

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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,25-02-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_getordertermsandconditions]1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getdocumentsreqd] 
@coid int,
@boid INT
AS
BEGIN

	SET NOCOUNT ON;
	
SELECT        id, name as documentinfo
FROM            db_sop.mst_documentsreqd x where coid= @coid and boid=@boid  order by srno

END


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

set @partyid=(Select partyid From   [db_sop].[hdr_drcrnote] where id=@id)
set @invid=(Select invid From   [db_sop].[hdr_drcrnote] where id=@id)

SELECT ISNULL(MAX(noteno), 0) as noteno from [db_sop].[hdr_drcrnote] 
where coid=@coid 
and boid=@boid

select 'D' as id, 'Debit Note' as type
union 
select 'C' as id, 'Credit Note' as type

Select id, reason from [db_sop].[mst_reasonfornote]

Select id, type from [db_mm].[mst_advicetypemaster]

Select id [invid], invno,invdate,customerid from db_sop.hdr_sale where customerid=@partyid and invno>0 and coid=@coid and boid=@boid and (cancelledbyuserid=0 or cancelledbyuserid is null);

Select id, noteno, notedate,  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
       [sgstamt], [cgstamt], [totalamt]
From   [db_sop].[hdr_drcrnote]
where id=@id;



SELECT d.id, d.itemid, im.[itemcode],im.[oldcode],im.[itemname], [billedqty], [noteqty], [rate], 	[taxableamt], [igst],
       [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], d.gstid, u.[uom], g.hsncode, d.notetypeid, type as notefor
from [db_sop].[dtl_drcrnote] d
Join [db_mm].[mst_item] im  on d.itemid= im.id
left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
left join [db_mm].[mst_advicetypemaster] a  on d.notetypeid = a.id
left join [db_mm].[mst_hsn] g on d.gstid=g.id
where d.noteid=@id

select im.[itemcode],im.[oldcode],im.[itemname],id.[itemid],id.oaid,od.oano, od.custpono, id.[billingdescription],id.[isfoc],id.[issample],id.[specialcode],
id.[packing],u.[uom],id.[gstid],id.[igstrate],id.[sgstrate],id.[cgstrate],id.[cessrate],id.[basicamount],id.[rate],id.[netrate],id.[orderedquantity],
id.[itemdiscpercent],id.[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],id.[totalamt],id.[remarks],id.qtyalreadydispatched, 
id.qtytodispatch,id.focqty,[batch],im.hsncode,g.igst,0 stock,id.totalamtinfc,rateinfc
from [db_sop].[dtl_sale] id
join [db_sop].[hdr_saleorder] od on id.oaid = od.oaid 
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
where id.invid=@invid

END



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

CREATE PROCEDURE [db_sop].[pr_GetGSTR1_Data]
	@coid int,
	@boid int,
	@fyid int = null,
	@fromDate date,
	@toDate	Date
AS
BEGIN
	SET NOCOUNT ON;

	select [invprefix],[invpostfix],[invno],[invdate], [billtocustomergstno], [billtocustomername],[netamt], [basicamt], [igstamt], [cgstamt], 'Company State' companystate, iif([igstamt]>0,'Inter State','Intra-State') as supplytype, 'Regular' invoicetype, 
		   0 as isreversecharge, null applicabletaxrate
	from  [db_sop].[hdr_sale] as SH,  db_sop.mst_ordertype BS
	Where invno>0
	And   SH.invoicetype=BS.id
	And   Upper(ordertype)!='EXPORT'  
	And   [invdate]>=@fromDate 
	And   [invdate]<=@toDate
	And   SH.coid=@coid 
	And	  SH.boid=@boid
	And  len(isnull([billtocustomergstno],''))>=15 ;

	select [invprefix],[invpostfix],[invno],[invdate], [billtocustomergstno], [billtocustomername],[netamt], [basicamt], [igstamt], [cgstamt], 'Company State' companystate, iif([igstamt]>0,'Inter State','Intra-State') as supplytype, 'Regular' invoicetype, 
		   0 as isreversecharge, null applicabletaxrate
	from  [db_sop].[hdr_sale] as SH,  db_sop.mst_ordertype BS
	Where invno>0
	And   SH.invoicetype=BS.id
	And   Upper(ordertype)!='EXPORT'  
	And   [invdate]>=@fromDate 
	And   [invdate]<=@toDate
	And   SH.coid=@coid 
	And	  SH.boid=@boid
	And  len(isnull([billtocustomergstno],''))<15
	And  [netamt]>=250000 ;
	
	select [invprefix],[invpostfix],[invno],[invdate], [billtocustomergstno], [billtocustomername],[netamt], [basicamt], [igstamt], [cgstamt], 'Company State' companystate, iif([igstamt]>0,'Inter State','Intra-State') as supplytype, 'Regular' invoicetype, 
		   0 as isreversecharge, null applicabletaxrate
	from  [db_sop].[hdr_sale] as SH,  db_sop.mst_ordertype BS
	Where invno>0
	And   SH.invoicetype=BS.id
	And   Upper(ordertype)!='EXPORT'  
	And   [invdate]>=@fromDate 
	And   [invdate]<=@toDate
	And   SH.coid=@coid 
	And	  SH.boid=@boid
	And  len(isnull([billtocustomergstno],''))<15
	And  [netamt]<250000 ;

	select [invprefix],[invpostfix],[invno],[invdate], [billtocustomergstno], [billtocustomername],[netamt], [basicamt], [igstamt], [cgstamt], 'Company State' companystate, iif([igstamt]>0,'Inter State','Intra-State') as supplytype, 'Export' invoicetype, 
		   0 as isreversecharge, null applicabletaxrate
	from  [db_sop].[hdr_sale] as SH,  db_sop.mst_ordertype BS
	Where invno>0
	And   SH.invoicetype=BS.id
	And   Upper(ordertype)='EXPORT'  
	And   [invdate]>=@fromDate 
	And   [invdate]<=@toDate
	And   SH.coid=@coid 
	And	  SH.boid=@boid ;

	select im.hsncode,'' hsndesc, u.[uom],sum(sd.qtytodispatch) totalqty, Sum(sd.[totalamt]) totalamt, sum(sd.[basicamount]) totaltaxable, 
	   Sum(sd.[igstamt]) igstamt,sum(sd.[cgstamt]) cgstamt,sum(sd.[sgstamt]) sgstamt, sum(sd.[cessamt]) cessamt
	from [db_sop].[dtl_sale] Sd 
		join [db_sop].[hdr_sale] sh  on sd.invid= sh.id
		join [db_mm].[mst_item] im  on sd.itemid= im.id
		left join [db_mm].[mst_itemuom] u  on im.issuingunitid = u.id
		left join [db_mm].[mst_gst] g on sd.gstid=g.gstid
	Where invno>0
	And   [invdate]>=@fromDate 
	And   [invdate]<=@toDate
	And   SH.coid=@coid 
	And	  SH.boid=@boid 
	Group by im.hsncode, u.[uom]
end;
GO
/****** Object:  StoredProcedure [db_sop].[pr_getinvoicedata]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		<Author,Amit>
-- Create date: <Create Date,03-12-2018>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_getinvoicedata] 1,1,5
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getinvoicedata] 
	@coid int,
	@boid int,
	@invid int

AS
BEGIN
	SET NOCOUNT ON;
	declare @orderid bigint =(select top 1 oaid from db_sop.dtl_sale where invid=@invid)
	declare @fyid bigint =(select fyid from db_sop.hdr_sale where id=@invid)
	
	Select 	ih.[oaids],[pino],[pidate],[confirmed],ih.[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],
	ih.[cancelledon],ih.[cancelledbyuserid],[invprefix],[invpostfix],ih.[customerid],ih.[customername],ih.[customeraddr1],ih.[customeraddr2],ih.[city],ih.[state],
	ih.[pin],ih.[customergstno],ih.[billtocustomerid],ih.[billtocustomername],ih.[billtocustomeraddr1],ih.[billtocustomeraddr2],ih.[billtocity],ih.[billtostate],
	ih.[billtopin],ih.[billtocustomergstno],ih.[consigneecustomerid],ih.[consigneecustomername],ih.[consigneecustomeraddr1],ih.[consigneecustomeraddr2],
	ih.[consigneecity],ih.[consigneestate],ih.[consigneepin],ih.[consigneecustomergstno],ih.[custPoNo],ih.[custPodate],ih.[basicamt],ih.[discamt],ih.[netamt],ih.[igstamt],
	ih.[cgstamt],ih.[sgstamt],[invamt],ih.[userid],ih.[approvedbymarketingheaduserid],ih.[approvedbycommercialuserid],[approvedbyaccountsuserid],ih.[remarks],
	ih.[coid],ih.[boid],ih.[fyid],ih.[createdby],ih.[createdon],ih.[modifiedby],ih.[modifiedon],
	 ih.consigneecustomerid,ih. billtocustomerid,(select id from db_sop.mst_ordertype where id=ih.invoicetype) ordertype,
	 currency,invcertification,conversionrate
from [db_sop].[hdr_sale] ih
where ih.id = @invid

	 select im.[itemcode],im.[oldcode],im.[itemname],id.[itemid],id.oaid,od.oano, od.custpono, id.[billingdescription],id.[isfoc],id.[issample],id.[specialcode],id.[packing],u.[uom],
	 id.[gstid],id.[igstrate],id.[sgstrate],id.[cgstrate],id.[cessrate],id.[basicamount],id.[rate],id.[netrate],id.[orderedquantity],id.[itemdiscpercent],
	 id.[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],id.[totalamt],id.[remarks]
	 ,id.qtyalreadydispatched, id.qtytodispatch,id.focqty,[batch],im.hsncode,g.igst,0 stock,id.totalamtinfc,rateinfc
	 from [db_sop].[dtl_sale] id
	left join [db_sop].[hdr_saleorder] od on id.oaid = od.oaid 
	 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
	   where id.invid=@invid
	  

	select id,invid,oaid,itemid,packing,qty,focqty,batch,mfgdate,expdate 
	from [db_sop].[dtl_sale_batches] where invid = @invid

		  select termsandconditionsid id,termsandconditionsid,t1.termsandcondition from [db_sop].[order_termsandconditions] t1 
	  where t1.orderid =@orderid
	  
	  --select id, [paymenttermid], [paymentterm], [percent], [amount] from  [db_sop].[order_paymentterms] t2 
	  --where t2.orderid =@orderid
	  select id,invid, srno, paymentterm, [percent], amount from [db_sop].[dtl_sale_paymentterms] 	where invid=@invid

	  select d.itemid, im.itemcode,im.itemname, d.[qtytobedispatch], d.deliverydate as date, row_number() over(order by d.id asc) as id, u.uom as uom
	  from [db_sop].[order_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 t2.[id],[documentinfo]  from [db_sop].[order_documentsreqd] t2 
	  where t2.orderid =@orderid


    select t1.[accesorieid],[t1].[itemid] from [db_sop].[mst_accessories] t1 
	  left join [db_sop].[order_itemaccessories] t2 on t1.accesorieid = t2.accessorieid
	  where t2.orderid =@orderid

	-- get packinginstructions 
	  select srno,instruction,instructionid from db_sop.order_packinginstructions where orderid =@orderid

	  -- get installation info 
	  select srno,installationinfo,installationid from db_sop.order_installationinfo where orderid =@orderid
	  -- get batchwise dtl
	select  [invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate] from [db_sop].[dtl_sale_batches]
	where invid=@invid
	--get ordertype master

	--select * from db_sop.mst_ordertype where fyid=@fyid
	select * from db_sop.mst_ordertype 

	--get ordertype master
	
	select d.id,invid,levyname, d.levyid, quantity, rate, uom, uomid, amount, d.hsncode, d.gstid, 
	igstamt, cgstamt, sgstamt, igstrate igst, cgstrate cgst, sgstrate sgst from [db_sop].[dtl_sale_levies] d
	  join db_masters.levies l on d.levyid=l.id
		where invid=@invid


		select id,invid, lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, 
		lcbankname, lcbankbranch, lcareacode, lctinno, lcvatno from [db_sop].[dtl_sale_lc] 	where invid=@invid

		select id,invid, precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, 
		portofdischarge, postcarriageby, placeofreceiptbypostcarriage, finaldestination from [db_sop].dtl_sale_exportcarriage 	where invid=@invid
	
		
	select  id, code , name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
	
		select id ,uom from [db_mm].[mst_itemuom]
		select * from [db_sop].dtl_sale_packinglist where invid=@invid
	select *	FROM    db_sop.dtl_sale_transportation where invid=@invid
	end
	---- suplid check yet to be done.
	------- whether to use left join on brand or make it mandatory in ui.


GO
/****** Object:  StoredProcedure [db_sop].[pr_getinvoicelist]    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_sop].[pr_getinvoicelist]  1,100,1,1,'PINO','asc','p','agri','customername'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getinvoicelist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='pino',
	@sortorder nvarchar(100)='desc',
	@type char(1)='P',
	@search varchar(50)='',
	@searchtype varchar(25) = ''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql = 'Select h.[id],[oaids],h.[pino],[pidate], h.invno, h.invdate,h.[createdby],u.username,[customername],ordertype invoicetype,case when  exists(select invid from db_mm.hdr_nrgp where invid=h.id) then  1   else   0 end  nrgpgenerated,h.invamt
	 from [db_sop].[hdr_sale] h
	join [db_masters].[users] u on h.createdby = u.userid 
	join [db_sop].[mst_ordertype]  t on h.invoicetype=t.id'
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@type='I')
		begin
		 set @sql += ' and h.invno>0' 
		end
		else
		begin
		 set @sql += ' and (h.invno=0 or h.invno is null)' 
		end 
		if (@searchtype = 'pino' and @search!='') 
	begin
		set @sql += ' and h.pino = ' + @search
	end
	else if (@searchtype = 'customername' and @search!='')
	begin
		set @sql += ' and  h.customername like ''%' + cast(@search as varchar(50)) + '%'''
		 set @sql +=' order by PATINDEX (''%' + + cast(@search as varchar(50)) + '%'',customername)asc, LEN(customername)' + @sortorder + ' '
	end
	else
	begin
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		end
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL

	set @sql = 'select count(h.[id])records from [db_sop].[hdr_sale] h	join [db_masters].[users] u on h.createdby = u.userid '
	set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@type='I')
		begin
		 set @sql += ' and h.invno>0' 
		end
		else
		begin
		 set @sql += ' and (h.invno=0 or h.invno is null)' 
		end 
		if (@searchtype = 'pino' and @search!='') 
	begin
		set @sql += ' and h.pino = ' + @search
	end
	else if (@searchtype = 'customername' and @search!='')
	begin
		set @sql += ' and  h.customername like ''%' + cast(@search as varchar(50)) + '%'''
	end
		EXEC sp_executesql @SQL
	
	
	
END



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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_getlastoano] 1,1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getlastoano] 
 @coid int,
 @boid int,
 @fyid int,
 @accesstoken varchar(50)=null
AS
BEGIN
	select (isnull(max(oano),0)) oano  from [db_sop].[hdr_saleorder] where coid=@coid and boid=@boid and fyid= @fyid	
	
	select (isnull(max(pino),0)) oano  from [db_sop].[hdr_sale] where coid=@coid and boid=@boid and fyid= @fyid	
	
	END



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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_getlastpino] 1,1,1
-- =============================================


CREATE PROCEDURE [db_sop].[pr_getlastpino] 
 @coid int,
 @boid int,
 @fyid int,
 @accesstoken varchar(50)=null
AS
BEGIN
	
	select (isnull(max(pino),0)) pino  from [db_sop].[hdr_sale] where coid=@coid and boid=@boid and fyid= @fyid	


	---get ordertype master
	select id,ordertype from db_sop.mst_ordertype where isactive =1  and fyid=@fyid and coid= @coid and boid=@boid
	
	---get Currency master
	select  id, code , name, case when ltrim(code)='INR' then 0 else 1 end fc  from  db_masters.Currency
	END



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

-- =============================================
-- Author:		<Author,Ravinder Pal>
-- Create date: <Create Date,10-01-2020>
-- Description:	<Description,Get Drcr Note Data>
-- [db_sop].[pr_getnotelist]  1,100,1,1,'PINO','asc','p','agri','customername'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getnotelist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='noteno',
	@sortorder nvarchar(100)='desc',
	@type char(1)='P',
	@search varchar(50)='',
	@searchtype varchar(25) = ''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	set @sql = 'Select h.id, h.noteno, h.notedate,  h.partyid, h.name,h.[address],  h.city,h.state, h.country, h.gstin, h.[drcr], h.[reasonid], h.invid, h.[taxableamt], h.[igstamt],
					h.[sgstamt], h.[cgstamt], h.[totalamt], iif(h.drcr=''C'',''Credit Note'',''Debit Note'') type, s.invno
				From   [db_sop].[hdr_drcrnote] h
				join  db_sop.hdr_sale s on s.id=invid '
		set @sql += ' where h.coid = ' + cast(@coid as varchar(5)) + ' and h.boid = ' + cast(@boid as varchar(5))
		if(@type='D')
		begin
		 set @sql += ' and h.drcr=''D'''
		end
		else if(@type='C')
		begin
		 set @sql += ' and h.drcr=''C'''
		end

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

	set @sql = 'select count([id])records from  [db_sop].[hdr_drcrnote] '
	set @sql += ' where coid = ' + cast(@coid as varchar(5)) + ' and boid = ' + cast(@boid as varchar(5))
		if(@type='D')
		begin
		 set @sql += ' and drcr=''D'''
		end
		else if(@type='C')
		begin
		 set @sql += ' and drcr=''C'''
		end
	if (@searchtype = 'noteno' and @search!='') 
	begin
		set @sql += ' and noteno = ' + @search
	end
	else if (@searchtype = 'customername' and @search!='')
	begin
		set @sql += ' and  name like ''%' + cast(@search as varchar(50)) + '%'''
	end
		EXEC sp_executesql @SQL
	
	
	
END



GO
/****** Object:  StoredProcedure [db_sop].[pr_getordertypecustomers]    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_sop].[pr_getordertypecustomers] 1,1,'1'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getordertypecustomers] 
	@coid int = 1,
	@boid int = 1,
	@type varchar(50)
AS
BEGIN
	SET NOCOUNT ON;
	
	select distinct customerid,customername,customeraddr1,customeraddr2,city,state,pin,customergstno ,hdr.currency
	from db_sop.hdr_saleorder hdr
	join  db_sop.mst_ordertype ot on hdr.ordertype=ot.id
	 where ot.id=@type and oaid not in (select top 1 oaid from db_sop.dtl_sale)

	 

	select m.id,levyname , m.hsncode,description,igst,cgst,sgst,m.gstid from db_masters.levies m 
	join  [db_sop].[mst_sale_levies] d on m.id=d.leviesid
	join  [db_mm].[mst_gst] g on m.gstid=g.gstid
	where ordertypeid=@type 

	select id ,uom from [db_mm].[mst_itemuom]


	
END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,25-02-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_getordertermsandconditions]1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getpaymentterms] 
@coid int,
@boid INT
AS
BEGIN

	SET NOCOUNT ON;
	
SELECT        id, name as paymentterm
FROM            db_sop.mst_paymentterms x where coid= @coid and boid=@boid  order by srno

END


GO
/****** Object:  StoredProcedure [db_sop].[pr_getpendingorders]    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:	<to fetch pending oa numbers for MRP>
--[db_sop].[pr_getpendingorders] 1,1,2
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getpendingorders] 
@coid int,
@boid int,
@fyid int,
@itemid varchar(200) = null,
@userid	int = null,
@accesstoken varchar(300)=null

AS
BEGIN
	SET NOCOUNT ON;
	IF OBJECT_ID('tempdb..#tempcustomerorders') IS NOT NULL DROP TABLE #tempcustomerorders
	create table #tempcustomerorders 
	(
		oaid			bigint,
		oano			varchar(20),
		oadate			date,
		customerid		bigint,
		customername	varchar(300),
		customeraddress	varchar(max),
		bomid			bigint,
		itemid			bigint,
		uom				varchar(10),
		itemcode		varchar(20),
		oldcode			varchar(20),
		itemname		varchar(200),
		orderqty		decimal(15,3),
		pendingqty		decimal(15,3)
	)

	-- insert data for pending order items from db_sop.dtl_saleorder
	-- as per sukhbir orderedquantity = order quantity + focqty 
	insert into #tempcustomerorders (oaid, itemid, uom, orderqty,pendingqty) 
	select oaid, itemid, uom, orderedquantity, isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0) pendingqty 
	from db_sop.dtl_saleorder where coid = @coid and boid=@boid and fyid = @fyid and itemid = coalesce(@itemid,itemid)
	and isnull(orderedquantity,0)-isnull(qtyalreadydispatched,0) >0 order by oaid desc
	--update data from item master
	update #tempcustomerorders set itemcode=a.itemcode,oldcode=a.oldcode,itemname=a.itemname
	from db_mm.mst_item a where #tempcustomerorders.itemid = a.id

	-- update oano from hdr_saleorder
	update #tempcustomerorders set oano = a.oano, oadate= a.oadate, customername = a.customername, customeraddress = a.customeraddr1 + ' ' + a.customeraddr2 + ' ' + a.city,
	customerid = a.customerid from db_sop.hdr_saleorder a where #tempcustomerorders.oaid = a.oaid 

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

select distinct oaid,oano,oadate, customerid, customername,customeraddress  from #tempcustomerorders order by oano desc

select * from #tempcustomerorders order by oaid,itemid


END









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

-- =============================================
-- Author:		<Author,,Manoj>
-- Create date: <Create Date,23-10-2018>
-- Description:	<Description,Get list of all user groups>
--[db_sop].[pr_getpendingordersPI] 1,1,5,'1'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getpendingordersPI] 
    @coid int,
	@boid int,
	@customerid int,
	@ordertype int
AS

	SET NOCOUNT ON;

	select distinct h.[oaid],oano orderno, 'No: ' + cast([oano] as varchar(10)) + ' Dt:' + cast([oadate] as varchar(10)) oano, h.[custPoNo],
	 h.custPodate, h.billtocustomerid, h.consigneecustomerid, sum(isnull(d.orderedquantity,0)) ordqty, sum(isnull(d.qtyalreadydispatched,0)) qtydispatched, 
	   (sum(isnull(d.orderedquantity,0))-sum(isnull(d.qtyalreadydispatched,0))) balqty
	from [db_sop].[hdr_saleorder] h
	join  [db_sop].[dtl_saleorder] d on h.oaid= d.oaid
    where h.customerid = @customerid  and h.ordertype=@ordertype
	group by
	h.[oaid],oano ,oadate,h.[custPoNo], h.custPodate, h.billtocustomerid, h.consigneecustomerid
	having  (sum(d.orderedquantity)-sum(isnull(d.qtyalreadydispatched,0))) > 0
	


GO
/****** Object:  StoredProcedure [db_sop].[pr_getsaleworkorderdata]    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,24-12-2019>
-- Description:	<Description,Get Sale Work Order data>
--[db_sop].[pr_getsaleworkorderdata] 1,1,7,'p'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getsaleworkorderdata]
	@coid int,
	@boid int,
	@swoid int

AS
BEGIN
	SET NOCOUNT ON;

	SELECT * from [db_sop].[hdr_sale_work_order] ih
	 where ih.swoid = @swoid and ih.coid= @coid and ih.boid = @boid

	 SELECT * from db_sop.dtl_sale_work_order dt
	 where dt.swoid = @swoid

	 END
	  




GO
/****** Object:  StoredProcedure [db_sop].[pr_getsaleworkorderlist]    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,24-12-2019>
-- Description:	<Description,Get Sale Work order list data>
--[db_sop].[pr_getsaleworkorderlist]  1,50,1,1,'oano','asc','INDUSTRIES','M','customername'
-- =============================================
CREATE PROCEDURE [db_sop].[pr_getsaleworkorderlist] 
	@PageNumber INT,
	@PageSize INT,
	@coid int = 1,
	@boid int = 1,
	@sort nvarchar(100)='h.oaid',
	@sortorder nvarchar(100)='desc',
	@search varchar(50)=''
AS
BEGIN
	SET NOCOUNT ON;
	declare @sql nvarchar(max);
	
	set @sql = 'select * from db_sop.hdr_sale_work_order h
				left join [db_sop].[hdr_saleorder] so on h.oaid= so.oaid'

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

		if(@search!='')
		begin
		 set @sql += ' and h.itemname like '+'''%'+ cast(@search as varchar(5)) + '%''' 
		end
		 begin 
		set @sql +=' order by ' + cast(@sort as varchar(100)) + ' ' + @sortorder + ' '
		end
		if(isnull(@PageNumber,0)>0)
	begin
	set @sql +=' OFFSET ' + cast(@PageSize * (@PageNumber - 1)   as varchar(4))  + ' ROWS
    FETCH NEXT ' + cast(@PageSize   as varchar(4)) + ' ROWS ONLY OPTION (RECOMPILE)'
	end
	print @sql
	EXEC sp_executesql @SQL
	 select count(hdr.swoid) records from db_sop.hdr_sale_work_order hdr
	 where isnull(hdr.coid,1) = @coid and isnull(hdr.boid,1) = @boid

	
END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,25-02-2019>
-- Description:	<Description,Get supplier data>
--[db_mm].[pr_gettermsandconditions]1,1,188
-- =============================================
CREATE PROCEDURE [db_sop].[pr_gettermsandconditions] 
@coid int,
@boid INT
AS
BEGIN
DECLARE @orderid int
	SET NOCOUNT ON;
	
SELECT        id, name as termsandcondition
FROM            db_sop.mst_termsandconditions x where coid= @coid and boid=@boid  order by srno

END


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


-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-25-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_printcustomerinvoice]  1,1,18
-- =============================================
CREATE PROCEDURE [db_sop].[pr_printcustomerinvoice] 
	@coid int,
	@boid int,
	@id int,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;

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

	

	-- invoice and customer information
	Select  s.id,  pino, pidate, confirmed, confirmedbyuserid, confirmedon, invno, invdate, revisedbyuserid, revisedon, cancelledon, cancelledbyuserid, invprefix, invpostfix, customerid, customername, 
                         customeraddr1, customeraddr2, city, state, pin, customergstno, billtocustomerid, billtocustomername, billtocustomeraddr1, billtocustomeraddr2, billtocity, billtostate, billtopin, billtocustomergstno, 
                         consigneecustomerid, consigneecustomername, consigneecustomeraddr1, consigneecustomeraddr2, consigneecity, consigneestate, consigneepin, consigneecustomergstno, custPoNo, custPodate, basicamt, 
                         discamt, netamt, igstamt, cgstamt, sgstamt, invamt, userid, approvedbymarketingheaduserid, approvedbycommercialuserid, approvedbyaccountsuserid, remarks, s.coid, s.boid, s.fyid, s.createdby, s.createdon, 
                         s.modifiedby, s.modifiedon, invoicetype, customer_gstno, customer_phonenumber, customer_taxnumber, roundoff, concessionaltax, advancereceived, 
						 billseriesid,invoicetype type,sm.statecode,sm1.statecode consigneestatecode,currency,symbol,invcertification
 FROM            db_sop.hdr_sale s 
join db_masters.statemaster sm on s.state=sm.statename
join db_masters.statemaster sm1 on s.consigneestate=sm1.statename
left join db_masters.currency c on s.currency=c.code
	where s.id =@id
	--declare @oaid bigint =(select oaid FROM            db_sop.hdr_sale
	--where id = @id )
	
	-- invoice details
	select [itemcode],im.[itemname],id.[itemid],id.[billingdescription],[isfoc],sh.custPoNo,[issample],id.[specialcode],id.[packing],
	u.[uom], id.[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],
	[itemdiscpercent],[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],[totalamt],id.[remarks],
	id.qtyalreadydispatched, sb.qty qtytodispatch,id.focqty,im.hsncode ,0 [weight],sb.batch, sb.mfgdate batchmfgdate, sb.expdate batchexpirydate
	from  [db_sop].[hdr_sale] sh
	join [db_sop].[dtl_sale] id on sh.id =id.invid
	join [db_sop].[dtl_sale_batches] sb on sh.id =sb.invid and id.itemid=sb.itemid
	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
	 
	where id.invid= @id 
	
	-- tax summary
	Select 'IGST ' + cast(left(igstrate,6) as varchar(3)) + ' %' description,sum(netamt) amount, sum(igstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id 
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' + cast(left(sgstrate,6) as varchar(3))  + ' %' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id  	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' + cast(left(cgstrate,6) as varchar(3))  + ' %' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id 	group by cgstrate having sum(isnull(cgstamt,0))>0
	
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
create table #temp
(
id int ,
description VARCHAR(300),
amount  decimal(13,2)
);
insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, sum(netamt) amount from [db_sop].[dtl_sale] id where id.invid= @id 
	union 
	select 2 id, 'Discount Amount' description, isnull(discamt,0) amount from [db_sop].[hdr_sale] where id= @id 
	union
	Select 3 id, 'IGST ' + cast(left(igstrate,6) as varchar(3)) + ' %' description,sum(igstamt) amount from [db_sop].[dtl_sale] 
	where invid= @id 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 4 id, 'SGST ' + cast(left(sgstrate,6) as varchar(3))  + ' %' description,sum(sgstamt) amount from [db_sop].[dtl_sale] 
	where invid= @id  	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 5 id, 'CGST ' + cast(left(cgstrate,6) as varchar(3))  + ' %' description,sum(cgstamt) amount from [db_sop].[dtl_sale] 
	where invid= @id  	group by cgstrate having sum(isnull(cgstamt,0))>0
	
	union 
	select 6 id, 'Round Off' description, isnull(roundoff,0) amount from [db_sop].[hdr_sale] where id =@id
	union 
	select 7 id, 'GRAND TOTAL' description, isnull(invamt,0) amount from [db_sop].[hdr_sale] where id= @id 
	)
	
	select * from #temp order by id

	-- convert inv-Amt to words
	SELECT db_general.NumberToWords(isnull(invamt,0),currency) NumberToWords from db_sop.hdr_sale WHERE id= @id 
	
	-- terms & condition information
	
	--select  termsandcondition from [db_sop].[order_termsandconditions] where orderid=@oaid
	select  termsandcondition from [db_sop].[order_termsandconditions] where orderid in (select top(1) oaid FROM            db_sop.dtl_sale
	where id = @id )
	-- get sale batch wise item detail (13-05-19 mohit)
 select * from [db_sop].[dtl_sale_batches] where invid=@id
END




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


-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-25-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_printcustomerinvoiceexport]  1,1,18
-- =============================================
CREATE PROCEDURE [db_sop].[pr_printcustomerinvoiceexport] 
	@coid int,
	@boid int,
	@id bigint,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;

	-- header data -- company information
	select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	b.country,b.phone_number,b.email,b.pan, b.tan ,insurance_info,b.gstno,iec,c.cin,b.fax
	from   db_general.company_branches b
	join  db_masters.company c on  b.coid = c.coid
	where b.coid = @coid and b.boid = @boid

	

	-- invoice and customer information
	Select  s.id,  pino, pidate, confirmed, confirmedbyuserid, confirmedon, invno, invdate, revisedbyuserid, revisedon, cancelledon, cancelledbyuserid, invprefix, invpostfix, customerid, customername, 
                         customeraddr1, customeraddr2, city, state, pin, customergstno, billtocustomerid, billtocustomername, billtocustomeraddr1, billtocustomeraddr2, billtocity, billtostate, billtopin, billtocustomergstno, 
                         consigneecustomerid, consigneecustomername, consigneecustomeraddr1, consigneecustomeraddr2, consigneecity, consigneestate, consigneepin, consigneecustomergstno, custPoNo, custPodate, basicamt, 
                         discamt, netamt, igstamt, cgstamt, sgstamt, invamt, userid, approvedbymarketingheaduserid, approvedbycommercialuserid, approvedbyaccountsuserid, remarks, s.coid, s.boid, s.fyid, s.createdby, s.createdon, 
                         s.modifiedby, s.modifiedon, invoicetype, customer_gstno, customer_phonenumber, customer_taxnumber, roundoff, concessionaltax, advancereceived, 
						 billseriesid,invoicetype type,sm.statecode,sm1.statecode consigneestatecode,currency,symbol,invcertification
 FROM            db_sop.hdr_sale s 
join db_masters.statemaster sm on s.state=sm.statename
join db_masters.statemaster sm1 on s.consigneestate=sm1.statename
left join db_masters.currency c on s.currency=c.code
	where s.id =@id
	
	select [itemcode],im.[itemname],id.[itemid],id.[billingdescription],[isfoc],sh.custPoNo,[issample],id.[specialcode],id.[packing],
	u.[uom], id.[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],
	[itemdiscpercent],[itemdiscamt],id.[netamt],id.[igstamt],id.[cgstamt],id.[sgstamt],id.[cessamt],[totalamt],id.[remarks],
	id.qtyalreadydispatched, sb.qty qtytodispatch,id.focqty,im.hsncode ,0 [weight],sb.batch, sb.mfgdate batchmfgdate, sb.expdate batchexpirydate,rateinfc,id.totalamtinfc
	from  [db_sop].[hdr_sale] sh
	join [db_sop].[dtl_sale] id on sh.id =id.invid
	left join [db_sop].[dtl_sale_batches] sb on sh.id =sb.invid and id.itemid=sb.itemid
	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
	 
	where id.invid= @id 
	
	-- tax summary
	Select 'IGST ' + cast(left(igstrate,6) as varchar(3)) + ' %' description,sum(netamt) amount, sum(igstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id 
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' + cast(left(sgstrate,6) as varchar(3))  + ' %' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id  	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' + cast(left(cgstrate,6) as varchar(3))  + ' %' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid= @id 	group by cgstrate having sum(isnull(cgstamt,0))>0
	
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
create table #temp
(
id int ,
description VARCHAR(300),
amount  decimal(13,2)
);
insert into #temp (id,description,amount)(
	
	--select 1 id, 'Discount Amount' description, isnull(discamt,0) amount from [db_sop].[hdr_sale] where id= @id 	
	--union 
	select 2 id, 'Round Off' description, isnull(roundoff,0) amount from [db_sop].[hdr_sale] where id =@id
	union 
	select 3 id, 'Total Amount' description, isnull(netamt,0) amount from [db_sop].[hdr_sale] where id= @id 
	)
	select * from #temp where amount<>0 order by id 

	-- convert inv-Amt to words
	SELECT db_general.NumberToWords(isnull(invamt,0),currency) NumberToWords from db_sop.hdr_sale WHERE id= @id 
	
	-- terms & condition information	
	select  termsandcondition from [db_sop].[order_termsandconditions] where orderid in (select top(1) oaid 
	FROM            db_sop.dtl_sale	where id = @id )

	-- get sale batch wise item detail (13-05-19 mohit)
 select * from [db_sop].[dtl_sale_batches] where invid=@id


 select invid, precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, portofdischarge, postcarriageby, placeofreceiptbypostcarriage, finaldestination from db_sop.dtl_sale_exportcarriage where invid =@id
select invid, lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, lcbankname, lcbankbranch, lcareacode, lctinno, lcvatno from	[db_sop].[dtl_sale_lc] where invid =@id
select invid, srno, paymentterm, [percent], amount from [db_sop].[dtl_sale_paymentterms] where invid =@id
select * from [db_sop].[dtl_sale_transport] where invid =@id
select invid, levyname, quantity, rate, uom, uomid, amount, l.hsncode, ml.gstid, igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate
 from [db_sop].[dtl_sale_levies] l join
  db_masters.levies ml on l.levyid=ml.id
  where invid =@id
select * from  [db_masters].[gst_lut]
select * from [db_sop].dtl_sale_packinglist
END




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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-25-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_printcustomerorder]  1,1,41
-- =============================================
CREATE PROCEDURE [db_sop].[pr_printcustomerorder] 
	@coid int,
	@boid int,
	@oaid int,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;

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

	-- invoice and customer information
	Select oaid, oano, oadate, customerid,isnull(c.title,'')+' '+ltrim(customername) customername, customeraddr1, customeraddr2, ih.city, ih.state, (isnull(c.pin,'')+' '+isnull(c.mobile_number,'')) , customergstno, customercontactpersonname, customercontactpersonphone, 
                         customercontactpersondesignation, customercontactpersondepartment, billtocustomerid, isnull(cb.title,'')+' '+ltrim(billtocustomername) billtocustomername, billtocustomeraddr1, billtocustomeraddr2, billtocity, billtostate, (isnull(cb.pin,'')+' '+isnull(cb.mobile_number,''))  billtopin, billtocustomergstno, 
                         consigneecustomerid, isnull(cc.title,'')+' '+ltrim(consigneecustomername) consigneecustomername, consigneecustomeraddr1, consigneecustomeraddr2, consigneecity, consigneestate,(isnull(cc.pin,'')+' '+isnull(cc.mobile_number,'')) consigneepin, consigneecustomergstno, custPoNo, custPodate, ourquoteno, 
                         ourquotedate, basicamt, discamt, netamt, igstamt, cgstamt, sgstamt, orderamt, cessamt, userid, orderstatus, confirmedbyuserid, approvedbymarketingheaduserid, approvedbycommercialuserid, 
                         approvedbyrandduserid, approvedbyproductionuserid, approvedbyceouserid, amendmentno, amendmentdate, cancelledon, cancelledbyuserid, remarks, ih.coid, ih.boid, fyid, ih.createdby, ih.createdon, ih.modifiedby, 
                         ih.modifiedon, ordertype, marketexecutive, concessionaltax, advancereceived, packinginstructions, installationinfo
	from [db_sop].[hdr_saleorder] ih join db_masters.customer c on ih.customerid=c.id
join db_masters.customer cb on ih.billtocustomerid=cb.id
join db_masters.customer cc on ih.consigneecustomerid=cc.id
	where ih.oaid = @oaid

	
	-- invoice details
	select [itemcode],case when len(oldcode)>1 then  (im.[itemname] +' '+isnull(oldcode,'')) else  (im.[itemname] +' '+isnull(itemcode,'')) end itemname,[itemid],id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],
	u.[uom], id.[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],
	[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],id.[remarks],
	id.qtyalreadydispatched, id.qtytodispatch,id.focqty,im.hsncode ,0 [weight]
	from [db_sop].[dtl_saleorder] 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
	where id.oaid= @oaid 
	
	-- tax summary
	Select 'IGST ' + cast(left(igstrate,6) as varchar(2)) + ' %' description,sum(netamt) amount, sum(igstamt) taxamount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' + cast(left(sgstrate,6) as varchar(2))  + ' %' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' + cast(left(cgstrate,6) as varchar(2))  + ' %' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	group by cgstrate having sum(isnull(cgstamt,0))>0
	
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
create table #temp
(
id int ,
description VARCHAR(300),
amount  decimal(13,2)
);
insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, sum(netamt) amount from [db_sop].[dtl_saleorder] id where id.oaid= @oaid 
	union
	Select 2 id, 'IGST ' + cast(left(igstrate,6) as varchar(2)) + ' %' description,sum(igstamt) amount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 3 id, 'SGST ' + cast(left(sgstrate,6) as varchar(2))  + ' %' description,sum(sgstamt) amount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 4 id, 'CGST ' + cast(left(cgstrate,6) as varchar(2))  + ' %' description,sum(cgstamt) amount from [db_sop].[dtl_saleorder] 
	where oaid=@oaid 	group by cgstrate having sum(isnull(cgstamt,0))>0
	union 
	select 5 id, 'Discount Amount' description, isnull(discamt,0) amount from [db_sop].[hdr_saleorder] where oaid =@oaid
	union 
	--select 6 id, 'Round Off' description, isnull(roundoff,0) amount from [db_sop].[hdr_saleorder] where oaid =@oaid
	--union 
	select 7 id, 'GRAND TOTAL' description, isnull(orderamt,0) amount from [db_sop].[hdr_saleorder] where oaid =@oaid
	)
	
	select * from #temp order by id

	SELECT  db_general.NumberToWords(isnull(orderamt,0),currency) NumberToWords from db_sop.hdr_saleorder WHERE oaid = @oaid 

	-- terms & condition information
	select termsandcondition from db_sop.order_termsandconditions WHERE orderid = @oaid 
	-- delivery sechedule information

	select i.itemname,d.remarks,d.deliverydate,d.qtytobedispatch,d.dispatchqty,d.dispatchon 
	from db_sop.order_deliveryschedule d inner join db_mm.mst_item i on i.id= d.itemid  WHERE orderid = @oaid 
-- payment trems information

select paymentterm,[percent],amount from db_sop.order_paymentterms  WHERE orderid = @oaid 
	-- documents information

	select documentinfo from db_sop.order_documentsreqd  WHERE orderid = @oaid 
	-- item accessories information

	select i.itemname,d.accessorieid,d.accessorieqty,d.accesoriebrand 
	from db_sop.order_itemaccessories d inner join 
	db_mm.mst_item i on i.id= d.itemid  WHERE orderid = @oaid 

	SELECT        installationinfo
FROM            db_sop.order_installationinfo  WHERE orderid = @oaid order by srno

SELECT       instruction
FROM            db_sop.order_packinginstructions WHERE orderid = @oaid order by srno
END






GO
/****** Object:  StoredProcedure [db_sop].[pr_printjobworkdata]    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_sop].[pr_printjobworkdata]  1,1,5
-- =============================================
CREATE PROCEDURE [db_sop].[pr_printjobworkdata] 
	@coid int,
	@boid int,
	@invid int,
	@userid int=null,
	@accesstoken varchar(50)=null
AS
BEGIN
	SET NOCOUNT ON;
	
	-- header data -- company information
	select  c.companyname,b.unitname,b.address1 + ' ' + b.address2+' ' + b.city+'-' + b.pin address,b.state,
	b.country,b.phone_number,b.email,b.PAN, b.TAN ,insurance_info
	from db_general.company_branches b
	join db_masters.company c on  b.coid = c.coid
	where b.coid = @coid and b.boid = @boid

	

	-- invoice and customer information
	Select 	[oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],
	[revisedon],	[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],
	[customeraddr1],[customeraddr2],[city],[state],	[pin],[customergstno],[billtocustomerid],[billtocustomername],
	[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],	[billtopin],[billtocustomergstno],
	[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],
	[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],
	[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],
	[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],[coid],[boid],[fyid],[createdby],
	[createdon],[modifiedby],[modifiedon], consigneecustomerid, billtocustomerid,[invoicetype], [customer_gstno],
	[customer_phonenumber] 
	from [db_sop].[hdr_sale] ih
	where ih.id = @invid

	
	-- invoice details
	select [itemcode],im.[itemname],[itemid],id.[billingdescription],[isfoc],[issample],id.[specialcode],id.[packing],
	u.[uom], id.[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[netrate],[orderedquantity],
	[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],id.[remarks],
	id.qtyalreadydispatched, id.qtytodispatch,id.focqty,im.hsncode ,0 [weight]
	from [db_sop].[dtl_sale] 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
	where id.invid= @invid 
	
	-- tax summary
	Select 'IGST ' + cast(left(igstrate,6) as varchar(2)) + ' %' description,sum(netamt) amount, sum(igstamt) taxamount from [db_sop].[dtl_sale] 
	where invid=@invid 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 'SGST ' + cast(left(sgstrate,6) as varchar(2))  + ' %' description,sum(netamt) amount, sum(sgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid=@invid 	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 'CGST ' + cast(left(cgstrate,6) as varchar(2))  + ' %' description,sum(netamt) amount, sum(cgstamt) taxamount from [db_sop].[dtl_sale] 
	where invid=@invid 	group by cgstrate having sum(isnull(cgstamt,0))>0
	
	-- invoice summary
	IF OBJECT_ID('tempdb..#temp') IS NOT NULL DROP TABLE #temp
create table #temp
(
id int ,
description VARCHAR(300),
amount  decimal(13,2)
);
insert into #temp (id,description,amount)(
	select 1 id, 'Taxable Amount' description, sum(netamt) amount from [db_sop].[dtl_sale] id where id.invid= @invid 
	union
	Select 2 id, 'IGST ' + cast(left(igstrate,6) as varchar(2)) + ' %' description,sum(igstamt) amount from [db_sop].[dtl_sale] 
	where invid=@invid 	
	group by igstrate having sum(isnull(igstamt,0))>0
	union
	Select 3 id, 'SGST ' + cast(left(sgstrate,6) as varchar(2))  + ' %' description,sum(sgstamt) amount from [db_sop].[dtl_sale] 
	where invid=@invid 	group by sgstrate having sum(isnull(sgstamt,0))>0
	union
	Select 4 id, 'CGST ' + cast(left(cgstrate,6) as varchar(2))  + ' %' description,sum(cgstamt) amount from [db_sop].[dtl_sale] 
	where invid=@invid 	group by cgstrate having sum(isnull(cgstamt,0))>0
	union 
	select 5 id, 'Discount Amount' description, isnull(discamt,0) amount from [db_sop].[hdr_sale] where id =@invid
	union 
	select 6 id, 'Round Off' description, isnull(roundoff,0) amount from [db_sop].[hdr_sale] where id =@invid
	union 
	select 7 id, 'GRAND TOTAL' description, isnull(invamt,0) amount from [db_sop].[hdr_sale] where id =@invid
	)
	
	select * from #temp order by id
	SELECT db_general.NumberToWords(netamt,currency) NumberToWords from db_sop.hdr_sale WHERE id = @invid 

END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-08-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_report_commanapiforcustomerorder]   1,1,2
-- =============================================
CREATE PROCEDURE [db_sop].[pr_report_commanapiforcustomerorder] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
-----	get distinct customers
  select id,(name +' '+isnull(address1 ,'')+' '+ isnull(address2,' ')) name from db_masters.customer  c    where id in 
  (SELECT  distinct(customerid) FROM     db_sop.hdr_saleorder h where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)

  -----	get distinct businesssegement
   select id,businesssegementname name from db_masters.businesssegement where id in
    (SELECT  distinct(segmentid) FROM  db_sop.hdr_saleorder h join  db_masters.customer  c on h.customerid=c.id where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)

-----	get distinct marketexecutive
    select userid id,firstname name from db_masters.users where userid in
	 (SELECT  distinct(marketexecutive) FROM  db_sop.hdr_saleorder h where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)



				 
END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-08-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_report_commanapiforcustomerorder]   1,1,2
-- =============================================
create PROCEDURE [db_sop].[pr_report_commanapiformarketing] 
	@coid int,
	@boid int,
	@fyid int
AS
BEGIN
	SET NOCOUNT ON;
-----	get distinct customers
  select id,(name +' '+isnull(address1 ,'')+' '+ isnull(address2,' ')) name from db_masters.customer  c    where id in 
  (SELECT  distinct(customerid) FROM     db_sop.hdr_saleorder h where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)

  -----	get distinct businesssegement
   select id,businesssegementname name from db_masters.businesssegement where id in
    (SELECT  distinct(segmentid) FROM  db_sop.hdr_saleorder h join  db_masters.customer  c on h.customerid=c.id where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)

-----	get distinct marketexecutive
    select userid id,firstname name from db_masters.users where userid in
	 (SELECT  distinct(marketexecutive) FROM  db_sop.hdr_saleorder h where h.coid=@coid and h.boid=@boid and h.fyid=@fyid)



				 
END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-25-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_report_customerorderregister]   1,1,1,1,'2019-04-10','2019-08-01',3,1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_report_customerorderregister] 
	@coid int,
	@boid int,
	@userid int,
	@fyid int,
	@fromdate date=null,
	@todate date=null,
	@businesssegement int=null,
	@marketexecutive int=null,
	@custid int=null
AS
BEGIN
	SET NOCOUNT ON
	declare @sql nvarchar(max)

	set @sql='SELECT   oano, format(oadate,''dd-MM-yyyy'') oadate,ourquoteno,format(ourquotedate,''dd-MM-yyyy'') ourquotedate,  (customername +'' ''+isnull(customeraddr1 ,'' '')+'' ''+ 
	isnull(customeraddr2,'' '')+'' ''+ isnull(h.city,'' '')+'' ''+isnull(h.state,'' '')+''-''+ isnull(h.pin,'' '')+'' GSTIN: ''+ isnull(customergstno,'' '')) customername,                   
                   custPoNo,  format(custPodate,''dd-MM-yyyy'') custPodate, netamt,orderstatus,firstname marketexecutive,concessionaltax,businesssegementname,advancereceived
				 
FROM     db_sop.hdr_saleorder h join  db_masters.customer  c on h.customerid=c.id
 join   db_masters.businesssegement b on c.segmentid=b.id
 join   db_masters.users u on h.marketexecutive=u.userid
 where h.coid='+cast(@coid as varchar(2))+' and h.boid='+cast(@boid as varchar(2))+'  and h.fyid='+cast(@fyid as varchar(2))+'  '
 if (@businesssegement>0)
 begin
 set @sql +=' and b.id='+cast(@businesssegement as varchar(5))+''
 end
  if (@marketexecutive>0)
 begin
 set @sql +=' and h.marketexecutive='+cast(@marketexecutive as varchar(5))+''
 end
  if (@custid>0)
 begin
 set @sql +=' and h.customerid='+cast(@custid as varchar(7))+''
 end
  if (@fromdate is not null and @todate is not null)
 begin
 set @sql +=' and  oadate between  '''+cast(@fromdate as nvarchar(10))+'''  and '''+cast(@todate as nvarchar(10)) + ''''
 end
 print @sql
	 EXEC sp_executesql @sql
		
	set @sql='SELECT sum(netamt) netamt,sum(advancereceived) advancereceived
				 
FROM     db_sop.hdr_saleorder h join  db_masters.customer  c on h.customerid=c.id
 join   db_masters.businesssegement b on c.segmentid=b.id
 join   db_masters.users u on h.marketexecutive=u.userid
 where h.coid='+cast(@coid as varchar(2))+' and h.boid='+cast(@boid as varchar(2))+'  and h.fyid='+cast(@fyid as varchar(2))+'  '
 if (@businesssegement>0)
 begin
 set @sql +=' and b.id='+cast(@businesssegement as varchar(5))+''
 end
  if (@marketexecutive>0)
 begin
 set @sql +=' and h.marketexecutive='+cast(@marketexecutive as varchar(5))+''
 end
  if (@custid>0)
 begin
 set @sql +=' and h.customerid='+cast(@custid as varchar(7))+''
 end
  if (@fromdate is not null and @todate is not null)
 begin
 set @sql +=' and  oadate between  '''+cast(@fromdate as nvarchar(10))+'''  and '''+cast(@todate as nvarchar(10)) + ''''
 end
 print @sql
	 EXEC sp_executesql @sql
		
	
END



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

-- =============================================
-- Author:		<Author,mohit>
-- Create date: <Create Date,03-25-2019>
-- Description:	<Description,Get supplier data>
--[db_sop].[pr_report_customersaleregister]   1,1,1,2,'2019-01-01','2019-08-01',0,0,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_report_customersaleregister] 
	@coid int,
	@boid int,
	@userid int,
	@fyid int,
	@fromdate date=null,
	@todate date=null,
	@businesssegement int=null,
	@marketexecutive int=null,
	@custid int=null
AS
BEGIN
	SET NOCOUNT ON
	declare @sql nvarchar(max)

	set @sql='SELECT  invno,format(invdate,''dd-MM-yyyy'') invdate,  (customername +'' ''+isnull(customeraddr1 ,'' '')+'' ''+ 
	isnull(customeraddr2,'' '')+'' ''+ isnull(h.city,'' '')+'' ''+isnull(h.state,'' '')+''-''+ isnull(h.pin,'' '')+'' GSTIN: ''+ isnull(customergstno,'' '')) customername,                   
                   custPoNo,  format(custPodate,''dd-MM-yyyy'') custPodate,basicamt,discamt, netamt,igstamt,cgstamt,sgstamt,invamt,concessionaltax,businesssegementname,advancereceived
				 
 FROM   db_sop.hdr_sale h join  db_masters.customer  c on h.customerid=c.id
 join   db_masters.businesssegement b on c.segmentid=b.id
 
 where invno>0 and h.coid='+cast(@coid as varchar(2))+' and h.boid='+cast(@boid as varchar(2))+'  and h.fyid='+cast(@fyid as varchar(2))+'  '
 if (@businesssegement>0)
 begin
 set @sql +=' and b.id='+cast(@businesssegement as varchar(5))+''
 end
 -- if (@marketexecutive>0)
 --begin
 --set @sql +=' and h.marketexecutive='+cast(@marketexecutive as varchar(5))+''
 --end
  if (@custid>0)
 begin
 set @sql +=' and h.customerid='+cast(@custid as varchar(7))+''
 end
  if (@fromdate is not null and @todate is not null)
 begin
 set @sql +=' and  invdate between  '''+cast(@fromdate as nvarchar(10))+'''  and '''+cast(@todate as nvarchar(10)) + ''''
 end

	 EXEC sp_executesql @sql
		
	
	set @sql='SELECT  sum(basicamt) basicamt,sum(discamt) discamt, sum(netamt) netamt,sum(igstamt) igstamt,sum(cgstamt) cgstamt,sum(sgstamt) gstamt,sum(invamt) invamt
				 
 FROM   db_sop.hdr_sale h join  db_masters.customer  c on h.customerid=c.id
 join   db_masters.businesssegement b on c.segmentid=b.id
 
 where invno>0 and h.coid='+cast(@coid as varchar(2))+' and h.boid='+cast(@boid as varchar(2))+'  and h.fyid='+cast(@fyid as varchar(2))+'  '
 if (@businesssegement>0)
 begin
 set @sql +=' and b.id='+cast(@businesssegement as varchar(5))+''
 end
  if (@custid>0)
 begin
 set @sql +=' and h.customerid='+cast(@custid as varchar(7))+''
 end
  if (@fromdate is not null and @todate is not null)
 begin
 set @sql +=' and  invdate between  '''+cast(@fromdate as nvarchar(10))+'''  and '''+cast(@todate as nvarchar(10)) + ''''
 end
 print  @sql
	 EXEC sp_executesql @sql
END



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

GO
/****** Object:  StoredProcedure [db_sop].[pr_save_saleswork_order]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		a.Author,Amit>
-- Create date: a.Create Date,23-10-2018>
-- Description:	a.Description,Get list of data from master tables >

-- =============================================
CREATE PROCEDURE [db_sop].[pr_save_saleswork_order]
	@coid int,
	@boid int,
	@userid int,
	@statementtype varchar(10),
	@headerdata [db_sop].[hdr_sale_work_order_tvp] READONLY,
	@detaildata [db_sop].[dtl_sale_work_order_tvp] readonly
AS
BEGIN
	SET NOCOUNT ON;

	declare @swoid bigint
	
	IF (@statementtype = 'Insert')
		BEGIN
		insert into  db_sop.hdr_sale_work_order ( swodate, oaid, itemid, itemname, itemcode, remarks, bomid, bomtype, coid, 
		boid, fyid, createdby, createdon)
        select getdate(), oaid, itemid, itemname, itemcode, remarks, bomid, bomtype, coid, 
		boid, fyid, @userid, getdate() from @headerdata
		
		SELECT @swoid = @@identity
	    insert into db_sop.dtl_sale_work_order( swoid, itemid, itemname, itemcode, remarks, bomid, bomtype)
        select   @swoid, itemid, itemname, itemcode, remarks, bomid, bomtype from @detaildata
		END
	Else
		Begin
			
		select @swoid = swoid from @headerdata where swoid >0

		update db_sop.hdr_sale_work_order set 
				swodate = a.swodate,
				oaid = a.oaid,
				itemid = a.itemid,
				itemname = a.itemname,
				itemcode=a.itemcode,
				remarks=a.remarks,
				bomid=a.bomid,
				bomtype=a.bomtype,
				coid=a.coid,
				boid=a.boid,
				fyid=a.fyid,
				createdby=a.createdby,
				createdon=a.createdon,
				modifiedby=@userid,
				modifiedon=getdate()
				FROM @headerdata a
				where db_sop.hdr_sale_work_order.swoid = a.swoid

				DELETE FROM db_sop.dtl_sale_work_order where swoid = @swoid

				insert into db_sop.dtl_sale_work_order( swoid, itemid, itemname, itemcode, remarks, bomid, bomtype)
				select  @swoid, itemid, itemname, itemcode, remarks, bomid, bomtype from @detaildata
				where id > 0

		End
END

GO
/****** Object:  StoredProcedure [db_sop].[pr_savecontractreview]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		a.Author,Amit>
-- Create date: a.Create Date,23-10-2018>
-- Description:	a.Description,Get list of data from master tables >
--[db_general].[pr_getmanagementgroupactivities] 1,1,1,1
-- =============================================
CREATE PROCEDURE [db_sop].[pr_savecontractreview]
	@coid int,
	@boid int,
	@userid int,
	@statementtype varchar(10),
	@contractreview_tvp [db_sop].[contractreview_saleorder_tvp] readonly
AS
BEGIN
	SET NOCOUNT ON;
	declare @oaid bigint , @id bigint;

	select @oaid = oaid, @id=id from @contractreview_tvp
	IF (@statementtype = 'Insert')
		BEGIN
		if (@oaid>0 and @id=0)
			Begin
				INSERT INTO [db_sop].[contractreview_saleorder]
				   ([oaid],[crdate],[dealerexpenses],[emddetailrequired],[emddetail],[emddate],[securitydepositrequired],
				   [securitydepositdetail],[securitydepositdate],[ldclause],[agreement],[inspection],[deliveryrequestedbycustomer]
				   ,[datecommittedbyproduction],[qcandpackingdate],[receivedbycustomerdate],[stockorder],[technicalquery]
				   ,[installationInfo],[exciseexemption],[ewaybillrequired],[customerpendency],[companypendency],[contactuser]
				   ,[freight],[remarks],[review1],[review2],[review3],[createdby],[createdon])
				select [oaid],crdate,dealerexpenses,emddetailrequired,emddetail
				,case when emddate = '1900-01-01' then '' else emddate end
				,securitydepositrequired,securitydepositdetail
				,case when [securitydepositdate] = '1900-01-01' then '' else [securitydepositdate] end
				,ldclause,agreement,inspection
				,case when [deliveryrequestedbycustomer] = '1900-01-01' then '' else [deliveryrequestedbycustomer] end 
				,case when [datecommittedbyproduction] = '1900-01-01' then '' else [datecommittedbyproduction] end 
				,case when [qcandpackingdate] = '1900-01-01' then '' else [qcandpackingdate] end 
				,case when [receivedbycustomerdate] = '1900-01-01' then '' else [receivedbycustomerdate] end 
				,stockorder,technicalquery,
				installationInfo,exciseexemption ,ewaybillrequired,customerpendency,companypendency,contactuser,
				freight,remarks,reviewone ,reviewtwo ,reviewthree,@userid,getdate() from @contractreview_tvp
			End
		END
	Else
		Begin
			if (@oaid>0 and @id>0)
			Begin
			UPDATE [db_sop].[contractreview_saleorder]
			   SET [oaid] = a.oaid
				  ,[crdate] = a.crdate
				  ,[dealerexpenses] = a.dealerexpenses
				  ,[emddetailrequired] = a.emddetailrequired
				  ,[emddetail] = a.emddetail
				  ,[emddate] = case when a.emddate = '1900-01-01' then '' else a.emddate end
				  ,[securitydepositrequired] = a.securitydepositrequired
				  ,[securitydepositdetail] = a.securitydepositdetail
				  ,[securitydepositdate] = case when a.securitydepositdate = '1900-01-01' then '' else a.securitydepositdate end
				  ,[ldclause] = a.ldclause
				  ,[agreement] = a.agreement
				  ,[inspection] = a.inspection
				  ,[deliveryrequestedbycustomer] = case when a.deliveryrequestedbycustomer = '1900-01-01' then '' else a.deliveryrequestedbycustomer end
				  ,[datecommittedbyproduction] = case when a.datecommittedbyproduction = '1900-01-01' then '' else a.datecommittedbyproduction end 
				  ,[qcandpackingdate] = case when a.qcandpackingdate = '1900-01-01' then '' else a.qcandpackingdate end 
				  ,[receivedbycustomerdate] = case when a.receivedbycustomerdate = '1900-01-01' then '' else a.receivedbycustomerdate end
				  ,[stockorder] = a.stockorder
				  ,[technicalquery] = a.technicalquery
				  ,[installationInfo] = a.installationInfo
				  ,[exciseexemption] = a.exciseexemption
				  ,[ewaybillrequired] = a.ewaybillrequired
				  ,[customerpendency] = a.customerpendency
				  ,[companypendency] = a.companypendency
				  ,[contactuser] = a.contactuser
				  ,[freight] = a.freight
				  ,[remarks] = a.remarks
				  ,[review1] = a.reviewone
				  ,[review2] = a.reviewtwo
				  ,[review3] = a.reviewthree
				  ,[modifiedby] = @userid
				  ,[modifiedon] = getdate()
				  from @contractreview_tvp a where [db_sop].[contractreview_saleorder].id = a.id
			end
		End
END

GO
/****** Object:  StoredProcedure [db_sop].[pr_savecustomerorder]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_sop].[pr_savecustomerorder]   
 @statementtype nvarchar(50),  
 @SOPheader  [db_sop].[hdr_saleorder_tvp] readonly,  
 @SOPdetail  [db_sop].[dtl_saleorder_tvp] readonly,  
 @soppaymentterm [db_sop].[order_paymentterms_tvp] readonly,  
 @soptermsandcondition [db_sop].[order_termsandconditions_tvp] readonly,  
 @sopdeliveryschedule [db_sop].[order_deliveryschedule_tvp] READONLY,  
 @SOPdocumentsrequired [db_sop].[order_documentsreqd_tvp] READONLY,  
 @SOPaccessories [db_sop].[order_itemaccessories_tvp] READONLY,  
 @SOPpackinginstructions [db_sop].[order_packinginstructions_tvp] READONLY,  
 @SOPInstallationInfo [db_sop].[order_installationinfo_tvp] READONLY, 
 @SOPdiscSummary [db_sop].[order_discsummary_tvp] Readonly,
 @userid int=1   
 AS  
 BEGIN   
 SET QUOTED_IDENTIFIER OFF;  
 SET ANSI_NULLS ON;     
 SET NOCOUNT ON;  
  declare @oaid int, @rowcnt int,@suplid int, @colstring nvarchar(max),@sql nvarchar(max),@ordernumber int  
  DECLARE @error VARCHAR(100)  
  set @userid = (SELECT createdby FROM @SOPheader)  
 BEGIN TRANSACTION   
  If (@statementtype='Insert')  
  BEGIN  
  set @ordernumber = 0  
  -- This is to faciltate separate Bill Series Concept for Orders: and also for P/Is, Invoices etc.  
 declare @separateseries bit=(SELECT separateseries FROM db_sop.mst_ordertype where id=(select  ordertype from @SOPheader) and fyid=(select fyid from @SOPheader) )  
 if (@separateseries=0)  
 begin  
 declare @parentid int=( SELECT parentid FROM db_sop.mst_ordertype where id=(select  ordertype from @SOPheader) and fyid=(select fyid from @SOPheader))  
 set @ordernumber = (SELECT ISNULL(MAX([oano]), 0) + 1 FROM [db_sop].hdr_saleorder d where ordertype=@parentid )  
 end  
 else   
 begin  
 set @ordernumber = (SELECT ISNULL(MAX([oano]), 0) + 1 FROM [db_sop].hdr_saleorder d where ordertype=(select  ordertype from @SOPheader) )  
 end  
   ----set @ordernumber = (SELECT ISNULL(MAX(oano), 0) + 1 FROM [db_sop].[hdr_saleorder])  
    
   insert into [db_sop].[hdr_saleorder] ([oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],  
   [customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],  
   [billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],  
   [consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],  
   [consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],  
   [orderstatus],[confirmedbyuserid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyrandduserid],[approvedbyproductionuserid],  
   [approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],[remarks],[coid],[boid],[fyid],[createdby],[createdon],[ordertype],  
   [marketexecutive],[concessionaltax],[advancereceived],[roundoff],[totalamtinfc],currency,[conversionrate])  
   Select @ordernumber,[oadate],[customerid],LTRIM(RTRIM(customername)),LTRIM(RTRIM(customeraddr1)),LTRIM(RTRIM(customeraddr2)),[city],[state],[pin],[customergstno],[customercontactpersonname],  
   [customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],  
   [billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],  
   [consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],  
   [discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],[orderstatus],[confirmedbyuserid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],  
   [approvedbyrandduserid],[approvedbyproductionuserid],[approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],[remarks],[coid],[boid],  
   [fyid],@userid,getdate(),[ordertype],[marketexecutive],[concessionaltax],[advancereceived],[roundoff],[totalamtinfc],currency,[conversionrate] from @SOPheader  
   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 @oaid= SCOPE_IDENTITY()  
      
     ---insert data into saleorder detail  
    insert into [db_sop].[dtl_saleorder] ([oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],
	[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],[technicalspecs],[totalamtinfc],rateinfc)  
    select @oaid,[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],
	[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],[technicalspecs],[totalamtinfc],rateinfc  
    from @sopdetail  
  
    -- updating item-master existing records (HSNCODE & gstid )   
    --change by mohit (13-06-2019)  
     --UPDATE db_mm.mst_item   
     -- SET    
     --  [hsncode]=a.[hsncode],  
     -- [gstid]=a.[gstid]  
     --FROM   @sopdetail a  
     --WHERE db_mm.mst_item.id= a.[itemid]   
  
    IF @@ERROR <> 0  
     BEGIN  
     -- Rollback the transaction  
     ROLLBACK  
     -- Raise an error and return  
      RAISERROR ('Error while adding sop detail data.', 16, 1)  
     SET @error = 'Error while adding sop detail data.  error no: ' + CAST(@@error AS VARCHAR(3))  
     RETURN @error   
     END  
  
    insert into [db_sop].[order_paymentterms] ([orderid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[coid],[boid],[percent],[amount])  
    select @oaid,[srno],[paymenttermid],[paymentterm],@userid,getdate(),[coid],[boid],[percent],[amount] from @soppaymentterm  
     IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding po pyt data.', 16, 1)  
      SET @error = 'Error while adding po pyt data.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END  
  
    -- INSERT TERMS AND CONDITIONS  
    insert into [db_sop].[order_termsandconditions] ([orderid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon])  
    select @oaid,[srno],[termsandconditionsid],[termsandcondition],@userid,getdate() from @soptermsandcondition  
     IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop terms data.', 16, 1)  
      SET @error = 'Error while adding sop terms data.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END  
      
    -- INSERT DELIVERY SCHEDULE  
    insert into [db_sop].[order_deliveryschedule] ([orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon])  
    select @oaid,[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon] from @sopdeliveryschedule  
      IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop delivery data.', 16, 1)  
      SET @error = 'Error while adding sop delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END  
      
    -- INSERT DOCUMENT REQUIRED  
    insert into [db_sop].[order_documentsreqd]([orderid],[srno],[documentid],[documentinfo],[createdby],[createdon])  
    select @oaid,[srno],[documentid],[documentinfo],@userid,getdate() from @SOPdocumentsrequired  
      IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop delivery data.', 16, 1)  
      SET @error = 'Error while adding sop delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END  
      
    -- INSERT ITEM ACCESSORIES  
    insert into [db_sop].[order_itemaccessories]([orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand])  
    select @oaid,[itemid],[accessorieid],[accessorieqty],[accesoriebrand] from @SOPaccessories  
     IF @@ERROR <> 0  
     BEGIN  
     -- Rollback the transaction  
     ROLLBACK  
     -- Raise an error and return  
      RAISERROR ('Error while adding sop delivery data.', 16, 1)  
     SET @error = 'Error while adding sop delivery data.  error no: ' + CAST(@@error AS VARCHAR(3))  
     RETURN @error   
     END  
      
    -- INSERT PACKING INSTRUCTIONS  
    insert into [db_sop].[order_packinginstructions]([orderid],[srno],[instructionid],[instruction],[createdby],[createdon])  
    select @oaid,[srno],[instructionid],[instruction],@userid,getdate() from @SOPpackinginstructions  
      IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop packing instructions.', 16, 1)  
      SET @error = 'Error while adding sop packing instructions.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END  
      
    -- INSERT INSTALLATION INFORMATION  
    insert into [db_sop].[order_installationinfo]  
    ([orderid],[srno],[installationid],[installationinfo],[createdby],[createdon])  
    select @oaid,[srno],[installationid],[installationinfo],@userid,getdate() from @SOPInstallationInfo  
      IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop installation information.', 16, 1)  
      SET @error = 'Error while adding sop installation information.  error no: ' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END 
	 --  Insert Disc Summary by navneet 
     insert into [db_sop].[order_discountsummary]
	 (orderid,discdescid,[name],totalamt,disc,discamt,createdby,createdon)
	 select @oaid,discdescid,[name],totalamt,disc,discamt,@userid,getdate() from @SOPdiscSummary
	 IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while adding sop disc Summary information.', 16, 1)  
      SET @error = 'Error while adding sop disc information.  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 @oaid = oaid from @sopheader  
     
   select [oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone],  
   [customercontactpersondesignation],[customercontactpersondepartment],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],  
   [billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],  
   [consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],[orderstatus],[confirmedbyuserid],  
   [approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyrandduserid],[approvedbyproductionuserid],[approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],  
   [remarks],[ordertype],[marketexecutive],[totalamtinfc],currency,conversionrate  
   from [db_sop].[hdr_saleorder] where oaid =@oaid   
   EXCEPT select[oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone]  
   ,[customercontactpersondesignation],[customercontactpersondepartment],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate]  
   ,[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],  
   [consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],[orderstatus],[confirmedbyuserid],  
   [approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyrandduserid],[approvedbyproductionuserid],[approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],  
   [remarks],[ordertype],[marketexecutive] ,[totalamtinfc],currency,conversionrate  
   from @sopheader  
     
   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_sop].[hdr_saleorder] ([oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],
	 [customercontactpersondepartment],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],
[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],[orderstatus],[confirmedbyuserid],
[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyrandduserid],[approvedbyproductionuserid],[approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],[remarks],[invoicetype],[marketexecutive],
[concessionaltax],[advancereceived],[packinginstructions] ,[installationinfo])   
     Select  [oano],[oadate],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[customercontactpersonname],[customercontactpersonphone],[customercontactpersondesignation],[customercontactpersondepartment],[billtocustomerid],
	 [billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],
	 [consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[ourquoteno],[ourquotedate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[orderamt],[userid],[orderstatus],[confirmedbyuserid],[approvedbymarketingheaduserid],
	 [approvedbycommercialuserid],[approvedbyrandduserid],[approvedbyproductionuserid],[approvedbyceouserid],[amendmentno],[amendmentdate],[cancelledon],[cancelledbyuserid],[remarks],[ordertype],[marketexecutive],[concessionaltax],[advancereceived],
	 [packinginstructions] ,[installationinfo] from db_sop.hdr_saleorder where oaid =@oaid   
     -- 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_sop.hdr_saleorder  set   
     [oadate]=a.[oadate],  
     [customerid]=a.[customerid],  
     [customername]=a.[customername],  
     [customeraddr1]=a.[customeraddr1],  
     [customeraddr2]=a.[customeraddr2],  
     [city]=a.[city],  
     [state]=a.[state],  
     [pin]=a.[pin],  
     [customergstno]=a.[customergstno],  
     [customercontactpersonname]=a.[customercontactpersonname],  
     [customercontactpersonphone]=a.[customercontactpersonphone],  
     [customercontactpersondesignation]=a.[customercontactpersondesignation],  
     [customercontactpersondepartment]=a.[customercontactpersondepartment],  
     [billtocustomerid]=a.[billtocustomerid],  
     [billtocustomername]=a.[billtocustomername],  
     [billtocustomeraddr1]=a.[billtocustomeraddr1],  
     [billtocustomeraddr2]=a.[billtocustomeraddr2],  
     [billtocity]=a.[billtocity],  
     [billtostate]=a.[billtostate],  
     [billtopin]=a.[billtopin],  
     [billtocustomergstno]=a.[billtocustomergstno],  
     [consigneecustomerid]=a.[consigneecustomerid],  
     [consigneecustomername]=a.[consigneecustomername],  
     [consigneecustomeraddr1]=a.[consigneecustomeraddr1],  
     [consigneecustomeraddr2]=a.[consigneecustomeraddr2],  
     [consigneecity]=a.[consigneecity],  
     [consigneestate]=a.[consigneestate],  
     [consigneepin]=a.[consigneepin],  
     [consigneecustomergstno]=a.[consigneecustomergstno],  
     [custPoNo]=a.[custPoNo],  
     [custPodate]=a.[custPodate],  
     [ourquoteno]=a.[ourquoteno],  
     [ourquotedate]=a.[ourquotedate],  
     [basicamt]=a.[basicamt],  
     [discamt]=a.[discamt],  
     [netamt]=a.[netamt],  
     [igstamt]=a.[igstamt],  
     [cgstamt]=a.[cgstamt],  
     [sgstamt]=a.[sgstamt],  
     [orderamt]=a.[orderamt],  
     [userid]=a.[userid],  
     [orderstatus]=a.[orderstatus],  
     [confirmedbyuserid]=a.[confirmedbyuserid],  
     [approvedbymarketingheaduserid]=a.[approvedbymarketingheaduserid],  
     [approvedbycommercialuserid]=a.[approvedbycommercialuserid],  
     [approvedbyrandduserid]=a.[approvedbyrandduserid],  
     [approvedbyproductionuserid]=a.[approvedbyproductionuserid],  
     [approvedbyceouserid]=a.[approvedbyceouserid],  
     [amendmentno]=a.[amendmentno],  
     [amendmentdate]=a.[amendmentdate],  
     [cancelledon]=a.[cancelledon],  
     [cancelledbyuserid]=a.[cancelledbyuserid],  
     [remarks]=a.[remarks],  
     [ordertype]=a.[ordertype],  
     [marketexecutive]=a.[marketexecutive],  
     [concessionaltax]=a.[concessionaltax],  
     [advancereceived]=a.[advancereceived] ,  
     [totalamtinfc]=a.[totalamtinfc],  
     conversionrate=a.conversionrate,  
     currency=a.currency  
     FROM   @SOPheader a  
     WHERE  db_sop.hdr_saleorder.oaid=a.oaid  
    End  
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    -- error in except statement and in data insertion in bkup db  
      delete from db_sop.dtl_saleorder where [oaid] = @oaid  
      
      insert into db_sop.dtl_saleorder  
      ([oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],  
      [cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],  
      [totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],[totalamtinfc],[rateinfc])  
      SELECT @oaid,[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],  
      [cessrate],[basicamount],[mrp],[rate],[netrate],[orderedquantity],[itemdiscpercent],[itemdiscamt],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],  
      [totalamt],[remarks],[qtyalreadydispatched],[qtytodispatch],[coid],[boid],[fyid],[focqty],[totalamtinfc],[rateinfc] from @SOPdetail  
        
      -- updating item-master existing records (HSNCODE & gstid )   
    --change by mohit (13-06-2019)  
     UPDATE db_mm.mst_item   
      SET    
       [hsncode]=a.[hsncode],  
      [gstid]=a.[gstid]  
     FROM   @sopdetail a  
     WHERE db_mm.mst_item.id= a.[itemid]   
        
      -- Rollback the transaction if there were any errors  
      IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing sop order detail record.', 16, 1)  
        RETURN  
       END  
------------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    -- check updates in packing instructions -- amit  
    Select [orderid],[srno],[instructionid],[instruction] from @SOPpackinginstructions  
    EXCEPT   
    select @oaid,[srno],[instructionid],[instruction] from [db_sop].[order_packinginstructions] where [orderid] =@oaid    
      
    SELECT @rowcnt = @@ROWCOUNT   
    -- check for rowcnt  
    IF @rowcnt > 0  
     BEGIN -- begin of row count  
      insert into CloudERPbklog.[db_sop].[order_packinginstructions] ([orderid],[srno],[instructionid],[instruction],  
      [modifiedby],[modifiedon])   
      Select [orderid],[srno],[instructionid],[instruction],[modifiedby],getdate()  
      from db_sop.order_packinginstructions where orderid = @oaid  
      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_sop].[order_packinginstructions] where orderid = @oaid;   
      -- insert packing instructions  
      insert into [db_sop].[order_packinginstructions] ([orderid],[srno],[instructionid],[instruction],[createdby],[createdon],  
      [modifiedby],[modifiedon])   
      Select @oaid,[srno],[instructionid],[instruction],@userid,getdate(),@userid,getdate()   
      from @SOPpackinginstructions  
     End      
------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  
    -- check updates in installation info -- amit  
    /*select [orderid],[srno],[installationid],[installationinfo] from  @SOPInstallationInfo  
    EXCEPT   
    select @oaid,[srno],[installationid],[installationinfo] from [db_sop].[order_installationinfo] where [orderid] =@oaid    
      
    SELECT @rowcnt = @@ROWCOUNT   
    -- check for rowcnt  
    IF @rowcnt > 0  
     BEGIN -- begin of row count  
      insert into CloudERPbklog.[db_sop].[order_installationinfo] ([orderid],[srno],[installationid],[installationinfo],[createdby],[createdon],  
      [modifiedby],[modifiedon])   
      Select [orderid],[srno],[installationid],[installationinfo],[createdby],[createdon],[modifiedby],[modifiedon]  
      from  [db_sop].[order_installationinfo] where orderid = @oaid  
      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_sop].[order_installationinfo]  where orderid = @oaid;   
      -- insert installation information  
      insert into [db_sop].[order_installationinfo] ([orderid],[srno],[installationid],[installationinfo],[createdby],[createdon],  
      [modifiedby],[modifiedon])   
      Select @oaid,[srno],[installationid],[installationinfo],@userid,getdate(),@userid,getdate()  
      from @SOPInstallationInfo  
     --End-- end of row count  
-----------------------------------------------------------------------------------------------------------------------------------------------------------  
     -- check updates in payment terms  
    select [orderid],[srno],[paymenttermid],[paymentterm],[coid],[boid],[percent],[amount]  
    from   @soppaymentterm  
    EXCEPT   
    select @oaid,[srno],[paymenttermid],[paymentterm],[coid],[boid],[percent],[amount]   
    from [db_sop].[order_paymentterms] where [orderid] =@oaid    
     
      
    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_sop].[order_paymentterms] ([orderid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount])   
      Select [orderid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount]  from db_sop.order_paymentterms where orderid = @oaid  
      --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_sop.order_paymentterms where [orderid] = @oaid  
       -- insert payment terms  
      insert into db_sop.order_paymentterms([orderid],[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount])  
      select @oaid,[srno],[paymenttermid],[paymentterm],[createdby],[createdon],[modifiedby],[modifiedon],[coid],[boid],[percent],[amount] from @soppaymentterm  
       -- Rollback the transaction if there were any errors  
      IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing po paymentterms record.', 16, 1)  
        RETURN   
       END  
     End--end of row count  
---------------------------------------------------------------------------------------------------------------------------------------------------------  
    -- check updates in terms and conditions  
    -- to check backlog table and insert query  
    select [orderid],[srno],[termsandconditionsid],[termsandcondition]  
    from  @SOPtermsandcondition  
    EXCEPT   
    select [orderid],[srno],[termsandconditionsid],[termsandcondition]  
    from [db_sop].[order_termsandconditions] where [orderid] = @oaid   
     
    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_sop].[order_termsandconditions] ([orderid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon],[modifiedby],[modifiedon])   
     -- SELECT [orderid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon],@userid,[modifiedon] from db_sop.order_termsandconditions where orderid = @oaid   
      --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_sop].[order_termsandconditions] where [orderid] = @oaid  
      insert into [db_sop].[order_termsandconditions]([orderid],[srno],[termsandconditionsid],[termsandcondition],[createdby],[createdon],[modifiedby],[modifiedon])  
      select @oaid,[srno],[termsandconditionsid],[termsandcondition],@userid,getdate(),@userid,getdate() from @SOPtermsandcondition  
      -- Rollback the transaction if there were any errors  
      IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing po termsandconditions record.', 16, 1)  
        RETURN  
       END  
     END -- end of row count       
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    -- check for updates in item delivery  
    Select [itemid],[remarks],[deliverydate],[qtytobedispatch] from  @sopdeliveryschedule  
    EXCEPT   
    select [itemid],[remarks],[deliverydate],[qtytobedispatch] from [db_sop].[order_deliveryschedule] where [orderid] = @oaid   
     
    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_sop].[order_deliveryschedule] ([orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon])   
      SELECT [orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon] from db_sop.order_deliveryschedule where orderid = @oaid   
      --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_sop].[order_deliveryschedule] where [orderid] = @oaid  
       insert into [db_sop].[order_deliveryschedule]([orderid],[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon])  
      select @oaid,[itemid],[remarks],[deliverydate],[qtytobedispatch],[dispatchqty],[dispatchon] from @SOPdeliveryschedule  
      -- Rollback the transaction if there were any errors  
      /*IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing po termsandconditions record.', 16, 1)  
        RETURN  
       END*/  
     End  
                  
  
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  
    select [orderid],[srno],[documentid],[documentinfo]  
    from  @sopdocumentsrequired  
    EXCEPT   
    select [orderid],[srno],[documentid],[documentinfo] from [db_sop].[order_documentsreqd] where [orderid] = @oaid   
     
    --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_sop].[order_documentsreqd] ([orderid],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon])   
      SELECT  [orderid],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon] from [db_sop].[order_documentsreqd] where orderid = @oaid   
      -- 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_sop].[order_documentsreqd] where [orderid] = @oaid  
       insert into [db_sop].[order_documentsreqd]([orderid],[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon])  
      select @oaid,[srno],[documentid],[documentinfo],[createdby],[createdon],[modifiedby],[modifiedon] from @SOPdocumentsrequired  
      -- Rollback the transaction if there were any errors  
      IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing po termsandconditions record.', 16, 1)  
        RETURN  
       END  
     End  
  
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------  
  
    -- check for udpates in accessories  
    select [orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand] from  @SOPaccessories  
    EXCEPT   
    select [orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand] from [db_sop].[order_itemaccessories] where [orderid] = @oaid   
     
     
    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_sop].[order_itemaccessories]([orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand])   
      SELECT  [orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand] from [db_sop].[order_itemaccessories] where orderid = @oaid   
      --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_sop].[order_itemaccessories] where [orderid] = @oaid  
      insert into [db_sop].[order_itemaccessories]([orderid],[itemid],[accessorieid],[accessorieqty],[accesoriebrand])  
      select @oaid,[itemid],[accessorieid],[accessorieqty],[accesoriebrand]from @SOPaccessories  
      -- Rollback the transaction if there were any errors  
      IF @@ERROR <> 0  
       BEGIN  
        -- Rollback the transaction  
        ROLLBACK  
        -- Raise an error and return  
        RAISERROR ('Error while updating existing po termsandconditions record.', 16, 1)  
        RETURN  
        END  

			   		 -- disc summary updation by navneet
     delete from [db_sop].[order_discountsummary] where orderid=@oaid

	 insert into [db_sop].[order_discountsummary]
	 (orderid,discdescid,[name],totalamt,disc,discamt,createdby,createdon)
	 select @oaid,discdescid,[name],totalamt,disc,discamt,@userid,getdate() from @SOPdiscSummary
	 IF @@ERROR <> 0  
      BEGIN  
      -- Rollback the transaction  
      ROLLBACK  
      -- Raise an error and return  
       RAISERROR ('Error while updating sop disc Summary information.', 16, 1)  
      SET @error = 'Error while updating sop disc information. error no:' + CAST(@@error AS VARCHAR(3))  
      RETURN @error   
      END 

       End  


----------------------------------------------------------------------------------------------------------------------------------------------------------------------  
    END  
commit  
END  
GO
/****** Object:  StoredProcedure [db_sop].[pr_savedrcrnote]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		<Author,Er.Ravinder Pal>
-- Create date: <Create Date,10-01-2020>
-- Description:	<Description,Save drcr note>

CREATE  PROCEDURE [db_sop].[pr_savedrcrnote] 
@action VARCHAR(20),
@header [db_sop].[hdr_drcrnote] readonly,
@detail [db_sop].[dtl_drcrnote] readonly,
@userid int=1,
@coid int,
@boid int,
@fyid int,
@accesstoken char(30)=null
AS
BEGIN
SET QUOTED_IDENTIFIER OFF;
SET ANSI_NULLS ON;   
SET NOCOUNT ON;
declare @noteid int, @noteno int, @rowcnt int,  @error VARCHAR(100)
set @noteno = (SELECT ISNULL(MAX(noteno), 0) + 1 as noteno from [db_sop].[hdr_drcrnote] where coid=@coid and boid=@boid) 

BEGIN TRANSACTION 
If (@action='Insert')
	Begin
		insert into [db_sop].[hdr_drcrnote](noteno, notedate,  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
					[sgstamt], [cgstamt], [totalamt],boid, [coid],[fyid],createdby,[createdon])
		SELECT  @noteno, notedate,  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
					[sgstamt], [cgstamt], [totalamt], @boid, @coid, @fyid, @userid, getdate() from @header
		IF @@ERROR <> 0
		BEGIN
		-- Rollback the transaction
		ROLLBACK
		-- Raise an error and return
		RAISERROR ('Error while adding note 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 note id.', 16, 1)
		RETURN
		END

		insert into [db_sop].[dtl_drcrnote](noteid, itemid,  billedqty, noteqty, rate, taxableamt, igst,
                   [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid,notetypeid)
		SELECT  @noteid, itemid,  billedqty, noteqty, rate, taxableamt, igst,
                   [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid from @detail
		IF @@ERROR <> 0
		BEGIN
		-- Rollback the transaction
		ROLLBACK
		-- Raise an error and return
		RAISERROR ('Error while adding note detail Data.', 16, 1)
		RETURN
		END

	end
else
	Begin

	select top 1 @noteid =id from @header

	SELECT   partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
			[sgstamt], [cgstamt], [totalamt] from [db_sop].[hdr_drcrnote] where id=@noteid
	EXCEPT 
	SELECT  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
			[sgstamt], [cgstamt], [totalamt] from @header

	SELECT @rowcnt = @@ROWCOUNT
	IF @rowcnt > 0
		BEGIN
		insert into CloudERPbklog.[db_sop].[hdr_drcrnote](id, noteno, notedate,  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
			                            [sgstamt], [cgstamt], [totalamt],createdby,[createdon], modifiedby, modifiedon)
		SELECT id, noteno, notedate,  partyid, name,[address],  city,state, country, gstin, [drcr], [reasonid], invid, [taxableamt], [igstamt],
			                            [sgstamt], [cgstamt], [totalamt],createdby,[createdon], modifiedby, modifiedon
		from [db_sop].[hdr_drcrnote] where id=@noteid

		UPDATE [db_sop].[hdr_drcrnote] 
			       set
		           partyid=a.partyid,
                   name=a.name,
                   [address]=a.[address],
                   city=a.city,
                   state=a.state,
                   country=a.country,
                   gstin=a.gstin,
                   [drcr]=a.[drcr],
				   [reasonid]=a.[reasonid],
				   invid=a.invid,
				   [taxableamt]=a.[taxableamt],
				   [sgstamt]=a.[sgstamt],
				   [cgstamt]=a.[cgstamt],
				   [igstamt]=a.[igstamt],
				   [totalamt]=a.[totalamt],
                   [modifiedby]=@userid,
                   [modifiedon]=getdate()
                   FROM   @header a
  				   WHERE [db_sop].[hdr_drcrnote].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 note header record.', 16, 1)
							RETURN
					END
	   end   
	 --  	SELECT  itemid,  billedqty, noteqty, rate, taxableamt, igst, [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid from [db_sop].[dtl_drcrnote] where noteid=@noteid
		--EXCEPT 
		--SELECT  itemid,  billedqty, noteqty, rate, taxableamt, igst, [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid from @detail

		--SELECT @rowcnt = @@ROWCOUNT
		--IF @rowcnt > 0
		--BEGIN
		insert into CloudERPbklog.[db_sop].[dtl_drcrnote](id, noteid,  itemid,  billedqty, noteqty, rate, taxableamt, igst, [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid)
		SELECT id, noteid,  itemid,  billedqty, noteqty, rate, taxableamt, igst, [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid
		from [db_sop].[dtl_drcrnote] where noteid=@noteid

		DELETE FROM [db_sop].[dtl_drcrnote] WHERE noteid = @noteid

		insert into [db_sop].[dtl_drcrnote](noteid, itemid,  billedqty, noteqty, rate, taxableamt, igst,
                   [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid)
		SELECT  @noteid, itemid,  billedqty, noteqty, rate, taxableamt, igst,
                   [sgst], [cgst], [igstamt], [sgstamt], [cgstamt], [totalamt], gstid, notetypeid from @detail

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

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

CREATE PROCEDURE [db_sop].[pr_saveinvoice]
@statementtype NVARCHAR(50),
@sopinvoiceheader [db_sop].[hdr_sale_tvp] READONLY,
@sopinvoicedetail [db_sop].[dtl_sale_tvp] READONLY,
@itemsbatchwise [db_sop].[dtl_sale_batches_tvp] READONLY,

@leviesarray [db_sop].[dtl_sale_levies_tvp] READONLY,
@lcarray [db_sop].[dtl_sale_lc_tvp] READONLY,
@expcarriagearray [db_sop].[dtl_sale_expcarriage_tvp] READONLY,
@paymentterms [db_sop].[dtl_sale_paymentterms_tvp] READONLY,
@transport [db_sop].[dtl_sale_transportation_tvp] READONLY,
@packingitems [db_sop].[dtl_sale_packinglist_tvp] READONLY,
@userid INT = 1
AS

BEGIN
	SET QUOTED_IDENTIFIER OFF;
	SET ANSI_NULLS ON;
	SET NOCOUNT ON;
	DECLARE @invid INT
		   ,@rowcnt INT
		   ,@colstring NVARCHAR(MAX)
		   ,@sql NVARCHAR(MAX)
	DECLARE @invno INT
	DECLARE @concessionaltax bit
	BEGIN TRANSACTION
	IF (@statementtype = 'Insert')
	BEGIN
	set @invno = 0
	-- This is to faciltate separate Bill Series Concept for Orders: and also for P/Is, Invoices etc.
	declare @separateseries bit=(SELECT separateseries FROM db_sop.mst_ordertype where id=(select  invoicetype from @sopinvoiceheader) and fyid=(select fyid from @sopinvoiceheader))
	if (@separateseries=0)
	begin
declare @parentid int=(	SELECT parentid FROM db_sop.mst_ordertype where id=(select  invoicetype from @sopinvoiceheader) and fyid=(select fyid from @sopinvoiceheader))
	set @invno = (SELECT ISNULL(MAX([pino]), 0) + 1 FROM [db_sop].[hdr_sale] d where invoicetype=@parentid )
	end
	else	
	begin
	set @invno = (SELECT ISNULL(MAX([pino]), 0) + 1 FROM [db_sop].[hdr_sale] d where invoicetype=(select  invoicetype from @sopinvoiceheader) )
	end

	--set @invno = (SELECT ISNULL(MAX([pino]), 0) + 1 FROM [db_sop].[hdr_sale] d )
	--set @concessionaltax = (SELECT concessionaltax FROM [db_sop].[hdr_saleorder] d where oaid=(select oaid from @sopinvoiceheader) )
		-- add sale header information
		INSERT INTO [db_sop].[hdr_sale]  ([oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],
		[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],
		[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],
		[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],
		[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],
		[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],
		[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],
		[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],
		[remarks],[coid],[boid],[fyid],[createdby],[createdon],invoicetype,
		currency,conversionrate,concessionaltax,invcertification,[totalamtinfc])
			SELECT [oaids],@invno,pidate,[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],
			[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],
			[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],
			[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],
			[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],
			[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],[coid],[boid],[fyid],
			@userid,getdate(),invoicetype,currency,conversionrate,@concessionaltax,invcertification,[totalamtinfc] from @sopinvoiceheader
			

		IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice header data.', 16, 1)
			RETURN
		END
		SELECT	@invid = SCOPE_IDENTITY()
		
		-- add transaction details
		INSERT INTO [db_sop].[dtl_sale] ([fyid],[invid],[oaid],[itemid],[billingdescription],[isfoc],
		[issample],[specialcode],[packing],[uom],
		[gstid],[igstrate],[sgstrate],[cgstrate],
		[cessrate],[basicamount],[rate],[itemdiscpercent],
		[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],
		[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],
		[totalamt],[remarks],[totalamtinfc],rateinfc)
			SELECT [fyid],@invid,[oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],
			[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],
			[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],
			[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[totalamtinfc],rateinfc from @sopinvoicedetail
			
	
	
	    if   exists(select 1 from @itemsbatchwise) 
				begin
                    insert into [db_sop].[dtl_sale_batches]  ([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
                    select @invid,[oaid],[itemid],[packing],[qty],[focqty],[batch],
                    [mfgdate],[expdate] from @itemsbatchwise where [qty]>0

                    insert into [db_sop].[dtl_sale_batches]([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
                    select @invid,[oaid],[itemid],[packing],[qtytodispatch],0,[batch],'',
                    '' from @sopinvoicedetail 
                    where itemid  not in (select itemid from @itemsbatchwise )
				end 
				ELSE
				begin
                      insert into [db_sop].[dtl_sale_batches]([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
                    select @invid,[oaid],[itemid],[packing],[qtytodispatch],0,[batch],'',
                    '' from @sopinvoicedetail
                -- insert into [db_sop].[dtl_sale_batches] ([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
				-- select @invid,[oaid],[itemid],[packing],[qty],[focqty],[batch],
	            -- [mfgdate],[expdate] from @itemsbatchwise
				end
		----Insert Levies data
	insert into [db_sop].[dtl_sale_levies] (invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
	igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate, createdby, createdon)
	select @invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, igstamt, cgstamt, sgstamt, igstrate,
	 cgstrate, sgstrate, @userid, getdate()	from @leviesarray
	 	IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice levies data.', 16, 1)
			RETURN
		END

	--	----Insert Lc data
		insert into [db_sop].[dtl_sale_lc] (invid, lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, 
		lcbankname, lcbankbranch, lcareacode, lctinno, lcvatno, createdby, createdon)
	select @invid,  lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, lcbankname, lcbankbranch, 
	lcareacode, lctinno, lcvatno, @userid, getdate() 	from @lcarray
	 	IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice LC data.', 16, 1)
			RETURN
		END
	

		----Insert export carriage data
		insert into db_sop.dtl_sale_exportcarriage (invid, precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, 
		portofdischarge, postcarriageby, placeofreceiptbypostcarriage, finaldestination, createdby, createdon)
	select @invid,  precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, portofdischarge, postcarriageby, 
	placeofreceiptbypostcarriage, finaldestination, @userid, getdate() from @expcarriagearray
	 	IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice export carriage data.', 16, 1)
			RETURN
		END

		--Insert payment data
		insert into [db_sop].[dtl_sale_paymentterms] (invid, srno, paymentterm, [percent], amount, createdby, createdon)
	select @invid, srno, paymentterm, [percent], amount, @userid, getdate() from @paymentterms
	 	IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice payment data.', 16, 1)
			RETURN
		END

		--Insert packing items data
		insert into [db_sop].dtl_sale_packinglist (invid, catno, couriertype, description, qty, unit, netweight, grossweight, length, breadth, height, totalweight, createdby, createdon)
	select @invid,  catno, couriertype, description, qty, unit, netweight, grossweight, length, breadth, height, totalweight, @userid, getdate() from @packingitems
	 	IF @@error <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK
			-- Raise an error and return
			RAISERROR ('Error while adding sop invoice payment data.', 16, 1)
			RETURN
		END


		--Insert transport data
	--	insert into    db_sop.invoice_transportation (invid, dispatchqty, dispatchdate, expecteddeliverydate, glrno, glrdate, transportid, transportname, vehicleno, weight, createdby, createdon)
	--select @invid,  dispatchqty, dispatchdate, expecteddeliverydate, glrno, glrdate, transportid, transportname, vehicleno, weight, @userid, getdate() from @transport
	-- 	IF @@error <> 0
	--	BEGIN
	--		-- Rollback the transaction
	--		ROLLBACK
	--		-- Raise an error and return
	--		RAISERROR ('Error while adding sop invoice payment data.', 16, 1)
	--		RETURN
	--	END
	END
	ELSE
	BEGIN -- begin of update 
		-- fetching indent id from table type
		SELECT TOP 1
			@invid = id
		FROM @sopinvoiceheader

		SELECT [oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],invcertification,currency
			
		FROM [db_sop].[hdr_sale]
		WHERE id = @invid
		EXCEPT
		SELECT   [oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],invcertification,currency
		FROM @sopinvoiceheader

		--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_sop].[hdr_sale] ([oaid],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],
			[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],
			[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername]
			,[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],
			[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],
			[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],
			[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid]
			,[remarks],[coid],[boid],[fyid],[createdby],[createdon],[modifiedby],[modifiedon])
				SELECT [oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],
				[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],[customeraddr1],[customeraddr2],[city],
				[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],
				[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2]
				,[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt]
				,[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],[coid],[boid],
				[fyid],[createdby],[createdon],@userid,[modifiedon] 					
				FROM [db_sop].[hdr_sale]
				WHERE id = @invid

			--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_sop].[hdr_sale]
			SET [oaids]=a.[oaids],
[pino]=a.[pino],
[pidate]=a.[pidate],
[confirmed]=a.[confirmed],
[confirmedbyuserid]=a.[confirmedbyuserid],
[confirmedon]=a.[confirmedon],
[invno]=a.[invno],
[invdate]=a.[invdate],
[revisedbyuserid]=a.[revisedbyuserid],
[revisedon]=a.[revisedon],
[cancelledon]=a.[cancelledon],
[cancelledbyuserid]=a.[cancelledbyuserid],
[invprefix]=a.[invprefix],
[invpostfix]=a.[invpostfix],
[customerid]=a.[customerid],
[customername]=a.[customername],
[customeraddr1]=a.[customeraddr1],
[customeraddr2]=a.[customeraddr2],
[city]=a.[city],
[state]=a.[state],
[pin]=a.[pin],
[customergstno]=a.[customergstno],
[billtocustomerid]=a.[billtocustomerid],
[billtocustomername]=a.[billtocustomername],
[billtocustomeraddr1]=a.[billtocustomeraddr1],
[billtocustomeraddr2]=a.[billtocustomeraddr2],
[billtocity]=a.[billtocity],
[billtostate]=a.[billtostate],
[billtopin]=a.[billtopin],
[billtocustomergstno]=a.[billtocustomergstno],
[consigneecustomerid]=a.[consigneecustomerid],
[consigneecustomername]=a.[consigneecustomername],
[consigneecustomeraddr1]=a.[consigneecustomeraddr1],
[consigneecustomeraddr2]=a.[consigneecustomeraddr2],
[consigneecity]=a.[consigneecity],
[consigneestate]=a.[consigneestate],
[consigneepin]=a.[consigneepin],
[consigneecustomergstno]=a.[consigneecustomergstno],
[custPoNo]=a.[custPoNo],
[custPodate]=a.[custPodate],
[basicamt]=a.[basicamt],
[discamt]=a.[discamt],
[netamt]=a.[netamt],
[igstamt]=a.[igstamt],
[cgstamt]=a.[cgstamt],
[sgstamt]=a.[sgstamt],
[invamt]=a.[invamt],
[userid]=a.[userid],
[approvedbymarketingheaduserid]=a.[approvedbymarketingheaduserid],
[approvedbycommercialuserid]=a.[approvedbycommercialuserid],
[approvedbyaccountsuserid]=a.[approvedbyaccountsuserid],
[remarks]=a.[remarks],
[coid]=a.[coid],
[boid]=a.[boid],
[fyid]=a.[fyid],
[modifiedby]=@userid,
[modifiedon]=getdate(),
currency = a.currency,
conversionrate = a.conversionrate,
invcertification=a.invcertification,
totalamtinfc=a.totalamtinfc
			FROM @sopinvoiceheader a
			WHERE  db_sop.hdr_sale.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 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
						id
					FROM CloudERPbklog.[db_sop].[hdr_sale]
					WHERE id = @invid)
			BEGIN
				-- insert data in INDENT HEADER table and checking @@ERROR 
				INSERT INTO CloudERPbklog.[db_sop].[hdr_sale] ([id],[oaid],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],[coid],[boid],[fyid],[createdby],[createdon],[modifiedby],[modifiedon])

					SELECT
					    [id],[oaids],[pino],[pidate],[confirmed],[confirmedbyuserid],[confirmedon],[invno],[invdate],[revisedbyuserid],[revisedon],[cancelledon],[cancelledbyuserid],[invprefix],[invpostfix],[customerid],[customername],[customeraddr1],[customeraddr2],[city],[state],[pin],[customergstno],[billtocustomerid],[billtocustomername],[billtocustomeraddr1],[billtocustomeraddr2],[billtocity],[billtostate],[billtopin],[billtocustomergstno],[consigneecustomerid],[consigneecustomername],[consigneecustomeraddr1],[consigneecustomeraddr2],[consigneecity],[consigneestate],[consigneepin],[consigneecustomergstno],[custPoNo],[custPodate],[basicamt],[discamt],[netamt],[igstamt],[cgstamt],[sgstamt],[invamt],[userid],[approvedbymarketingheaduserid],[approvedbycommercialuserid],[approvedbyaccountsuserid],[remarks],[coid],[boid],[fyid],[createdby],[createdon],[modifiedby],[modifiedon]
					FROM [db_sop].[hdr_sale]
					WHERE id = @invid
				-- 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 [oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch]
		FROM [db_sop].[dtl_sale]
		WHERE invid = @invid
		EXCEPT
		SELECT [oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch]
		FROM @sopinvoicedetail 
		--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_sop.dtl_sale ([id],[fyid],[invid],[oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch])

				SELECT
					[id],[fyid],[invid],[oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch]
				FROM db_sop.dtl_sale
				WHERE invid = @invid

			--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_sop.dtl_sale WHERE invid = @invid

			INSERT INTO db_sop.dtl_sale ([fyid],[invid],[oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch],[totalamtinfc],rateinfc)
				SELECT
				  [fyid],@invid,[oaid],[itemid],[billingdescription],[isfoc],[issample],[specialcode],[packing],[uom],[gstid],[igstrate],[sgstrate],[cgstrate],[cessrate],[basicamount],[rate],[itemdiscpercent],[itemdiscamt],[netrate],[orderedquantity],[qtyalreadydispatched],[qtytodispatch],[netamt],[igstamt],[cgstamt],[sgstamt],[cessamt],[totalamt],[remarks],[batch],[totalamtinfc],rateinfc
				FROM @sopinvoicedetail
			-- 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
		 

		-- item wise batch details
		-- removing items those are not their in tvp
		--delete from db_sop.dtl_sale_batches where invid = @invid and  id not in (select id from @itemsbatchwise)

		-- update existing records
		--update db_sop.dtl_sale_batches set oaid = a.oaid,itemid=a.itemid, packing=a.packing,qty=a.qty,
		--focqty=a.focqty,batch = a.batch, mfgdate=a.mfgdate,expdate=a.expdate from
		--#tempbatchdetail a where db_sop.dtl_sale_batches.id= #tempbatchdetail.id 
		
		--  add new records
		-- Insert into [db_sop].[dtl_sale_batches] ([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],
		--[mfgdate],[expdate])
		--select @invid,[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate] 
		--from @itemsbatchwise where id = 0
		delete from db_sop.dtl_sale_batches where invid = @invid
		 if   exists(select 1 from @itemsbatchwise) 
				begin
				insert into [db_sop].[dtl_sale_batches]  ([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
				select @invid,[oaid],[itemid],[packing],[qty],[focqty],[batch],
	            [mfgdate],[expdate] from @itemsbatchwise where qty>0

				insert into [db_sop].[dtl_sale_batches]([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
				select @invid,[oaid],[itemid],[packing],[qtytodispatch],0,[batch],'',
				'' from @sopinvoicedetail 
				where itemid  not in (select itemid from @itemsbatchwise)
				end 
				ELSE
				begin
                		insert into [db_sop].[dtl_sale_batches]([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
				select @invid,[oaid],[itemid],[packing],[qtytodispatch],0,[batch],'',
				'' from @sopinvoicedetail 
                -- insert into [db_sop].[dtl_sale_batches] ([invid],[oaid],[itemid],[packing],[qty],[focqty],[batch],[mfgdate],[expdate])
				-- select @invid,[oaid],[itemid],[packing],[qty],[focqty],[batch],
	            -- [mfgdate],[expdate] from @itemsbatchwise
				end
				END -- end of row count
		END
--SELECT  invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
--	igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate FROM [db_sop].[dtl_sale_levies]
--		WHERE invid = @invid
--		EXCEPT
--	SELECT  invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
--	igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate FROM @leviesarray
--	SELECT @rowcnt = 0
--	SELECT @rowcnt = @@rowcount
--	if @rowcnt >0
--	begin
--	update  [db_sop].[dtl_sale_lc] set invid=@invid, lcno=lcno, lcdate=lcdate, lcamendmentno=lcamendmentno, lcamendmentdate=lcamendmentdate, lcdescription=lcdescription, 
--		lcbankname=lcbankname, lcbankbranch=lcbankbranch, lcareacode=lcareacode, lctinno=lctinno, lcvatno=lcvatno	from @lcarray
--	end
--	else
--	begin
	--  insert into [db_sop].[dtl_sale_levies] (invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
	--igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate, createdby, createdon)
	--select @invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, igstamt, cgstamt, sgstamt, igstrate,
	-- cgstrate, sgstrate, @userid, getdate()	from @leviesarray
	 --end

	 delete from [db_sop].[dtl_sale_levies] where invid=@invid
	   insert into [db_sop].[dtl_sale_levies] (invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, 
	igstamt, cgstamt, sgstamt, igstrate, cgstrate, sgstrate, createdby, createdon)
	select @invid, levyid, quantity, rate, uom, uomid, amount, hsncode, gstid, igstamt, cgstamt, sgstamt, igstrate,
	 cgstrate, sgstrate, @userid, getdate()	from @leviesarray

	  delete from [db_sop].[dtl_sale_lc] where invid=@invid
	 	insert into [db_sop].[dtl_sale_lc] (invid, lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, 
		lcbankname, lcbankbranch, lcareacode, lctinno, lcvatno, createdby, createdon)
	select @invid,  lcno, lcdate, lcamendmentno, lcamendmentdate, lcdescription, lcbankname, lcbankbranch, 
	lcareacode, lctinno, lcvatno, @userid, getdate() 	from @lcarray

	 delete from [db_sop].dtl_sale_exportcarriage where invid=@invid
		insert into db_sop.dtl_sale_exportcarriage (invid, precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, 
		portofdischarge, postcarriageby, placeofreceiptbypostcarriage, finaldestination, createdby, createdon)
	select @invid,  precarriageby, placeofreceiptbyprecarriage, vesselflightno, portofloading, portofdischarge, postcarriageby, 
	placeofreceiptbypostcarriage, finaldestination, @userid, getdate() from @expcarriagearray

	 delete from [db_sop].[dtl_sale_paymentterms] where invid=@invid
	insert into [db_sop].[dtl_sale_paymentterms] (invid, srno, paymentterm, [percent], amount, createdby, createdon)
	select @invid, srno, paymentterm, [percent], amount, @userid, getdate() from @paymentterms

	 delete from [db_sop].dtl_sale_packinglist where invid=@invid
	insert into [db_sop].dtl_sale_packinglist (invid, catno, couriertype, description, qty, unit, netweight, grossweight, length, breadth, height, totalweight, createdby, createdon)
	select @invid,  catno, couriertype, description, qty, unit, netweight, grossweight, length, breadth, height, totalweight, @userid, getdate() from @packingitems

	 delete from [db_sop].dtl_sale_transportation where invid=@invid
	insert into    db_sop.dtl_sale_transportation (invid, dispatchqty, dispatchdate, expecteddeliverydate, glrno, glrdate, transportid, transportname, vehicleno, weight, createdby, createdon)
	select @invid,  dispatchqty, dispatchdate, expecteddeliverydate, glrno, glrdate, transportid, transportname, vehicleno, weight, @userid, getdate() from @transport


	--update  [db_sop].[dtl_sale_lc] set invid=@invid, lcno=lcno, lcdate=lcdate, lcamendmentno=lcamendmentno, lcamendmentdate=lcamendmentdate, lcdescription=lcdescription, 
	--	lcbankname=lcbankname, lcbankbranch=lcbankbranch, lcareacode=lcareacode, lctinno=lctinno, lcvatno=lcvatno	from @lcarray

	--	update db_sop.dtl_sale_exportcarriage set invid=@invid, precarriageby=precarriageby, placeofreceiptbyprecarriage=placeofreceiptbyprecarriage, vesselflightno=vesselflightno, portofloading=portofloading, 
	--	portofdischarge=portofdischarge, postcarriageby=postcarriageby, placeofreceiptbypostcarriage=placeofreceiptbypostcarriage, finaldestination=finaldestination 
	--	  where id=id
	--update [db_sop].[dtl_sale_paymentterms] set invid=@invid, srno=srno, paymentterm=paymentterm, [percent]=[percent], amount=amount  where id=id

	--update [db_sop].[dtl_sale_paymentterms]  set invid=@invid, catno=catno, couriertype=couriertype, description=description, qty=qty, unit=unit, netweight=netweight, 
	--grossweight=grossweight, length=length, breadth=breadth, height=height, totalweight=totalweight where id=id

	--update     db_sop.invoice_transportation  set invid=@invid, dispatchqty=dispatchqty, dispatchdate=dispatchdate, expecteddeliverydate=expecteddeliverydate, 
	--glrno=glrno, glrdate=glrdate, transportid=transportid, transportname=transportname, vehicleno=vehicleno, weight=weight where id=id
	COMMIT

END







GO
/****** Object:  StoredProcedure [db_sop].[pr_saveorderuploadinfo]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 CREATE PROCEDURE [db_sop].[pr_saveorderuploadinfo]
    @statementtype nvarchar(50),
	@userid int=1,
	@filename VARCHAR(200),
    @QuoteImageInfo VARCHAR(MAX)=NULL,
	@coid int,
	@boid int,
	@fyid INT,
	@orderid BIGINT,
	@orderno 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_sop].[order_images]
		  ([orderid],[filename],[imageinfo],[isactive],[createdby],[createdon])
		  VALUES(@orderid,@filename,@QuoteImageInfo,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

select * from [db_sop].[order_images]



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

--exec [db_sop].[pr_vouchergeneration] 1,5, 'Insert'
CREATE PROCEDURE [db_sop].[pr_vouchergeneration]  
@invid bigint,
@invno bigint,
@statementtype VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	
IF OBJECT_ID('tempdb..#tempvouch') IS NOT NULL DROP TABLE #tempvouch
	create table #tempvouch
	(
coid	int,
boid	int,
userid	int,
voucherno	bigint,
rowno	int,
voucherdate	date,
voucheramount	decimal(18, 2),
vouchertype	char(1),
vouchercategory	char(1),
accountid	bigint,
drcr	char(1),
narration	varchar(500),
refid	bigint,
isconfirm	bit,
trntype	int,
oppositeacid	bigint,
fyid	int,
subledgercode	varchar(2),
cencaled	bit,
createdby	bigint,
createdon	datetime,
);

	declare @id int=0 ,@id1 int=0;
	declare @checkitemid bigint;
	set @invid=0
	set @invno=0	
	select top 1 @id=id, @invid=id,@invno=invno  from [db_sop].[hdr_sale] where id >@id and invno>0 and fyid=1 order by id	
	if (@invno >0)
		begin
			startagain:		
	declare @voucherno bigint 
	select @voucherno= isnull(max(voucherno),0)+1 from [db_accounts].[voucher] where vouchercategory='S' and trntype=5
	print @invid 
	
	delete from #tempvouch
insert into #tempvouch (voucheramount,accountid, drcr)(
select isnull(invamt,0) amt,a.id as acid,'D' as type from	[db_sop].[hdr_sale]	h join [db_accounts].[accountHeads] a
on h.customerid=a.partyid where h.id=@invid
union all
select sum(isnull(basicamount,0)) amt,saleacid as ACID,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , saleacid  
union all
select sum(isnull(igstamt,0)) amt,igstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , igstoutputacid 
union all
select sum(isnull(cgstamt,0)) amt,cgstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , cgstoutputacid 
union all
select sum(isnull(sgstamt,0)) amt,sgstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , sgstoutputacid 
union all
select sum(isnull(cessamt,0)) amt,cessoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid  group by h.invid,h.gstid , cessoutputacid )
		
 declare @trntype INT,@voucherdate datetime
 update #tempvouch set coid=h.coid,boid=h.boid,userid=h.userid,voucherno=@voucherno,voucherdate=h.invdate,
	vouchertype='J',vouchercategory='S',narration='Vide Sale Bill No. '+ltrim(@invno)+' Dtd. '+ ltrim(invdate),refid=@invid,isconfirm=1,trntype=@trntype
	,fyid=h.fyid,createdby=h.userid,createdon=getdate(), oppositeacid= case when drcr='C' then (select top 1 (accountid) from #tempvouch where drcr='D')
	 else (select top 1 (accountid) from #tempvouch where drcr='C') end from [db_sop].[hdr_sale] h where h.id=@invid

	 insert into [db_accounts].[voucher] ( coid, boid, userid, voucherno, rowno, voucherdate, voucheramount, vouchertype, vouchercategory, accountid, drcr, narration, refid, isconfirm, trntype, oppositeacid, fyid, subledgercode, cencaled, createdby, 
                         createdon)(
						 select  coid, boid, userid, voucherno, ROW_NUMBER() OVER(ORDER BY drcr ASC) AS Rowno, voucherdate, voucheramount, vouchertype, vouchercategory, accountid, drcr, narration, refid, isconfirm, 5, oppositeacid, fyid, subledgercode, cencaled, createdby, 
                         createdon from #tempvouch where voucheramount>0)


	
	 select top 1 @id1=id, @invid=id,@invno=invno   from [db_sop].[hdr_sale] where id >@id and invno>0 and fyid=1 order by id

			
			set @id = @id1
			select @id1 = max(id) from [db_sop].[hdr_sale] where invno>0 and fyid=1 
			if (@id=@id1)
			begin 
			select @id1 = max(id) from [db_sop].[hdr_sale] where invno>0 and fyid=1 
			end
			else  
			begin
			IF (@id>0) GOTO startagain;
			end 
	end			
 	

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

--exec [db_sop].[pr_vouchergenerationforsale] 1,5, 'Insert'
CREATE PROCEDURE [db_sop].[pr_vouchergenerationforsale]  
@invid bigint,
@invno bigint,
@statementtype VARCHAR(50)
AS
BEGIN
	SET NOCOUNT ON;
	
IF OBJECT_ID('tempdb..#tempvouch') IS NOT NULL DROP TABLE #tempvouch
	create table #tempvouch
	(
coid	int,
boid	int,
userid	int,
voucherno	bigint,
rowno	int,
voucherdate	date,
voucheramount	decimal(18, 2),
vouchertype	char(1),
vouchercategory	char(1),
accountid	bigint,
drcr	char(1),
narration	varchar(500),
refid	bigint,
isconfirm	bit,
trntype	int,
oppositeacid	bigint,
fyid	int,
subledgercode	varchar(2),
cencaled	bit,
createdby	bigint,
createdon	datetime,
);

	
	if (@invno >0)
		begin
			startagain:		
	declare @voucherno bigint 
	select @voucherno= isnull(max(voucherno),0)+1 from [db_accounts].[voucher] where vouchercategory='S' and trntype=5
	print @invid 
	
	delete from #tempvouch
insert into #tempvouch (voucheramount,accountid, drcr)(
select isnull(invamt,0) amt,a.id as acid,'D' as type from	[db_sop].[hdr_sale]	h join [db_accounts].[accountHeads] a
on h.customerid=a.partyid where h.id=@invid
union all
select sum(isnull(basicamount,0)) amt,saleacid as ACID,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , saleacid  
union all
select sum(isnull(igstamt,0)) amt,igstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , igstoutputacid 
union all
select sum(isnull(cgstamt,0)) amt,cgstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , cgstoutputacid 
union all
select sum(isnull(sgstamt,0)) amt,sgstoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid group by h.invid,h.gstid , sgstoutputacid 
union all
select sum(isnull(cessamt,0)) amt,cessoutputacid,'C' as type from	[db_sop].[dtl_sale]	h inner join 
[db_mm].[mst_gst] g on h.gstid=g.gstid where h.invid=@invid  group by h.invid,h.gstid , cessoutputacid )
		
 declare @trntype INT,@voucherdate datetime
 update #tempvouch set coid=h.coid,boid=h.boid,userid=h.userid,voucherno=@voucherno,voucherdate=h.invdate,
	vouchertype='J',vouchercategory='S',narration='Vide Sale Bill No. '+ltrim(@invno)+' Dtd. '+ ltrim(invdate),refid=@invid,isconfirm=1,trntype=@trntype
	,fyid=h.fyid,createdby=h.userid,createdon=getdate(), oppositeacid= case when drcr='C' then (select top 1 (accountid) from #tempvouch where drcr='D')
	 else (select top 1 (accountid) from #tempvouch where drcr='C') end from [db_sop].[hdr_sale] h where h.id=@invid
	 select * from #tempvouch
	 insert into [db_accounts].[voucher] ( coid, boid, userid, voucherno, rowno, voucherdate, voucheramount, vouchertype, vouchercategory, accountid, drcr, narration, refid, isconfirm, trntype, oppositeacid, fyid, subledgercode, cencaled, createdby, 
                         createdon)(
						 select  coid, boid, userid, voucherno, ROW_NUMBER() OVER(ORDER BY drcr ASC) AS Rowno, voucherdate, voucheramount, vouchertype, vouchercategory, accountid, drcr, narration, refid, isconfirm, 5, oppositeacid, fyid, subledgercode, cencaled, createdby, 
                         createdon from #tempvouch where voucheramount>0)

	end			
 	

end
GO
/****** Object:  StoredProcedure [dbo].[pr_createsinglecolumnmaster_table]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--drop table db_mm.test
--exec [dbo].[pr_createsinglecolumnmaster_table] 'dbo.test2'
CREATE procedure [dbo].[pr_createsinglecolumnmaster_table]
@tablename varchar(100),
@menuname varchar(100),
@menulink varchar(50)
as

BEGIN
declare @sql nvarchar(max)
 set @sql='CREATE TABLE '+@tablename+'(
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](250) NOT NULL,
	[coid] [int] NULL,
	[boid] [int] NULL,
	[isactive] [bit] NOT NULL,
	[createdby] [int] NOT NULL,
	[createdon] [datetime] NOT NULL,
	[modifiedby] [int] NULL,
	[modifiedon] [datetime] NULL,
 CONSTRAINT [PK_'+@tablename+'] PRIMARY KEY CLUSTERED 
(
	[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]



ALTER TABLE '+@tablename+' ADD  DEFAULT ((0)) FOR [coid]


ALTER TABLE '+@tablename+' ADD  DEFAULT ((0)) FOR [boid]

ALTER TABLE '+@tablename+' ADD  DEFAULT ((0)) FOR [createdby]

ALTER TABLE '+@tablename+'  ADD  DEFAULT ((getdate())) FOR [createdon]

ALTER TABLE '+@tablename+' ADD  DEFAULT ((1)) FOR [isactive]


ALTER TABLE '+@tablename+' ADD  DEFAULT ((0)) FOR [modifiedby]'

exec sp_executesql @sql

insert into [db_general].[erp_modules_functionalities] 
( boid, coid, moduleid, functionality, parentid, orderno, srcversionno, dbversion, srcupdatedon, dbupdatedon, menuname, menulink, isactive, createdby, createdon)
 values (1,1,8,@menuname,0,0,1,1,GETDATE(),GETDATE(),@menuname,'/single-master/'+@menulink,1,1,GETDATE())
 
 insert into [db_masters].[rcd_singlecolumn] 
( boid, coid, type, columnname, fromname, tablename, url, isactive, createdby, createdon)
 values (1,1,@menulink,'name',@menuname,@tablename,'/single-master/'+@menulink,1,1,GETDATE())
END



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

CREATE procedure [dbo].[pr_TableCleanup]
as

--Code starts here for table cleanup--
DECLARE @myCursor cursor;
DECLARE @tableName char(100),
@sql char(300)

BEGIN
  SET @myCursor = CURSOR FOR
        SELECT tablename 
        FROM [db_general].[tablename_needto_empty]

  OPEN @myCursor
  FETCH NEXT FROM @myCursor
  INTO @tableName

  WHILE @@FETCH_STATUS = 0
        BEGIN
              SET @sql = 'delete FROM ' + rtrim(@tableName )
              EXEC (@sql)
              FETCH NEXT FROM @myCursor INTO @tableName             
        END   
  CLOSE @myCursor
  DEALLOCATE @myCursor
END

GO
/****** Object:  StoredProcedure [dbo].[test]    Script Date: 1/15/2020 8:31:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create PROCEDURE [dbo].[test]  
   as
BEGIN 
 DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
	@coid int
select @cols = STUFF((SELECT ',' + QUOTENAME(paramname) 
                   from [db_mm].[hdr_reportfilter_param]
                    group by paramname, id
                    order by id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')		
 set @query = N'SELECT ' + @cols + N' from 
             (
                select paravalue, paramname
                from [db_mm].[hdr_reportfilter_param] 
            ) x
            pivot 
            (
                max(paravalue)
                for paramname in (' + @cols + N')
            ) p '			  
 exec sp_executesql @query; 
END
GO
