
/****** Object:  StoredProcedure [dbo].[DeleteWarehouseAndRelations]    Script Date: 2023/01/16 02:11:05 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:		Azimi
-- Create date: 
-- Description:	
-- select * from Accwarehouse
-- =============================================
ALTER PROCEDURE [dbo].[DeleteWarehouseAndRelations] 
	@WarehouseID bigint,
	@OnlyRelation bit = 0,
	@wNotFactor bit,
	@wNotSellFactor bit,
	@FromFactorID bigint = 0
AS
BEGIN
	if @WarehouseID <= 0 
		return 

	SET NOCOUNT ON;
	
	BEGIN TRANSACTION
	
	DECLARE @ID as BIGINT

	if @wNotFactor = 0
	BEGIN
		SELECT @ID=FormID from AccWarehouse where FromForm in (0,1) and ID = @WarehouseID
		IF @ID > 0 and @ID <> @FromFactorID
		BEGIN
			print 'DeleteFactorAndRelations @FactorID='+Str(@ID)
			EXEC DeleteFactorAndRelations @FactorID = @ID, @OnlyRelation=0 , @fNotSellFactor = @wNotSellFactor, @fNotWare=1
		END
		UPDATE AccWarehouse SEt FormID=0 where FromForm in (0,1) and ID = @WarehouseID
	END

	SELECT @ID=OutID from AccWarehouse where ID = @WarehouseID
	IF @ID > 0 and @ID <> @WarehouseID
	BEGIN
		print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
		EXEC DeleteWarehouseAndRelations @WarehouseID = @ID, @OnlyRelation=0, @wNotFactor=@wNotFactor, @wNotSellFactor=@wNotSellFactor
	END

	Delete AccDocItem where RelationTable=9 and RelationTableID in (select ID from AccWarehouseDetails where WarehouseID = @WarehouseID)
--؟	Delete AccDocItem where RelationTable=10 and RelationTableID = @WarehouseID

	if @OnlyRelation=0
	BEGIN
		Delete AccWarehouseDelivery where WareDetailsID in (select ID from AccWarehouseDetails where WarehouseID = @WarehouseID)
		Delete AccWarehouseDetails where WarehouseID = @WarehouseID
		Delete AccWarehouse where ID = @WarehouseID
	END
	ELSe
	BEGIN
		update AccWarehouseDetails SET DocItemID=0 WHERE WarehouseID = @WarehouseID
		update AccWarehouse SET FormID=0 where ID = @WarehouseID
		--update AccWarehouse SET InOROut = InOROut+100 where ID = @WarehouseID and InOROut < 100
	END

	COMMIT

END