/****** Object:  StoredProcedure [dbo].[DeleteFactorAndRelations]    Script Date: 2023/01/16 02:12:19 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:		Azimi
-- Create date: s
-- Description:	
-- =============================================
ALTER PROCEDURE [dbo].[DeleteFactorAndRelations] 
	@FactorID bigint,
	@OnlyRelation bit = 0,
	@fNotWare bit,
	@fNotSellFactor bit
AS
BEGIN
	if @FactorID <= 0 
		return 	SET NOCOUNT ON;
	
	BEGIN TRANSACTION

	IF CURSOR_STATUS('global','FactorCursor')>=-1
		DEALLOCATE FactorCursor

	DECLARE @ID as BIGINT

	if @fNotWare=0
	BEGIN
		DECLARE FactorCursor CURSOR FOR select WareOutID from AccFactor where ID = @FactorID
		Open FactorCursor
	
		FETCH NEXT FROM FactorCursor INTO @ID
		WHILE @@FETCH_STATUS = 0 
		BEGIN
			print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
			EXEC DeleteWarehouseAndRelations @WarehouseID=@ID, @FromFactorID = @FactorID, @wNotFactor=1, @wNotSellFactor=@fNotSellFactor
			FETCH NEXT FROM FactorCursor INTO @ID
		END
		CLOSE FactorCursor
		DEALLOCATE FactorCursor

		DECLARE WareCursor CURSOR FOR select ID from AccWarehouse where FromForm in (0,1) AND FormID = @FactorID
		Open WareCursor
		FETCH NEXT FROM WareCursor INTO @ID
		WHILE @@FETCH_STATUS = 0 
		BEGIN
			print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
			EXEC DeleteWarehouseAndRelations @WarehouseID=@ID, @FromFactorID = @FactorID, @wNotFactor=1, @wNotSellFactor=@fNotSellFactor
			FETCH NEXT FROM WareCursor INTO @ID
		END
		CLOSE WareCursor
		DEALLOCATE WareCursor
	END


	Delete AccDocItem where RelationTable=12 and RelationTableID in (select id from AccFactorDetail where FactorID = @FactorID)

	if @OnlyRelation=0
	BEGIN
		Delete AccFactorDetail where  FactorID = @FactorID
		Delete AccFactor where ID = @FactorID
	END
	ELSe
	BEGIN
		update AccFactorDetail SET DocItemID=0 WHERE FactorID = @FactorID
		update AccFactor SET WareOutID=0 where ID = @FactorID
		--update AccFactor SET [Type] = [Type]+100 where ID = @FactorID and [Type] < 100
	END

	COMMIT

END