BLVCKFX
3/11/2020 - 6:59 PM

Delete customer voucher

Delete customer voucher.#SADA => RENDeleteCustVoucherRENDeleteCustVoucher.PNG

// This is a framework class. Customizing this class may cause problems with future upgrades to the software.
class RENDeleteCustVoucher extends RunBaseBatch
{
    // Packed variables
    TransDate               transDate;
    Voucher                 voucher;
    DocumentNum             documentNum;
    NoYesId                 recalcAccount;
    AccountNum              accountNum;
    boolean                 isInvoice;
    LedgerJournalNameId     JournalName;

    NumberSequenceGroupID   NumberSequenceGroup;
    TaxBookRecId            taxBookRecId;
    TaxBookSectionRecId     taxBookSectionRecId;

    // Dialog fields
    DialogField     dlgVoucher;
    DialogField     dlgTransDate;
    DialogField     dlgRecalcAccount;
    DialogField     dlgJournalName;

    #define.CurrentVersion(4)
    #define.Version1(4)
    #localmacro.CurrentList
        transDate,
        voucher,
        documentNum,
        recalcAccount,
        AccountNum,
        isInvoice,
        NumberSequenceGroup,
        JournalName
    #endmacro
}


public boolean allowSaveLast()
{
    boolean ret;

    ret = false;

    return ret;
}


/// <summary>
///    Indicates whether the class is shown in the list of <c>Journal</c> types.
/// </summary>
/// <returns>
///    true if the class is shown in the list of <c>Journal</c> types; otherwise, false.
/// </returns>
/// <remarks>
///    A class that can be used in a batch journal is a class where the same parameters can be used
///    repeatedly. The dialog box can be shown and the parameters can be changed, but parameters of some
///    classes might build on data that is only valid for a short time. Running a class two times with the
///    same parameters is not always possible. If the <c>RunBaseBatch.canGoBatch</c> method is false, this
///    method will not have any effect.
/// </remarks>
public boolean canGoBatchJournal()
{
    return false;
}


private void Delete()
{
    custInvoiceJour                     custInvoiceJour;
    CustInvoiceTrans                    CustInvoiceTrans;
    CustInvoiceSalesLink                CustInvoiceSalesLink;

    SourceDocumentLine                  SourceDocumentLine;
    CustInvoicePackingSlipQuantityMatch CustInvoicePackingSlipQuantityMatch;

    custBillOfExchangeInvoice           custBillOfExchangeInvoice;
    custBillOfExchangeInvoice           custBillOfExchangeInvoice_T;
    custBillOfExchangeJour              custBillOfExchangeJour;

    CustPackingSlipTrans                CustPackingSlipTrans;

    salesTable                          salesTable;
    salesline                           salesline;

    shipCarrierShipmentInvoice          shipCarrierShipmentInvoice;
    salesShippingStat                   salesShippingStat;

    inventReportDimHistory              inventReportDimHistory;

    InventTransOrigin                   InventTransOrigin, InventTransOriginReturn;
    InventTrans                         InventTrans, inventTransReturn;
    inventTransPosting                  inventTransPosting;

    inventSettlement                    inventSettlement;
    R_ADAAgreementDetails               tileAgreementDetails;
    R_ADAComSalesDetails                tileComSalesDetails;

    // ALT_SC_20160122_CommissionPatch Begin
    R_ADAComCommissionTrans             tileComCommissionTrans;
    // ALT_SC_20160122_CommissionPatch End
    // ALT_SC_20161201_DelVoucher Begin
    Boolean                             WithTrans = false;
    // ALT_SC_20161201_DelVoucher End
    //ALT_LR_20180214_RenDeleteCustPackingMatc
    container                            CustPackRecIDMatch;
    //ALT_LR_20180214_RenDeleteCustPackingMatc

    ;

    unchecked(Uncheck::TableSecurityPermission)
    {

        while select forupdate custInvoiceJour
        where custInvoiceJour.LedgerVoucher == voucher
           && custInvoiceJour.InvoiceDate   == transDate
        {

            isInvoice           =   true;
            accountnum          =   custInvoiceJour.InvoiceAccount;
            NumberSequenceGroup =   custInvoiceJour.numberSequenceGroup;
            documentNum         =   custInvoiceJour.InvoiceId;

            while select forupdate CustInvoiceTrans
            where CustInvoiceTrans.InvoiceId == custInvoiceJour.InvoiceId
               && CustInvoiceTrans.SalesId   == custInvoiceJour.SalesId
               && CustInvoiceTrans.InvoiceDate==transDate

            {
                // ALT_SC_20161201_DelVoucher Begin
                WithTrans = false;
                // ALT_SC_20161201_DelVoucher End

                setprefix("InventTrans");

                while select  InventTransOrigin
                        where InventTransOrigin.InventTransId   == CustInvoiceTrans.InventTransId   &&
                              InventTransOrigin.ItemId          == CustInvoiceTrans.ItemId

                {
                    // ALT_SC_20161201_DelVoucher Begin
                    WithTrans = true;
                    // ALT_SC_20161201_DelVoucher End

                    while select forupdate inventTrans
                      where inventTrans.Voucher             == voucher
                         && inventTrans.InventTransOrigin   == InventTransOrigin.RecId
                         && inventTrans.InvoiceId           == documentNum
                         && inventTrans.DateFinancial       == transDate
                         && (
                            (inventTrans.Statusissue   == statusissue::Sold && inventTrans.StatusReceipt   == statusreceipt::None)      ||
                            (inventTrans.Statusissue   == statusissue::None && inventTrans.StatusReceipt   == statusreceipt::Purchased)
                            )
                         && inventTrans.PackingSlipId == ""
                    {
                        if (InventTransOrigin.ReferenceCategory == InventTransType::Sales &&
                            InventTrans.InvoiceReturned                                   &&
                            InventTrans.MarkingRefInventTransOrigin                       &&
                            inventTrans.StatusReceipt == statusreceipt::Purchased)
                        {
                            while select forupdate inventTransReturn
                                where inventTransReturn.InventTransOrigin == InventTrans.MarkingRefInventTransOrigin
                                   && inventTransReturn.Qty               == -InventTrans.Qty
                                   && inventTransReturn.StatusIssue       == StatusIssue::Sold
                                   exists join InventTransOriginReturn
                                    where  InventTransOriginReturn.RecId == inventTransReturn.InventTransOrigin
                                       &&  InventTransOriginReturn.ReferenceCategory == InventTransType::InventTransaction
                                       && !InventTransOriginReturn.ReferenceId
                            {
                                inventTransReturn.delete();
                            }

                        }

                        setprefix("SalesLine");

                        while select forupdate salesline
                        where salesline.InventTransId==InventTransOrigin.InventTransId
                        {
                            salesline.RemainSalesPhysical   += salesline.unitConvertInvent2Sales(inventTrans.Qty)*-1;
                            salesline.RemainInventPhysical  += (inventTrans.Qty*-1);

                            if(salesLine.SalesType   ==  salesType::ReturnItem)
                            {
                                salesline.ReturnStatus      = salesline.Scrap ? ReturnStatusLine::Received : ReturnStatusLine::Awaiting;
                                salesline.ReturnClosedDate  = dateNull();
                            }
                            salesline.setSalesStatus();

                            salesline.update();
                            INFOLOG.add(EXCEPTION::Info,"update Sales line " + salesline.salesId +
                                                        " in transaction "   + int642str(salesline.RecId));
                        }

                        inventTrans.delete(NoYes::No,NoYes::No);
                        inventTrans.forceDeleteReturnTransOrigin();
                        INFOLOG.add(EXCEPTION::Info,"Delete no packing inventtrans "  + voucher +
                                                   " in transaction "                + int642str(inventTrans.RecId));
                    }

                    setprefix("InventTrans");

                    while select forupdate inventTrans
                    where inventTrans.Voucher             == voucher
                        && inventTrans.InvoiceId           == documentNum
                        && inventTrans.InventTransOrigin   == InventTransOrigin.RecId
                        && inventTrans.DateFinancial == transDate
                        && (
                        (inventTrans.Statusissue   == statusissue::Sold && inventTrans.StatusReceipt   == statusreceipt::None)      ||
                        (inventTrans.Statusissue   == statusissue::None && inventTrans.StatusReceipt   == statusreceipt::Purchased)
                        )
                        && inventTrans.PackingSlipId != ""

                    {

                        while select CustPackingSlipTrans
                        where CustPackingSlipTrans.PackingSlipId    ==  InventTrans.PackingSlipId   &&
                                CustPackingSlipTrans.InventTransId    ==  InventTransOrigin.InventTransId
                        {
                            delete_from CustInvoicePackingSlipQuantityMatch
                            where CustInvoicePackingSlipQuantityMatch.InvoiceSourceDocumentLine     == CustInvoiceTrans.SourceDocumentLine &&
                                    CustInvoicePackingSlipQuantityMatch.PackingSlipSourceDocumentLine == CustPackingSlipTrans.SourceDocumentLine;
                        }

                        update_recordSet CustPackingSlipTrans
                            setting FullyMatched = NoYes::No
                                where CustPackingSlipTrans.PackingSlipId    == inventTrans.PackingSlipId &&
                                      CustPackingSlipTrans.InventTransId    == InventTransOrigin.InventTransId;

                        inventTrans.CostAmountPosted    =0;
                        inventTrans.CurrencyCode        ="";
                        inventTrans.InvoiceId           ="";
                        inventTrans.Voucher             ="";
                        inventTrans.DateFinancial       =datenull();
                        inventTrans.Statusissue         =statusissue::Deducted;
                        inventTrans.CostAmountStd       =0;
                        inventTrans.CostAmountAdjustment=0;

                        if (inventTrans.InvoiceReturned)
                        {
                            inventTrans.InvoiceReturned         =   noyes::No;
                            inventTrans.StatusReceipt           =   StatusReceipt::Received;
                            inventTrans.StatusIssue             =   StatusIssue::None;
                            inventTrans.CostAmountOperations    =   0;
                        }

                        setprefix("SalesLine");

                        while select forupdate salesline
                        where salesline.InventTransId==InventTransOrigin.InventTransId
                        {

                            salesline.RemainSalesFinancial  += salesline.unitConvertInvent2Sales(inventTrans.Qty)*-1;
                            salesline.RemainInventFinancial += inventTrans.Qty*-1;


                            if(salesline.SalesType   ==  salesType::ReturnItem)
                            {
                                salesline.ReturnStatus      = returnStatusLine::Received;
                                salesline.ReturnClosedDate  = dateNull();
                            }
                            salesline.setSalesStatus();

                            salesline.update();
                            INFOLOG.add(EXCEPTION::Info,"update Sales line " + salesline.salesId +
                                                        " in transaction "   + int642str(salesline.RecId));
                        }


                        inventTrans.update();
                        INFOLOG.add(EXCEPTION::Info,"Updated packing inventtrans " + voucher +
                                                    " in transaction "             + int642str(inventTrans.RecId));

                    }
                }

                setprefix("SalesTable");

                // ALT_SC_20161201_DelVoucher Begin
                if (!WithTrans)
                {
                    while select forupdate salesline
                    where salesline.InventTransId==CustInvoiceTrans.InventTransId
                    {

                        salesline.RemainSalesPhysical   += CustInvoiceTrans.Qty;
                        salesline.RemainInventPhysical  = salesline.calcQtyOrdered(salesline.RemainSalesPhysical);

                        if(salesline.SalesType   ==  salesType::ReturnItem)
                        {
                            salesline.ReturnStatus      = returnStatusLine::Received;
                            salesline.ReturnClosedDate  = dateNull();
                        }

                        salesline.setSalesStatus();

                        salesline.update();

                        INFOLOG.add(EXCEPTION::Info,"update Sales line " + salesline.salesId +
                                                    " in transaction "   + int642str(salesline.RecId));
                    }
                    //ALT_LR_20180214_RenDeleteCustPackingMatc - begin
                    while select forUpdate CustInvoicePackingSlipQuantityMatch where CustInvoicePackingSlipQuantityMatch.InvoiceSourceDocumentLine == CustInvoiceTrans.SourceDocumentLine
                    {
                        update_recordSet CustPackingSlipTrans
                            setting FullyMatched = NoYes::No
                                where CustPackingSlipTrans.SourceDocumentLine    == CustInvoicePackingSlipQuantityMatch.PackingSlipSourceDocumentLine;
                        CustInvoicePackingSlipQuantityMatch.delete();
                    }
                    //ALT_LR_20180214_RenDeleteCustPackingMatc - end
                }
                // ALT_SC_20161201_DelVoucher End

                while select forupdate salesTable
                where salesTable.SalesId==CustInvoiceTrans.OrigSalesId
                {
                    salesTable.DocumentStatus= Documentstatus::PackingSlip;

                    if (salesTable.SalesType  == salesType::ReturnItem &&
                        salesTable.ReturnStatus  == ReturnStatusHeader::Closed)

                    {
                        // ALT_DP_20151130_InvoiceDeleteBugFix - begin
                        // salesTable.ReturnStatus  = ReturnStatusHeader::Open;
                        if (CustInvoiceTrans.salesLine().Scrap)
                            salesTable.ReturnStatus  = ReturnStatusHeader::Open;
                        else
                            salesTable.ReturnStatus  = ReturnStatusHeader::Created;
                        // ALT_DP_20151130_InvoiceDeleteBugFix - end
                    }

                    // ALT_SC_20170211_DeleteVoucherRts Begin
                    salesTable.SAD_RTSIntegrationSynchWithRTS = NoYes::No;
                    // ALT_SC_20170211_DeleteVoucherRts End
                    salesTable.update();

                    INFOLOG.add(EXCEPTION::Info,"update Sales table " + voucher +
                                                " in transaction    " + int642str(salesTable.RecId));

                }

                setprefix("InventReportDimHistory");

                while select forupdate inventReportDimHistory
                where inventReportDimHistory.TransRefId    == voucher
                    && inventReportDimHistory.InventTransId == CustInvoiceTrans.InventTransId
                {

                    inventReportDimHistory.delete();
                    INFOLOG.add(EXCEPTION::Info,"deleted inventreportdimhistory " + voucher +
                                                " in transaction " + int642str(inventReportDimHistory.RecId));
                }

                delete_from tileAgreementDetails
                    where tileAgreementDetails.ReferenceType    ==  R_ADAReferenceType::Invoice      &&
                            TileAgreementDetails.RefID            ==  CustInvoiceTrans.InvoiceId      &&
                            TileAgreementDetails.RefDate          ==  CustInvoiceTrans.InvoiceDate    &&
                            TileAgreementDetails.InventTransId    ==  CustInvoiceTrans.InventTransId;

                delete_from tileComSalesDetails
                    where tileComSalesDetails.R_ADAReferenceType    ==  R_ADAReferenceType::Invoice      &&
                            tileComSalesDetails.R_ADARefID            ==  CustInvoiceTrans.InvoiceId      &&
                            tileComSalesDetails.R_ADARefDate          ==  CustInvoiceTrans.InvoiceDate    &&
                            tileComSalesDetails.R_ADAComInventTransId ==  CustInvoiceTrans.InventTransId;

                setprefix("CustInvoiceTrans");

                CustInvoiceTrans.delete();
                INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                            " in transaction " + int642str(CustInvoiceTrans.RecId));

            }

            setprefix("ShipCarrierShipmentInvoice");

            while select forupdate shipCarrierShipmentInvoice
            where shipCarrierShipmentInvoice.CustInvoiceJourRefRecId == CustInvoiceJour.RecId
            {

                shipCarrierShipmentInvoice.delete();
                INFOLOG.add(EXCEPTION::Info,"deleted ShipCarrierShipmentInvoice " + voucher +
                                            " in transaction " + int642str(shipCarrierShipmentInvoice.RecId));
            }

            setprefix("salesshippingstat");

            while select forupdate salesshippingstat
            where salesshippingstat.InvoiceId   == CustInvoiceJour.InvoiceId
                && salesshippingstat.InvoiceDate == CustInvoiceJour.InvoiceDate
            {

                salesshippingstat.delete();
                INFOLOG.add(EXCEPTION::Info,"deleted salesshippingstat " + voucher +
                                            " in transaction " + int642str(salesshippingstat.RecId));
            }

            //ALT_SC_20160122_CommissionPatch Begin
            setprefix("tileComCommissionTrans");

            while select forupdate tileComCommissionTrans
            where   tileComCommissionTrans.R_ADAComInvoiceId          ==  CustInvoiceJour.InvoiceId      &&
                    tileComCommissionTrans.R_ADAComInvoiceDate        ==  CustInvoiceJour.InvoiceDate    &&
                    tileComCommissionTrans.R_ADAComCustAccount        ==  CustInvoiceJour.InvoiceAccount
            {

                tileComCommissionTrans.delete();
                INFOLOG.add(EXCEPTION::Info,"deleted tileComCommissionTrans " + voucher +
                                            " in transaction " + int642str(tileComCommissionTrans.RecId));
            }
            //ALT_SC_20160122_CommissionPatch End

            setprefix("CustInvoiceJour");

            custInvoiceJour.delete();
            INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                        " in transaction " + int642str(custInvoiceJour.RecId));
        }

    }


    if(this.DeleteLedger(CustInvoiceJour))
    {
        setprefix("CustInvoiceSalesLink");
        while select forupdate CustInvoiceSalesLink
        where CustInvoiceSalesLink.invoiceId  ==voucher
            && CustInvoiceSalesLink.invoiceDate==transDate
        {
            CustInvoiceSalesLink.delete();

            INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + voucher +
                                        " in transaction " + int642str(CustInvoiceSalesLink.RecId));
        }

        setprefix("InventSettlement");

        while select forupdate inventSettlement
        where inventSettlement.Voucher  ==voucher
            && inventSettlement.TransDate==transDate
        {
            inventSettlement.delete();

            INFOLOG.add(EXCEPTION::Info,"Deleted voucher " + voucher +
                                        " in transaction " + int642str(inventSettlement.RecId));
        }


        setprefix("InventTransPosting");

        while select forupdate inventTransPosting
        where inventTransPosting.Voucher  ==voucher
            && inventTransPosting.TransDate==transDate
            && inventTransPosting.InventTransPostingType==InventTransPostingType::Financial

        {
            inventTransPosting.delete();

            INFOLOG.add(EXCEPTION::Info,"Deleted voucher " + voucher +
                                        " in transaction " + int642str(inventTransPosting.RecId));
        }

    }

}


private boolean DeleteLedger(CustInvoiceJour CustInvoiceJour)
{
    custBillOfExchangeInvoice   custBillOfExchangeInvoice;
    custBillOfExchangeInvoice   custBillOfExchangeInvoice_T;
    custBillOfExchangeJour      custBillOfExchangeJour;

    custTrans                   custTrans;
    custTransOpen               custTransOpen;

    taxTrans                    taxTrans;
    taxTransGeneralJournalAccountEntry  taxTransGeneralJournalAccountEntry;
    CosCostTrans                CosCostTrans;
    AssetTrans                  AssetTrans;
    bankAccountTrans            bankAccountTrans;
    ledgerJournalTrans          ledgerJournalTrans;

    NumberSequenceGroupId       NumberSequenceGroupLocal;

    custInvoiceTable            custInvoiceTable;
    custInvoiceLine             custInvoiceLine;
    boolean                     ret = true;

    while select forupdate custBillOfExchangeInvoice
            where custBillOfExchangeInvoice.InvoiceVoucher == voucher
               && custBillOfExchangeInvoice.invoiceDate    == transDate
    {
        while select forupdate custBillOfExchangeJour
        where custBillOfExchangeInvoice.BillOfExchangeId == custBillOfExchangeJour.BillOfExchangeId

        {
            while select forupdate custBillOfExchangeInvoice_T
            where custBillOfExchangeInvoice_T.BillOfExchangeId == custBillOfExchangeJour.BillOfExchangeId

            {

                this.DeleteUpdateLedger(custBillOfExchangeInvoice_T.Voucher,custBillOfExchangeInvoice_T.InvoiceDate);
                /*
                setprefix("LedgerTrans");

                while select forupdate ledgerTrans
                where ledgerTrans.Voucher   == custBillOfExchangeInvoice_T.Voucher
                    && ledgerTrans.TransDate == custBillOfExchangeInvoice_T.InvoiceDate
                {
                    ledgerTrans.delete();

                    INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + _voucher +
                                                " in transaction " + int2str(ledgerTrans.RecId));

                }

                */
                while select forupdate custTrans
                where custTrans.Voucher   == custBillOfExchangeInvoice_T.Voucher
                    && custTrans.TransDate == custBillOfExchangeInvoice_T.InvoiceDate
                {
                    setprefix("CustTransOpen");

                    while  select forupdate custTransOpen
                    where custTransOpen.RefRecId  == custTrans.RecId
                        && custTransOpen.TransDate == custBillOfExchangeInvoice_T.InvoiceDate
                    {
                        custTransOpen.delete();

                        INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                                    " in transaction " + int642str(custTransOpen.RecId));
                    }

                    setprefix("CustTrans");

                    custTrans.delete();
                    INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                                " in transaction " + int642str(custTrans.RecId));
                }

                custBillOfExchangeInvoice_T.delete();

                INFOLOG.add(eXCEPTION::Info,"Deleted Bill Of Exchange jour" + voucher +
                                            " in transaction " + int642str(custInvoiceJour.RecId));
            }
            custBillOfExchangeJour.delete();

            INFOLOG.add(eXCEPTION::Info,"Deleted Bill Of Exchange trans " + voucher +
                                        " in transaction " + int642str(custInvoiceJour.RecId));
        }

        custBillOfExchangeInvoice.delete();

        INFOLOG.add(eXCEPTION::Info,"Deleted Bill Of Exchange invoice " + voucher +
                                    " in transaction " + int642str(custInvoiceJour.RecId));
    }

    setprefix("TaxTrans");

    while select forupdate taxTrans
    where taxTrans.Voucher  ==voucher
        && taxTrans.TransDate==transDate
    {
        taxBookRecId        =   taxTrans.TaxBook;
        taxBookSectionRecId =   taxTrans.TaxBookSection;

        delete_from taxTransGeneralJournalAccountEntry where taxTransGeneralJournalAccountEntry.TaxTrans == taxTrans.RecId;

        taxTrans.delete();

        INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                    " in transaction " + int642str(taxTrans.RecId));
    }
    this.DeleteUpdateLedger(voucher, transDate);
    /*
    setprefix("LedgerTrans");

    while select forupdate ledgerTrans
    where ledgerTrans.Voucher  ==voucher
        && ledgerTrans.TransDate==transDate
    {
        ledgerTrans.delete();

        INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + _voucher +
                                    " in transaction " + int2str(ledgerTrans.RecId));
    }
    */

    while select forupdate CosCostTrans
    where CosCostTrans.Voucher  ==voucher
        && CosCostTrans.TransDate==transDate
    {
        CosCostTrans.delete();

        INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + voucher +
                                    " in transaction " + int642str(CosCostTrans.RecId));
    }

    while select forupdate AssetTrans
    where AssetTrans.Voucher  ==voucher
        && AssetTrans.TransDate==transDate
    {
        AssetTrans.delete();

        INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + voucher +
                                    " in transaction " + int642str(AssetTrans.RecId));
    }



    setprefix("BankAccountTrans");

    while select forupdate bankAccountTrans
    where bankAccountTrans.Voucher  ==voucher
        && bankAccountTrans.TransDate==transDate
    {
        bankAccountTrans.delete();

        INFOLOG.add(eXCEPTION::Info,"Deleted voucher " + voucher +
                                    " in transaction " + int642str(bankAccountTrans.RecId));
    }

    setprefix("LedgerJournalTrans");

    while select forupdate ledgerJournalTrans
    where ledgerJournalTrans.Voucher  ==voucher
        && ledgerJournalTrans.TransDate==transDate
    {
        ledgerJournalTrans.delete();

        INFOLOG.add(eXCEPTION::Info,"deleted voucher " + voucher +
                                    " in transaction " + int642str(ledgerJournalTrans.RecId));
    }


    while select forupdate custInvoiceTable
    where custInvoiceTable.InvoiceId     ==voucher
        && custInvoiceTable.InvoiceDate   ==transDate
    {

            NumberSequenceGroupLocal =   custInvoiceTable.numberSequenceGroup;

            while select forupdate custInvoiceLine
            where custInvoiceTable.RecId        ==custInvoiceLine.ParentRecId
            {
                setprefix("CustInvoiceLine");
                custInvoiceLine.delete();

                INFOLOG.add(EXCEPTION::Info,"deleted invoiceline " + voucher +
                                        " in transaction     " + int642str(custTransOpen.RecId));
            }

        setprefix("CustInvoiceTable");

        custInvoiceTable.delete();

        INFOLOG.add(EXCEPTION::Info,"deleted invoicetable " + voucher +
                                    " in transaction      " + int642str(custTransOpen.RecId));
    }

    while select forupdate custTrans
    where custTrans.Voucher  ==voucher
        && custTrans.TransDate==transDate
    {
        setprefix("CustTransOpen");

        while  select forupdate custTransOpen
        where custTransOpen.RefRecId ==custTrans.RecId
            && custTransOpen.TransDate==transDate
        {
        custTransOpen.delete();

        INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                    " in transaction " + int642str(custTransOpen.RecId));
        }
        setprefix("CustTrans");

        custTrans.delete();
        INFOLOG.add(EXCEPTION::Info,"deleted voucher " + voucher +
                                    " in transaction " + int642str(custTrans.RecId));
    }


    return ret;

}


private void DeleteUpdateLedger(Voucher _voucher,TransDate   _transDate)
{
    generalJournalAccountEntry              generalJournalAccountEntry;
    generalJournalEntry                     generalJournalEntry;
    subledgerVoucherGeneralJournalEntry     subledgerVoucherGeneralJournalEntry;
    ledgerEntry                             ledgerEntry;
    ledgerEntryJournal                      ledgerEntryJournal;
    ledgerEntryJournalizing                 ledgerEntryJournalizing;
    LedgerJournalTrans                      ledgerJournalTrans;


    ;

    while select RecId from generalJournalAccountEntry
        join RecId from generalJournalEntry
            where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
                join RecId from subledgerVoucherGeneralJournalEntry
                    where subledgerVoucherGeneralJournalEntry.GeneralJournalEntry == generalJournalEntry.RecId
                        && subledgerVoucherGeneralJournalEntry.Voucher == _voucher
                        && subledgerVoucherGeneralJournalEntry.VoucherDataAreaId == curext()
                        && subledgerVoucherGeneralJournalEntry.AccountingDate == _transDate



    {

            delete_from ledgerEntry
                where ledgerEntry.GeneralJournalAccountEntry == generalJournalAccountEntry.RecId;

            delete_from ledgerEntryJournal
            where ledgerEntryJournal.RecId == generalJournalEntry.LedgerEntryJournal;

            delete_from ledgerEntryJournalizing
            where ledgerEntryJournalizing.GeneralJournalAccountEntry == generalJournalAccountEntry.RecId;


    }


    delete_from ledgerEntry
        exists join generalJournalAccountEntry
            where generalJournalAccountEntry.RecId == ledgerEntry.GeneralJournalAccountEntry
        exists join generalJournalEntry
            where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
        exists join subledgerVoucherGeneralJournalEntry
            where subledgerVoucherGeneralJournalEntry.GeneralJournalEntry == generalJournalEntry.RecId
                && subledgerVoucherGeneralJournalEntry.Voucher == _voucher
                && subledgerVoucherGeneralJournalEntry.VoucherDataAreaId == curext()
                && subledgerVoucherGeneralJournalEntry.AccountingDate == _transDate;

    delete_from generalJournalAccountEntry
        exists join generalJournalEntry
            where generalJournalEntry.RecId == generalJournalAccountEntry.GeneralJournalEntry
                && generalJournalEntry.Ledger == Ledger::current()
        exists join subledgerVoucherGeneralJournalEntry
            where subledgerVoucherGeneralJournalEntry.GeneralJournalEntry == generalJournalEntry.RecId
                && subledgerVoucherGeneralJournalEntry.Voucher == _voucher
                && subledgerVoucherGeneralJournalEntry.VoucherDataAreaId == curext()
                && subledgerVoucherGeneralJournalEntry.AccountingDate == _transDate;

    GeneralJournalEntry::deleteOrphans();

    delete_from subledgerVoucherGeneralJournalEntry
        where subledgerVoucherGeneralJournalEntry.VoucherDataAreaId == curext()
        && subledgerVoucherGeneralJournalEntry.AccountingDate == _transDate
        && subledgerVoucherGeneralJournalEntry.Voucher == _voucher
        notexists join generalJournalEntry
            where generalJournalEntry.RecId == subledgerVoucherGeneralJournalEntry.GeneralJournalEntry
                && generalJournalEntry.Ledger == Ledger::current();
}


/// <summary>
///    Returns a class that contains the methods that are described by the <c>RunBaseDialogable</c>
///    interface.
/// </summary>
/// <returns>
///    A class that contains the methods that are described by the <c>RunBaseDialogable</c> interface.
/// </returns>
/// <remarks>
///    A dialog box can be either built by using the <c>Dialog</c> class or by using a class that is
///    created in the Application Object Tree (AOT).
/// </remarks>
public Object dialog()
{
    DialogRunbase       dialog = super();
;
    dlgVoucher         = dialog.addFieldValue(extendedTypeStr(voucher   ),voucher       ,"@ANR773"  );
    dlgTransDate       = dialog.addFieldValue(extendedTypeStr(transDate ),transDate     ,"@ANR774"  );
    //dlgJournalName     = dialog.addFieldValue(extendedTypeStr(LedgerJournalNameId   ),JournalName);

    dlgRecalcAccount   = dialog.addFieldValue(extendedTypeStr(NoYesId   ),recalcAccount ,"@SYS15182");



    dlgRecalcAccount.visible(false);
    return dialog;
}


public void dialogPostRun(DialogRunbase dialog)
{
;
    super(dialog);
}


public boolean getFromDialog()
{
;
    transDate       = dlgTransDate.value();
    voucher         = dlgVoucher.value();
    recalcAccount   = dlgRecalcAccount.value();
    //JournalName     = dlgJournalName.value();


    return super();
}


public boolean init()
{
    return true;
}


protected void new()
{
    super();
}


public container pack()
{
    return [#CurrentVersion,#CurrentList];
}


public NoYesId parmRecalcAccount(NoYesId _recalcAccount = recalcAccount)
{
    recalcAccount = _recalcAccount;

    return recalcAccount;
}


public TransDate parmTransDate(TransDate _transDate = transDate)
{
    transDate = _transDate;

    return transDate;
}


public Voucher parmVoucher(Voucher _voucher = voucher)
{
    voucher = _voucher;

    return voucher;
}


/// <summary>
///    Contains the code that does the actual job of the class.
/// </summary>
public void run()
{
    #OCCRetryCount
    if (! this.validate())
        throw error("");

    try
    {
        ttsbegin;

        this.Delete();
        this.updatelog();

        ttscommit;
    }
    catch (Exception::Deadlock)
    {
        retry;
    }
    catch (Exception::UpdateConflict)
    {
        if (appl.ttsLevel() == 0)
        {
            if (xSession::currentRetryCount() >= #RetryNum)
            {
                throw Exception::UpdateConflictNotRecovered;
            }
            else
            {
                retry;
            }
        }
        else
        {
            throw Exception::UpdateConflict;
        }
    }

}


public boolean runsImpersonated()
{
    return true;
}


public boolean unpack(container packedClass)
{
    Version version = RunBase::getVersion(packedClass);
;
    switch (version)
    {
        case #CurrentVersion:
            [version,#CurrentList] = packedClass;
            break;
        default:
            return false;
    }

    return true;
}


void updatelog()
{
    RENLogDeleteVoucher RENLogDeleteVoucher;
    ;

    RENLogDeleteVoucher.clear();
    RENLogDeleteVoucher = RENLogDeleteVoucher::find(Voucher,
                                                    RENModuleCustVendLedger::Cust,
                                                    DocumentStatus::Invoice,
                                                    true);

    RENLogDeleteVoucher.selectForUpdate(true);
    RENLogDeleteVoucher.Voucher                 =   Voucher;
    RENLogDeleteVoucher.DocumentNum             =   documentNum;
    RENLogDeleteVoucher.DocumentDate            =   transDate;
    RENLogDeleteVoucher.DocumentStatus          =   DocumentStatus::Invoice;
    RENLogDeleteVoucher.AccountNum              =   accountnum;
    RENLogDeleteVoucher.ModuleCustVendLedger    =   RENModuleCustVendLedger::Cust;
    RENLogDeleteVoucher.numberSequenceGroup     =   numberSequenceGroup;
    RENLogDeleteVoucher.recalcAccount           =   recalcAccount;
    RENLogDeleteVoucher.TaxBook                 =   taxBookRecId;
    RENLogDeleteVoucher.TaxBookSection          =   taxBookSectionRecId;

    RENLogDeleteVoucher.Recovered               =   !isInvoice;

    RENLogDeleteVoucher.RecoveredDate           =   Datenull();
    RENLogDeleteVoucher.InfologData             =   INFOLOG.infologData();

    if(RENLogDeleteVoucher.RecId)
    {
        RENLogDeleteVoucher.update();
    }
    else
    {
        RENLogDeleteVoucher.insert();
    }
}


public boolean validate(Object _calledFrom = null)
{
    custInvoiceJour             custInvoiceJour;
    custBillOfExchangeInvoice   custBillOfExchangeInvoice;
    custBillOfExchangeJour      custBillOfExchangeJour;

    vendTrans                   vendTrans;
    CustTrans                   CustTrans;

    // ALT_DP_20150528_LedgerMisc - begin
    TaxReportPeriod             taxReportPeriod;
    TaxTrans                    taxTrans;
    #ISOCountryRegionCodes

    InventTrans                 inventTrans;
    // ALT_DP_20150528_LedgerMisc - end

    boolean                     ret = true;
    ;

    CustTrans   =   CustTrans::findVoucherDate(voucher,transDate);

    if (!CustTrans)
    {
        return checkFailed("@ANR781");
    }

    if (CustTrans.remainAmountCur() != CustTrans.AmountCur
        && CustTrans.TransType != LedgerTransType::CashDiscount
        )
    {
        return checkFailed("@ANR782");
    }

    vendTrans = VendTrans::findVoucherDate(voucher,transDate);

    if (vendTrans)
    {
        return checkFailed("@ANR776");
    }

    while select forupdate custInvoiceJour
    where custInvoiceJour.LedgerVoucher == voucher      &&
          custInvoiceJour.InvoiceDate   == transDate
    {
        // ALT_DP_20150528_LedgerMisc - begin
        if (SysCountryRegionCode::isLegalEntityInCountryRegion([#isoIT]))
        {
            select firstonly RecId, TaxPeriod from taxReportPeriod
                where taxReportPeriod.FromDate  <= custInvoiceJour.InvoiceDate  &&
                      taxReportPeriod.ToDate    >= custInvoiceJour.InvoiceDate  &&
                      taxReportPeriod.Closed
            exists join taxTrans
                where taxTrans.TaxPeriod == taxReportPeriod.TaxPeriod           &&
                      taxTrans.TransDate == custInvoiceJour.InvoiceDate         &&
                      taxTrans.Voucher   == custInvoiceJour.LedgerVoucher;
            if (taxReportPeriod)
            {
                return checkFailed(strFmt("@SYS79476", "@SYS79287", taxReportPeriod.TaxPeriod));
            }
        }

        select firstonly RecId from inventTrans
            where inventTrans.DateFinancial == custInvoiceJour.InvoiceDate &&
                  inventTrans.Voucher   == custInvoiceJour.LedgerVoucher;

        if (inventTrans)
        {
            if (! InventClosing::checkOpen(custInvoiceJour.InvoiceDate))
                return false;
        }
        // ALT_DP_20150528_LedgerMisc - end

        while select * from  custBillOfExchangeInvoice
        where   custBillOfExchangeInvoice.InvoiceVoucher == custInvoiceJour.LedgerVoucher   &&
                custBillOfExchangeInvoice.invoiceDate    == custInvoiceJour.InvoiceDate
        {
            select firstonly custBillOfExchangeJour
            where custBillOfExchangeInvoice.BillOfExchangeId == custBillOfExchangeJour.BillOfExchangeId &&
                  custBillOfExchangeJour.Status              != CustVendNegInstStatus::Drawn;

            if (custBillOfExchangeJour.RecId)

            {
                return checkFailed("@ANR775");
            }
        }
    }

    return ret;
}


server static RENDeleteCustVoucher construct()
{
    return new RENDeleteCustVoucher();
}


// Here goes a description of the class
static ClassDescription description()
{
    return "@ANR778";
}


static void main(Args args)
{
    RENDeleteCustVoucher    RENDeleteCustVoucher;
    CustTrans               CustTrans;
    FormDataSource          formDataSource;

;
    RENDeleteCustVoucher = RENDeleteCustVoucher::construct();

    if(args && args.record() && args.dataset() == tableNum(CustTrans))
    {
        formDataSource  =   args.record().dataSource();
        CustTrans.data(args.record());
        RENDeleteCustVoucher.parmTransDate(CustTrans.TransDate);
        RENDeleteCustVoucher.parmVoucher(CustTrans.Voucher);
    }
    if (RENDeleteCustVoucher.prompt())
        RENDeleteCustVoucher.run();

    if(formDataSource)
    {
        formDataSource.research();
    }
}