/****** Object:  StoredProcedure [dbo].[DeleteWarehouseAndRelations]    Script Date: 17/11/2022 10:05:32 ب.ظ ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

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

	SET NOCOUNT ON;
	
	BEGIN TRANSACTION
	
	DECLARE @ID as BIGINT
	SELECT @ID=FormID from AccWarehouse where FromForm = 0 and ID = @WarehouseID
	IF @ID > 0 and @ID <> @FromFactorID
	BEGIN
		print 'DeleteWarehouseAndRelations @WarehouseID='+Str(@ID)
		EXEC DeleteFactorAndRelations @FactorID = @ID, @OnlyRelation =@OnlyRelation 
	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 =@OnlyRelation 
	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