Create PROCEDURE [dbo].[Delete_Mandeh_Data]
AS
BEGIN
    -----(وايجاد مجدد آنها TmpOver_Under_Row - TmpOver_Under_Factor - TmpHeadH - TmpHavaleh - TmpSerial_File - TmpExp_File حذف لينكهاي جداول )--------------------------------------

    EXEC dbo.TruncateTableAndDropCreateRelations;
    TRUNCATE TABLE dbo.Karkerd;
    TRUNCATE TABLE dbo.Stock;
    TRUNCATE TABLE dbo.TmpAcc_Cheqe_link;
    TRUNCATE TABLE dbo.Acc_Cheqe_Link;
    TRUNCATE TABLE dbo.Tbl_RandomLottery;
    TRUNCATE TABLE dbo.History_Delete_HeadGh;
    TRUNCATE TABLE dbo.History_Delete_Ghest;
    TRUNCATE TABLE dbo.History_Delete_Sanad;
    TRUNCATE TABLE dbo.History_Detail_Factors;

    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'UserHistory')
        TRUNCATE TABLE dbo.UserHistory;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'WarehouseHistory')
        TRUNCATE TABLE dbo.WarehouseHistory;
    TRUNCATE TABLE dbo.TblQueue;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'Tmp_Over_Under_Factor_Cash'
    )
        TRUNCATE TABLE dbo.Tmp_Over_Under_Factor_Cash;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'Tmp_Over_Under_Factor_Drug'
    )
        TRUNCATE TABLE dbo.Tmp_Over_Under_Factor_Drug;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'Tmp_Over_Under_Row_Drug'
    )
        TRUNCATE TABLE dbo.Tmp_Over_Under_Row_Drug;

    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'EShopTablesChanges')
        TRUNCATE TABLE dbo.EShopTablesChanges;


    --*************************************************************************************
    DELETE FROM ClubCreditSetting
    WHERE (IsActive = 0)
          OR (EndDate < GETDATE());
    DELETE FROM ClubDetailScore
    WHERE (ISNULL(PriceUse, 0) > 0)
          OR (EndDate < GETDATE());
    DELETE FROM dbo.Tbl_ScoreClub
    WHERE Autoid NOT IN
          (
              SELECT ScoreId FROM dbo.ClubDetailScore
          );
    --EXEC dbo.CorrectExpirationStock 
    ----------(حذف وجوه نقد و همه چكها به غي از وصول نشده - درجريان وصول - پاس نشده و هدرهاي بدون ديتيل)-------------------------------------------------------------
    DELETE FROM Cheqe
    WHERE CH_Pass NOT IN ( '0', '3', '10' )
          OR Ch_Pass_New = '20';
    DELETE FROM Cheqe
    WHERE Ch_no IS NULL;
    DELETE FROM HeadC
    WHERE NOT EXISTS
    (
        SELECT * FROM Cheqe WHERE Id_Cheqe = HeadC.Id_Cheqe
    );
    UPDATE HeadC
    SET Id_Havaleh = 0,
        Id_Sanad = 0;

    IF EXISTS
    (
        SELECT *
        FROM dbo.syscolumns
        WHERE id = OBJECT_ID('Cheqe')
              AND name = 'PreGuid_Cheqe'
    )
    BEGIN
        ALTER TABLE [dbo].[Cheqe] DROP COLUMN PreGuid_Cheqe;
        ALTER TABLE Cheqe ADD PreGuid_Cheqe UNIQUEIDENTIFIER NULL;
    END;

    UPDATE HeadC
    SET Guy_Code = Guy_Bank
    WHERE (
              Guy_Code IS NULL
              OR Guy_Code = ''
          )
          AND
          (
              Guy_Bank IS NOT NULL
              AND Guy_Bank <> ''
          );
    -------------------------------------------------------------------------------------------
    IF EXISTS
    (
        SELECT *
        FROM dbo.sysobjects
        WHERE id = OBJECT_ID(N'[dbo].[TU_Account]')
              AND OBJECTPROPERTY(id, N'IsTrigger') = 1
    )
        ALTER TABLE Account DISABLE TRIGGER TU_Account;

    UPDATE Account
    SET Bedeh = 0,
        Bestan = 0;

    IF EXISTS
    (
        SELECT *
        FROM dbo.sysobjects
        WHERE id = OBJECT_ID(N'[dbo].[TU_Account]')
              AND OBJECTPROPERTY(id, N'IsTrigger') = 1
    )
        ALTER TABLE Account ENABLE TRIGGER TU_Account;

    -------------------------------------------------------------------------------------------
    TRUNCATE TABLE History_Price;
    UPDATE Anbar
    SET Mojodi = 0,
        Exit_Fa = 0,
        Resive_Fa = 0;

    ------------------حذف اقساطي که قسط آنها تمام شده و صفر کردن شماره فاکتور هاي باقيمانده----------------------------------------------------------------------------------
    DELETE FROM Ghest
    WHERE Bedeh = 0
          AND FlagTypeAghsat = '0';
    DELETE FROM HeadGh
    WHERE T_Bedeh = T_Bestan;
    UPDATE Ghest
    SET NumberFactor = 0
    WHERE NumberFactor <> '0';


    DECLARE @IdGhest BIGINT;
    DECLARE @iCount INT;
    DECLARE Cursor_Delete CURSOR LOCAL FOR SELECT Id_Ghest FROM HeadGh;
    OPEN Cursor_Delete;
    FETCH NEXT FROM Cursor_Delete
    INTO @IdGhest;
    WHILE @@Fetch_Status = 0
    BEGIN
        DELETE FROM HeadGh
        WHERE Id_Ghest =
        (
            SELECT Id_Ghest
            FROM
            (
                SELECT COUNT(*) ICount,
                       Ghest.Id_Ghest,
                       CASE
                           WHEN Ghest.FlagTypeAghsat = '1' THEN
                           (
                               SELECT COUNT(FlagTypeAghsat)
                               FROM Ghest
                               WHERE Id_Ghest = @IdGhest
                                     AND FlagTypeAghsat = '1'
                           )
                       END AS CountTypeFlag
                FROM HeadGh
                    INNER JOIN Ghest
                        ON Ghest.Id_Ghest = HeadGh.Id_Ghest
                WHERE Ghest.Id_Ghest = @IdGhest
                GROUP BY Ghest.Id_Ghest,
                         Ghest.FlagTypeAghsat
            ) AS table1
            GROUP BY Id_Ghest
            HAVING SUM(ICount) = SUM(ISNULL(CountTypeFlag, 0))
        );
        FETCH NEXT FROM Cursor_Delete
        INTO @IdGhest;
    END;
    CLOSE Cursor_Delete;
    DEALLOCATE Cursor_Delete;


    -------------------------------------------(Amval va Daraei)--------------------------------------
    UPDATE Capital
    SET Es_Cash = ISNULL(Es_Cash, 0) + ISNULL(Es_Current_Year, 0);
    UPDATE Capital
    SET CurPrice = ISNULL(CurPrice, 0) - ISNULL(Es_Current_Year, 0);
    UPDATE Capital
    SET Es_Current_Year = 0;
    -------------------------------------------(Amval va Daraei)--------------------------------------

    -------------------------------------------(DrugStore)--------------------------------------------------
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'Last_Dumy')
        TRUNCATE TABLE Last_Dumy;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'tblekhtetam')
        TRUNCATE TABLE TblEkhtetam;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'IRI_Prescriptions')
        TRUNCATE TABLE IRI_Prescriptions;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'IRI_InsuredContracts')
        TRUNCATE TABLE IRI_InsuredContracts;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'HIO_Prescriptions')
        TRUNCATE TABLE HIO_Prescriptions;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'HIX_Prescriptions')
        TRUNCATE TABLE HIX_Prescriptions;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'History_Delete_DrugH')
        TRUNCATE TABLE dbo.History_Delete_DrugH;
    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'History_Delete_DrugHavaleh'
    )
        TRUNCATE TABLE dbo.History_Delete_DrugHavaleh;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'History_TmpDrugH')
    BEGIN
        IF (EXISTS
        (
            SELECT name
            FROM sysobjects
            WHERE name = 'FK_History_TmpDrugHavaleh_History_TmpDrugH'
        )
           )
            ALTER TABLE dbo.History_TmpDrugHavaleh
            DROP CONSTRAINT FK_History_TmpDrugHavaleh_History_TmpDrugH;
        TRUNCATE TABLE dbo.History_TmpDrugH;
    END;
    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'History_TmpDrugHavaleh'
    )
    BEGIN
        TRUNCATE TABLE dbo.History_TmpDrugHavaleh;
        ALTER TABLE dbo.History_TmpDrugHavaleh
        ADD CONSTRAINT FK_History_TmpDrugHavaleh_History_TmpDrugH
            FOREIGN KEY (Id_Havaleh)
            REFERENCES dbo.History_TmpDrugH (Id_Havaleh) ON DELETE CASCADE;
    END;
    --------------------------------------------------------------------------------------------------------------
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TrackingHeader')
        TRUNCATE TABLE TrackingHeader;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TrackingDetail')
        TRUNCATE TABLE TrackingDetail;
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TrackingPrescription')
        TRUNCATE TABLE TrackingPrescription;
    ----------------------------------------------------------------------------------------------------------------- IHIO 
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'IHIOPrescription')
    BEGIN
        IF (EXISTS
        (
            SELECT name
            FROM sysobjects
            WHERE name = 'FK_IHIOPrescriptionDetail_IHIOPrescription'
        )
           )
            ALTER TABLE dbo.IHIOPrescriptionDetail
            DROP CONSTRAINT FK_IHIOPrescriptionDetail_IHIOPrescription;
        IF EXISTS (SELECT name FROM sysobjects WHERE name = 'IHIOPrescription')
            TRUNCATE TABLE dbo.IHIOPrescription;
        IF EXISTS
        (
            SELECT name
            FROM sysobjects
            WHERE name = 'IHIOPrescriptionDetail'
        )
            TRUNCATE TABLE dbo.IHIOPrescriptionDetail;
        IF EXISTS (SELECT name FROM sysobjects WHERE name = 'IHIOActivityHistory')
            TRUNCATE TABLE dbo.IHIOActivityHistory;
        ALTER TABLE dbo.IHIOPrescriptionDetail
        ADD CONSTRAINT FK_IHIOPrescriptionDetail_IHIOPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.IHIOPrescription (Id) ON DELETE CASCADE;
    END;
    ----------------------------------------------------------------------------------------------------------------- IHIO
    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'FK_IHIOSavedPresciptionDetail_IHIOSavedPrescription'
    )
    BEGIN
        ALTER TABLE dbo.IHIOSavedPrescriptionDetail
        DROP CONSTRAINT FK_IHIOSavedPresciptionDetail_IHIOSavedPrescription;
        TRUNCATE TABLE dbo.IHIOSavedPrescription;
        TRUNCATE TABLE dbo.IHIOSavedPrescriptionDetail;

        ALTER TABLE dbo.IHIOSavedPrescriptionDetail
        ADD CONSTRAINT FK_IHIOSavedPresciptionDetail_IHIOSavedPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.IHIOSavedPrescription (Id) ON DELETE CASCADE;
    END;
    ---------------------------------------------------------------------------------------------------------------------- EPM
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'EPMDrugCodeError')
        TRUNCATE TABLE dbo.EPMDrugCodeError;

    ---------------------------------------------------------------------------------------------------------------------- TAMIN

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'FK_TaminUIDInfo_TaminPrescriptionDetail'
    )
    BEGIN
        ALTER TABLE dbo.TaminPrescriptionDetailUID
        DROP CONSTRAINT FK_TaminUIDInfo_TaminPrescriptionDetail;
        TRUNCATE TABLE dbo.TaminPrescriptionDetailUID;
    END;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'FK_TaminSavedPrescriptionDetail_TaminSavedPrescription'
    )
    BEGIN

        ALTER TABLE dbo.TaminSavedPrescriptionDetail
        DROP CONSTRAINT FK_TaminSavedPrescriptionDetail_TaminSavedPrescription;
        TRUNCATE TABLE dbo.TaminSavedPrescription;
        TRUNCATE TABLE dbo.TaminSavedPrescriptionDetail;

        ALTER TABLE dbo.TaminSavedPrescriptionDetail
        ADD CONSTRAINT FK_TaminSavedPrescriptionDetail_TaminSavedPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.TaminSavedPrescription (Id) ON DELETE CASCADE;
    END;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'FK_TaminPrescriptionDetail_TaminPrescription'
    )
    BEGIN
        ALTER TABLE dbo.TaminPrescriptionDetail
        DROP CONSTRAINT FK_TaminPrescriptionDetail_TaminPrescription;
        TRUNCATE TABLE dbo.TaminPrescription;
        TRUNCATE TABLE dbo.TaminPrescriptionDetail;

        ALTER TABLE dbo.TaminPrescriptionDetail
        ADD CONSTRAINT FK_TaminPrescriptionDetail_TaminPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.TaminPrescription (Id) ON DELETE CASCADE;
    END;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'FK_TaminSavedPrescriptionDetail_TaminSavedPrescription'
    )
    BEGIN
        ALTER TABLE dbo.TaminSavedPrescriptionDetail
        DROP CONSTRAINT FK_TaminSavedPrescriptionDetail_TaminSavedPrescription;
        TRUNCATE TABLE dbo.TaminSavedPrescription;
        TRUNCATE TABLE dbo.TaminSavedPrescriptionDetail;

        ALTER TABLE dbo.TaminSavedPrescriptionDetail
        ADD CONSTRAINT FK_TaminSavedPrescriptionDetail_TaminSavedPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.TaminSavedPrescription (Id) ON DELETE CASCADE;
    END;

    IF EXISTS
    (
        SELECT name
        FROM sysobjects
        WHERE name = 'TaminPrescriptionDetailUID'
    )
    BEGIN
        ALTER TABLE dbo.TaminPrescriptionDetailUID
        ADD CONSTRAINT FK_TaminUIDInfo_TaminPrescriptionDetail
            FOREIGN KEY (PrescriptionDetailId)
            REFERENCES dbo.TaminPrescriptionDetail (Id) ON DELETE CASCADE;
    END;
    ---------------------------------------------------------------------------------------------------------------TTAC
    IF EXISTS
    (
        SELECT 1
        FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE f
        WHERE f.CONSTRAINT_NAME = 'FK_TTACPrescriptionDetailUID_TTACPrescriptionDetail'
    )
    BEGIN
        ALTER TABLE dbo.TTACPrescriptionDetailUID
        DROP CONSTRAINT FK_TTACPrescriptionDetailUID_TTACPrescriptionDetail;
        TRUNCATE TABLE dbo.TTACPrescriptionDetailUID;
    END;

    IF EXISTS
    (
        SELECT 1
        FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE f
        WHERE f.CONSTRAINT_NAME = 'FK_TTACPrescriptionDetail_TTACPrescription'
    )
    BEGIN
        ALTER TABLE dbo.TTACPrescriptionDetail
        DROP CONSTRAINT FK_TTACPrescriptionDetail_TTACPrescription;
        TRUNCATE TABLE dbo.TTACPrescription;
        TRUNCATE TABLE dbo.TTACPrescriptionDetail;

        ALTER TABLE dbo.TTACPrescriptionDetail
        ADD CONSTRAINT FK_TTACPrescriptionDetail_TTACPrescription
            FOREIGN KEY (PrescriptionId)
            REFERENCES dbo.TTACPrescription (Id) ON DELETE CASCADE;
    END;

    IF EXISTS
    (
        SELECT 1
        FROM INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE f
        WHERE f.CONSTRAINT_NAME = 'TTACPrescriptionDetailUID'
    )
    BEGIN
        ALTER TABLE dbo.TTACPrescriptionDetailUID
        ADD CONSTRAINT FK_TTACPrescriptionDetailUID_TTACPrescriptionDetail
            FOREIGN KEY (PrescriptionDetailId)
            REFERENCES dbo.TTACPrescriptionDetail (Id) ON DELETE CASCADE;
    END;

    -----------------------------------------------------------------------------------------------------------------
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'TblUMDrugHavaleh')
        TRUNCATE TABLE TblUMDrugHavaleh;
    --------------------------------------------------------------------------------------------------------
    IF EXISTS (SELECT name FROM sysobjects WHERE name = 'UserShiftWork')
        DELETE FROM UserShiftWork;
END;