public static void ReleaseRetainage(ARInvoiceEntry graph, ARInvoiceExt invoice, ARRetainageFilter filter, bool isAutoRelease)
        {
            graph.Clear(PXClearOption.ClearAll);
            PXUIFieldAttribute.SetError(graph.Document.Cache, null, null, null);

            RetainageOptions retainageOptions = new RetainageOptions();

            retainageOptions.DocDate          = filter.DocDate;
            retainageOptions.FinPeriodID      = filter.FinPeriodID;
            retainageOptions.CuryRetainageAmt = invoice.CuryRetainageReleasedAmt;

            ARInvoiceEntryRetainage retainageExt = graph.GetExtension <ARInvoiceEntryRetainage>();

            ARInvoice retainageInvoice = retainageExt.ReleaseRetainageProc(invoice, retainageOptions, isAutoRelease);

            graph.Save.Press();

            if (isAutoRelease)
            {
                List <ARRegister> toRelease = new List <ARRegister>()
                {
                    retainageInvoice
                };
                using (new PXTimeStampScope(null))
                {
                    ARDocumentRelease.ReleaseDoc(toRelease, true);
                }
            }
        }
Exemplo n.º 2
0
        public static List <ARInvoice> Process(List <ARInvoice> list, bool isMassProcess)
        {
            List <ARInvoice> listWithTax = new List <ARInvoice>(list.Count);
            ARInvoiceEntry   rg          = PXGraph.CreateInstance <ARInvoiceEntry>();

            for (int i = 0; i < list.Count; i++)
            {
                try
                {
                    rg.Clear();
                    rg.Document.Current = PXSelect <ARInvoice, Where <ARInvoice.docType, Equal <Required <ARInvoice.docType> >, And <ARInvoice.refNbr, Equal <Required <ARInvoice.refNbr> > > > > .Select(rg, list[i].DocType, list[i].RefNbr);

                    listWithTax.Add(rg.CalculateAvalaraTax(rg.Document.Current));
                    PXProcessing <ARInvoice> .SetInfo(i, ActionsMessages.RecordProcessed);
                }
                catch (Exception e)
                {
                    if (isMassProcess)
                    {
                        PXProcessing <ARInvoice> .SetError(i, e is PXOuterException?e.Message + "\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message);
                    }
                    else
                    {
                        throw new PXMassProcessException(i, e);
                    }
                }
            }

            return(listWithTax);
        }
Exemplo n.º 3
0
        public virtual IEnumerable ViewInvoice(PXAdapter adapter)
        {
            ARInvoiceEntry target = PXGraph.CreateInstance <ARInvoiceEntry>();

            target.Clear();
            target.Document.Current = PXSelect <ARInvoice, Where <ARInvoice.docType, Equal <Current <PMTran.aRTranType> >, And <ARInvoice.refNbr, Equal <Current <PMTran.aRRefNbr> > > > > .Select(this);

            throw new PXRedirectRequiredException(target, "Invoice")
                  {
                      Mode = PXBaseRedirectException.WindowMode.NewWindow
                  };
        }
        protected virtual void SetupGraph()
        {
            graph.Clear();
            graph.Views.Caches.Add(typeof(Contract));
            graph.Views.Caches.Add(typeof(ContractDetail));
            graph.Views.Caches.Add(typeof(ContractBillingSchedule));

            PXCache <ContractBillingSchedule> scheduleCache = (PXCache <ContractBillingSchedule>)graph.Caches[typeof(ContractBillingSchedule)];

            PXDBDefaultAttribute.SetDefaultForUpdate <ContractBillingSchedule.contractID>(scheduleCache, null, false);

            PXCache <ContractDetail> contractItemCache = (PXCache <ContractDetail>)graph.Caches[typeof(ContractDetail)];

            PXDBDefaultAttribute.SetDefaultForUpdate <ContractDetail.contractID>(contractItemCache, null, false);
        }
Exemplo n.º 5
0
        public virtual IEnumerable ViewInvoice(PXAdapter adapter)
        {
            ARTran arTran = PXSelect <ARTran, Where <ARTran.pMTranID, Equal <Current <PMTran.tranID> > > > .SelectSingleBound(this, new object[] { Transactions.Current });

            if (arTran != null)
            {
                ARInvoiceEntry target = PXGraph.CreateInstance <ARInvoiceEntry>();
                target.Clear();
                target.Document.Current = target.Document.Search <ARInvoice.refNbr>(arTran.RefNbr);
                throw new PXRedirectRequiredException(target, "Invoice")
                      {
                          Mode = PXBaseRedirectException.WindowMode.NewWindow
                      };
            }

            return(adapter.Get());
        }
        public virtual ARRegister OnBeforeRelease(ARRegister ardoc)
        {
            var invoice = ardoc as ARInvoice;

            if (invoice == null || invoice.IsTaxValid == true || !IsExternalTax(invoice.TaxZoneID))
            {
                return(ardoc);
            }

            ARInvoiceEntry graph = invoice.OrigModule == GL.BatchModule.SO
                                ? LazySoInvoiceEntry.Value
                                : LazyArInvoiceEntry.Value;

            graph.Clear();

            return(graph.RecalculateExternalTax(graph, invoice));
        }
Exemplo n.º 7
0
        public virtual IEnumerable ViewDoc(PXAdapter adapter)
        {
            DRSchedule sc = PXSelect <DRSchedule, Where <DRSchedule.scheduleID, Equal <Current <DRScheduleTran.scheduleID> > > > .Select(this);

            if (sc != null)
            {
                switch (sc.Module)
                {
                case BatchModule.AR:
                    ARInvoiceEntry arTarget = PXGraph.CreateInstance <ARInvoiceEntry>();
                    arTarget.Clear();


                    ARInvoice invoice = PXSelect <ARInvoice, Where <ARInvoice.docType, Equal <Required <DRScheduleDetail.docType> >, And <ARInvoice.refNbr, Equal <Required <DRScheduleDetail.refNbr> > > > > .Select(this, sc.DocType, sc.RefNbr);

                    if (invoice != null)
                    {
                        arTarget.Document.Current = invoice;
                        throw new PXRedirectRequiredException(arTarget, true, "ViewDocument")
                              {
                                  Mode = PXBaseRedirectException.WindowMode.NewWindow
                              };
                    }
                    break;

                case BatchModule.AP:
                    APInvoiceEntry apTarget = PXGraph.CreateInstance <APInvoiceEntry>();
                    apTarget.Clear();


                    APInvoice invoice2 = PXSelect <APInvoice, Where <APInvoice.docType, Equal <Required <DRScheduleDetail.docType> >, And <APInvoice.refNbr, Equal <Required <DRScheduleDetail.refNbr> > > > > .Select(this, sc.DocType, sc.RefNbr);

                    if (invoice2 != null)
                    {
                        apTarget.Document.Current = invoice2;
                        throw new PXRedirectRequiredException(apTarget, true, "ViewInvoice")
                              {
                                  Mode = PXBaseRedirectException.WindowMode.NewWindow
                              };
                    }
                    break;
                }
            }
            return(adapter.Get());
        }
Exemplo n.º 8
0
        private static ARInvoice CreatePPDCreditMemo(ARInvoiceEntry ie, ARPPDCreditMemoParameters filter, List <PendingPPDCreditMemoApp> list)
        {
            int       index = 0;
            ARInvoice invoice;

            try
            {
                ie.Clear(PXClearOption.ClearAll);
                PXUIFieldAttribute.SetError(ie.Document.Cache, null, null, null);

                invoice = ie.CreatePPDCreditMemo(filter, list, ref index);

                PXProcessing <PendingPPDCreditMemoApp> .SetInfo(index, ActionsMessages.RecordProcessed);
            }
            catch (Exception e)
            {
                PXProcessing <PendingPPDCreditMemoApp> .SetError(index, e);

                invoice = null;
            }

            return(invoice);
        }
Exemplo n.º 9
0
        public virtual IEnumerable ViewDoc(PXAdapter adapter)
        {
            if (Schedule.Current != null)
            {
                switch (Schedule.Current.Module)
                {
                case BatchModule.AR:
                    ARInvoiceEntry arTarget = PXGraph.CreateInstance <ARInvoiceEntry>();
                    arTarget.Clear();


                    ARInvoice invoice = PXSelect <ARInvoice, Where <ARInvoice.docType, Equal <Current <DRSchedule.docType> >, And <ARInvoice.refNbr, Equal <Current <DRSchedule.refNbr> > > > > .Select(this);

                    if (invoice != null)
                    {
                        arTarget.Document.Current = invoice;
                        throw new PXRedirectRequiredException(arTarget, "ViewDocument");
                    }
                    break;

                case BatchModule.AP:
                    APInvoiceEntry apTarget = PXGraph.CreateInstance <APInvoiceEntry>();
                    apTarget.Clear();


                    APInvoice invoice2 = PXSelect <APInvoice, Where <APInvoice.docType, Equal <Current <DRSchedule.docType> >, And <APInvoice.refNbr, Equal <Current <DRSchedule.refNbr> > > > > .Select(this);

                    if (invoice2 != null)
                    {
                        apTarget.Document.Current = invoice2;
                        throw new PXRedirectRequiredException(apTarget, "ViewInvoice");
                    }
                    break;
                }
            }
            return(adapter.Get());
        }
        public virtual void Bill(CustomersList customer, EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

            arGraph.Clear();
            pmGraph.Clear();

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

            List <ARRegister>            doclist = new List <ARRegister>();
            List <EPExpenseClaimDetails> listOfDirectBilledClaims = new List <EPExpenseClaimDetails>();

            PXSelectBase <EPExpenseClaimDetails> select = new PXSelectJoin <EPExpenseClaimDetails,
                                                                            LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>, And <Where <Contract.baseType, Equal <Contract.ContractBaseType>, Or <Contract.nonProject, Equal <True> > > > >
                                                                                      , LeftJoin <Account, On <EPExpenseClaimDetails.expenseAccountID, Equal <Account.accountID> > >
                                                                                      >,
                                                                            Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                   And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                        And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                             And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                  And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                       And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                            And <Where <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>, Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > >,
                                                                            OrderBy <Asc <EPExpenseClaimDetails.branchID> > >(this);

            arGraph.RowPersisted.AddHandler <ARInvoice>(
                delegate(PXCache sender, PXRowPersistedEventArgs e)
            {
                if (e.TranStatus == PXTranStatus.Open)
                {
                    foreach (EPExpenseClaimDetails row in listOfDirectBilledClaims.Select(claimdetail => Transactions.Locate(claimdetail)))
                    {
                        row.ARDocType = ((ARInvoice)e.Row).DocType;
                        row.ARRefNbr  = ((ARInvoice)e.Row).RefNbr;
                    }
                }
            });


            decimal signOperation = 1m;

            decimal tipQty = 1m;

            foreach (PXResult <EPExpenseClaimDetails, Contract, Account> res in select.Select(customer.CustomerID, customer.LocationID, filter.EndDate))
            {
                EPExpenseClaimDetails row = (EPExpenseClaimDetails)res;

                if (row.ContractID != null && !ProjectDefaultAttribute.IsNonProject(row.ContractID))
                {
                    if (pmDoc == null)
                    {
                        pmDoc             = (PMRegister)pmGraph.Document.Cache.Insert();
                        pmDoc.OrigDocType = PMOrigDocType.ExpenseClaim;
                        pmDoc.OrigDocNbr  = row.RefNbr;
                    }

                    PMTran usage = InsertPMTran(pmGraph, res);
                    if (usage.Released == true)                     //contract trans are created as released
                    {
                        UsageMaint.AddUsage(pmGraph.Transactions.Cache, usage.ProjectID, usage.InventoryID, usage.BillableQty ?? 0m, usage.UOM);
                    }
                }
                else
                {
                    if (arDoc == null || arDoc.BranchID != row.BranchID)
                    {
                        if (arDoc != null)
                        {
                            arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                            arGraph.Document.Update(arDoc);
                            arGraph.Save.Press();
                            listOfDirectBilledClaims.Clear();
                        }
                        EPExpenseClaimDetails summDetail = PXSelectJoinGroupBy <EPExpenseClaimDetails,
                                                                                LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>, And <Where <Contract.baseType, Equal <Contract.ContractBaseType>, Or <Contract.nonProject, Equal <True> > > > >
                                                                                          >,
                                                                                Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                       And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                            And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                                 And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                      And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                           And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                                And <EPExpenseClaimDetails.branchID, Equal <Required <EPExpenseClaimDetails.branchID> >,
                                                                                                                     And <Where <Contract.nonProject, Equal <True>, Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > > >
                                                                                , Aggregate <Sum <EPExpenseClaimDetails.curyTranAmt> >
                                                                                > .Select(this, customer.CustomerID, customer.LocationID, filter.EndDate, row.BranchID);

                        if (summDetail.CuryTranAmt < 0)
                        {
                            signOperation = -1;
                        }
                        else
                        {
                            signOperation = 1;
                        }

                        arDoc = (ARInvoice)arGraph.Document.Cache.Insert();
                        //arDocList.Add(arDoc);
                        if (signOperation < 0)
                        {
                            arGraph.Document.Cache.SetValueExt <ARInvoice.docType>(arDoc, AR.ARDocType.CreditMemo);
                        }
                        else
                        {
                            arGraph.Document.Cache.SetValueExt <ARInvoice.docType>(arDoc, AR.ARDocType.Invoice);
                        }
                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerID>(arDoc, row.CustomerID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerLocationID>(arDoc, row.CustomerLocationID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.docDate>(arDoc, filter.InvoiceDate);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.branchID>(arDoc, row.BranchID);
                        arDoc.OrigModule  = BatchModule.EP;
                        arDoc.OrigRefNbr  = row.RefNbr;
                        arDoc             = arGraph.Document.Update(arDoc);
                        arDoc.FinPeriodID = filter.InvFinPeriodID;
                        if (Setup.Current.AutomaticReleaseAR == true)
                        {
                            arDoc.Hold = false;
                        }
                        doclist.Add(arDoc);
                    }

                    //insert ARTran
                    InsertARTran(arGraph, row, signOperation);
                    if ((row.CuryTipAmt ?? 0) != 0)
                    {
                        if (signOperation < 0 == row.ClaimCuryTranAmtWithTaxes < 0)
                        {
                            tipQty = 1;
                        }
                        else
                        {
                            tipQty = -1;
                        }
                        InsertARTran(arGraph, row, signOperation, tipQty, true);
                    }
                    listOfDirectBilledClaims.Add(row);
                }

                row.Billed = true;
                Transactions.Update(row);
            }

            if (arDoc != null)
            {
                arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                arGraph.Document.Update(arDoc);
                arGraph.Save.Press();
            }

            if (pmDoc != null)
            {
                pmGraph.Save.Press();
            }

            this.Persist(typeof(EPExpenseClaimDetails), PXDBOperation.Update);

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Exemplo n.º 11
0
        public virtual bool Bill(int?projectID, DateTime?invoiceDate)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, projectID);

            ContractBillingSchedule schedule = PXSelect <ContractBillingSchedule> .Search <ContractBillingSchedule.contractID>(this, project.ContractID);

            DateTime billingDate;

            if (invoiceDate == null)
            {
                if (schedule.Type == BillingType.OnDemand)
                {
                    billingDate = Accessinfo.BusinessDate ?? DateTime.Now;
                }
                else
                {
                    billingDate = schedule.NextDate.Value;
                }
            }
            else
            {
                billingDate = invoiceDate.Value;
            }

            Customer customer = null;

            if (project.CustomerID != null)
            {
                customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(this, project.CustomerID);
            }

            if (customer == null)
            {
                throw new PXException(Messages.NoCustomer);
            }

            List <BillingData> list          = new List <BillingData>();
            List <PMTran>      reversalTrans = new List <PMTran>();

            PXSelectBase <PMTask> selectTasks = new PXSelect <PMTask,
                                                              Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                                     And <PMTask.billingID, IsNotNull,
                                                                          And <PMTask.isActive, Equal <True> > > > >(this);

            foreach (PMTask task in selectTasks.Select(project.ContractID))
            {
                if ((task.BillingOption == PMBillingOption.OnTaskCompletion && task.IsCompleted == true) ||
                    (task.BillingOption == PMBillingOption.OnProjectCompetion && project.IsCompleted == true) ||
                    task.BillingOption == PMBillingOption.OnBilling)
                {
                    list.AddRange(BillTask(task, billingDate));
                    reversalTrans.AddRange(ReverseWipTask(task, billingDate));
                }
            }

            //Regroup by Invoices:
            Dictionary <string, List <BillingData> > invoices = new Dictionary <string, List <BillingData> >();
            string emptyInvoiceDescriptionKey = "!@#$%^&";

            foreach (BillingData data in list)
            {
                if (string.IsNullOrEmpty(data.Rule.InvoiceDescription))
                {
                    if (invoices.ContainsKey(emptyInvoiceDescriptionKey))
                    {
                        invoices[emptyInvoiceDescriptionKey].Add(data);
                    }
                    else
                    {
                        invoices.Add(emptyInvoiceDescriptionKey, new List <BillingData>(new BillingData[] { data }));
                    }
                }
                else
                {
                    if (invoices.ContainsKey(data.Rule.InvoiceDescription))
                    {
                        invoices[data.Rule.InvoiceDescription].Add(data);
                    }
                    else
                    {
                        invoices.Add(data.Rule.InvoiceDescription, new List <BillingData>(new BillingData[] { data }));
                    }
                }

                //Reverse On Billing:

                if (data.PMTran != null)
                {
                    bool reverseOnBilling = false;

                    if (data.PMTran.Reverse == PMReverse.OnBilling)
                    {
                        reverseOnBilling = true;
                    }
                    else if (data.PMTran.Reverse != PMReverse.Never && IsNonGL(data.PMTran))
                    {
                        reverseOnBilling = true;
                    }

                    if (reverseOnBilling)
                    {
                        reversalTrans.AddRange(ReverseTran(data.PMTran));
                    }
                }
            }


            //Schedule update:
            schedule.NextDate = GetNextBillingDate(this, schedule, schedule.NextDate);
            schedule.LastDate = this.Accessinfo.BusinessDate;
            BillingSchedule.Update(schedule);


            //ContractDetail update:
            PXSelectBase <ContractDetailExt> cis = new PXSelect <ContractDetailExt, Where <ContractDetailExt.contractID, Equal <Required <ContractDetailExt.contractID> >,
                                                                                           And <ContractDetailExt.resetUsage, Equal <ResetUsageOption.onBilling> > > >(this);

            foreach (ContractDetailExt ci in cis.Select(project.ContractID))
            {
                ci.Used = 0;
                ContractDetail.Update(ci);
            }

            List <ARRegister> doclist     = new List <ARRegister>();
            PMRegister        reversalDoc = null;

            if (invoices.Count > 0)
            {
                using (PXTransactionScope ts = new PXTransactionScope())
                {
                    ARInvoiceEntry invoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>();
                    invoiceEntry.FieldVerifying.AddHandler <ARInvoice.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                    invoiceEntry.FieldVerifying.AddHandler <ARTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                    invoiceEntry.FieldVerifying.AddHandler <ARTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });

                    foreach (KeyValuePair <string, List <BillingData> > kv in invoices)
                    {
                        invoiceEntry.Clear(PXClearOption.ClearAll);

                        string    description = kv.Key == emptyInvoiceDescriptionKey ? null : kv.Key;
                        string    docDesc     = description ?? string.Format(PXMessages.LocalizeNoPrefix(CT.Messages.BillingFor), project.ContractCD, project.Description);
                        ARInvoice invoice     = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateInstance();
                        invoice.DocType = GetDocType(kv.Value);
                        int mult = 1;
                        if (invoice.DocType == ARDocType.CreditMemo)
                        {
                            mult = -1;
                        }

                        invoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].Insert(invoice);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.customerID>(invoice, customer.AcctCD);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.customerLocationID>(invoice, project.LocationID);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.docDate>(invoice, billingDate);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.docDesc>(invoice, docDesc);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.projectID>(invoice, project.ContractID);

                        CurrencyInfo curyinfo = (CurrencyInfo)invoiceEntry.Caches[typeof(CurrencyInfo)].Current;
                        foreach (BillingData data in kv.Value)
                        {
                            data.Tran.ExtPrice = data.Tran.ExtPrice.GetValueOrDefault() * mult;
                            data.Tran.Qty      = data.Tran.Qty.GetValueOrDefault() * mult;
                            data.Tran.TranAmt  = data.Tran.TranAmt.GetValueOrDefault() * mult;

                            decimal curyamount;
                            PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, data.Tran.UnitPrice.GetValueOrDefault(), out curyamount);
                            data.Tran.CuryUnitPrice = curyamount;
                            PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, data.Tran.ExtPrice.GetValueOrDefault(), out curyamount);
                            data.Tran.CuryExtPrice     = curyamount;
                            data.Tran.CuryTranAmt      = data.Tran.CuryExtPrice;
                            data.Tran.FreezeManualDisc = true;
                            data.Tran.CuryInfoID       = curyinfo.CuryInfoID;
                            ARTran newTran = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Insert(data.Tran);

                            if (data.Tran.TranAmt > newTran.TranAmt)
                            {
                                newTran.PMDeltaOption = ARTran.pMDeltaOption.CompleteLine;                                //autocomplete when currency descrepency exists.
                            }

                            if (data.Tran.AccountID != null)
                            {
                                ARTran copy = (ARTran)invoiceEntry.Caches[typeof(ARTran)].CreateCopy(newTran);
                                copy.AccountID = data.Tran.AccountID;

                                copy = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Update(copy);

                                if (data.SubCD != null)
                                {
                                    invoiceEntry.Caches[typeof(ARTran)].SetValueExt <ARTran.subID>(copy, data.SubCD);
                                }
                            }

                            if (data.Note != null)
                            {
                                PXNoteAttribute.SetNote(invoiceEntry.Caches[typeof(ARTran)], newTran, data.Note);
                            }
                            if (data.Files != null && data.Files.Length > 0)
                            {
                                PXNoteAttribute.SetFileNotes(invoiceEntry.Caches[typeof(ARTran)], newTran, data.Files);
                            }


                            //item.RefLineNbr = newTran.LineNbr;
                        }

                        ARInvoice oldInvoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateCopy(invoice);

                        invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                        invoiceEntry.Caches[typeof(ARInvoice)].RaiseRowUpdated(invoice, oldInvoice);
                        invoiceEntry.Caches[typeof(ARInvoice)].SetValue <ARInvoice.curyOrigDocAmt>(invoice, invoice.CuryDocBal);

                        if (project.AutomaticReleaseAR == true)
                        {
                            invoiceEntry.Caches[typeof(ARInvoice)].SetValueExt <ARInvoice.hold>(invoice, false);
                        }

                        doclist.Add((ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].Current);
                        invoiceEntry.Save.Press();
                    }

                    Actions.PressSave();

                    if (reversalTrans.Count > 0)
                    {
                        RegisterEntry pmEntry = PXGraph.CreateInstance <RegisterEntry>();
                        pmEntry.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });                    //Project can be completed.
                        pmEntry.FieldVerifying.AddHandler <PMTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });                       //Task can be completed.
                        pmEntry.FieldVerifying.AddHandler <PMTran.inventoryID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
                        reversalDoc              = (PMRegister)pmEntry.Document.Cache.Insert();
                        reversalDoc.OrigDocType  = PMOrigDocType.AllocationReversal;
                        reversalDoc.Description  = "Allocation Reversal on Billing";
                        pmEntry.Document.Current = reversalDoc;

                        foreach (PMTran tran in reversalTrans)
                        {
                            pmEntry.Transactions.Insert(tran);
                        }
                        pmEntry.Save.Press();
                    }

                    ts.Complete();
                }
            }
            else
            {
                this.Persist(typeof(ContractBillingSchedule), PXDBOperation.Update);
                this.Persist(typeof(Contract), PXDBOperation.Update);
            }

            if (project.AutomaticReleaseAR == true)
            {
                try
                {
                    ARDocumentRelease.ReleaseDoc(doclist, false);
                }
                catch (Exception ex)
                {
                    throw new PXException(Messages.AutoReleaseARFailed, ex);
                }

                if (reversalDoc != null)
                {
                    try
                    {
                        RegisterRelease.Release(reversalDoc);
                    }
                    catch (Exception ex)
                    {
                        throw new PXException(Messages.AutoReleaseOfReversalFailed, ex);
                    }
                }
            }

            return(doclist.Count > 0);
        }
Exemplo n.º 12
0
        public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate)
        {
            IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate);

            ARInvoiceEntry invoiceEntry = CreateGraph();

            using (PXTransactionScope transactionScope = new PXTransactionScope())
            {
                foreach (ScheduleDet occurrence in occurrences)
                {
                    foreach (PXResult <ARInvoice, Customer, CurrencyInfo> scheduledInvoiceResult in PXSelectJoin <
                                 ARInvoice,
                                 InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >,
                                            InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >,
                                 Where <
                                     ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >,
                                     And <ARInvoice.scheduled, Equal <True> > > >
                             .Select(this, schedule.ScheduleID))
                    {
                        invoiceEntry.Clear();

                        invoiceEntry.customer.Current = scheduledInvoiceResult;
                        ARInvoice    scheduledInvoice             = scheduledInvoiceResult;
                        CurrencyInfo scheduledInvoiceCurrencyInfo = scheduledInvoiceResult;

                        ARInvoice newInvoice = InsertDocument(
                            invoiceEntry,
                            occurrence,
                            scheduledInvoiceResult,
                            scheduledInvoiceResult,
                            scheduledInvoiceCurrencyInfo);

                        InsertDetails(invoiceEntry, scheduledInvoice, newInvoice);

                        BalanceCalculation.ForceDocumentControlTotals(invoiceEntry, newInvoice);

                        try
                        {
                            invoiceEntry.Save.Press();
                        }
                        catch
                        {
                            if (invoiceEntry.Document.Cache.IsInsertedUpdatedDeleted)
                            {
                                throw;
                            }
                        }
                    }

                    schedule.LastRunDate = occurrence.ScheduledDate;
                    Running_Schedule.Cache.Update(schedule);
                }

                transactionScope.Complete(this);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }

            Running_Schedule.Cache.Persisted(false);
        }
Exemplo n.º 13
0
        public virtual void Bill(CustomersList customer, PX.Objects.EP.EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

            arGraph.Clear();
            pmGraph.Clear();

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

            List <ARRegister>            doclist = new List <ARRegister>();
            List <EPExpenseClaimDetails> listOfDirectBilledClaims = new List <EPExpenseClaimDetails>();

            PXSelectBase <EPExpenseClaimDetails> select = new PXSelectJoin <EPExpenseClaimDetails,
                                                                            InnerJoin <EPExpenseClaim, On <EPExpenseClaimDetails.refNbr, Equal <EPExpenseClaim.refNbr> > >,
                                                                            Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                   And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                        And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                             And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                  And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                       And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> > > > > > > >,
                                                                            OrderBy <Asc <EPExpenseClaimDetails.customerID, Asc <EPExpenseClaimDetails.customerLocationID> > > >(this);

            foreach (PXResult <EPExpenseClaimDetails, EPExpenseClaim> res in select.Select(customer.CustomerID, customer.LocationID, filter.EndDate))
            {
                EPExpenseClaimDetails row = (EPExpenseClaimDetails)res;
                EPExpenseClaim        doc = (EPExpenseClaim)res;

                if (row.ContractID != null && !ProjectDefaultAttribute.IsNonProject(this, row.ContractID))
                {
                    if (pmDoc == null)
                    {
                        pmDoc             = (PMRegister)pmGraph.Document.Cache.Insert();
                        pmDoc.OrigDocType = PMOrigDocType.ExpenseClaim;
                        pmDoc.OrigDocNbr  = doc.RefNbr;
                    }

                    InsertPMTran(pmGraph, row, doc, Setup.Current.CopyNotesPM == true, Setup.Current.CopyFilesPM == true);
                }
                else
                {
                    if (arDoc == null ||
                        arDoc.CustomerID != row.CustomerID ||
                        arDoc.CustomerLocationID != row.CustomerLocationID)
                    {
                        if (arDoc != null)
                        {
                            arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                            arGraph.Document.Update(arDoc);
                            arGraph.Save.Press();
                        }
                        arDoc                    = (ARInvoice)arGraph.Document.Cache.Insert();
                        arDoc.DocType            = AR.ARDocType.Invoice;
                        arDoc.CustomerID         = row.CustomerID;
                        arDoc.CustomerLocationID = row.CustomerLocationID;
                        arDoc                    = arGraph.Document.Update(arDoc);
                        arGraph.Document.Cache.RaiseFieldUpdated <AR.ARInvoice.customerID>(arDoc, null);
                        if (Setup.Current.AutomaticReleaseAR == true)
                        {
                            arDoc.Hold = false;
                        }
                        doclist.Add(arDoc);
                    }

                    //insert ARTran
                    InsertARTran(arGraph, row, Setup.Current.CopyNotesAR == true, Setup.Current.CopyFilesAR == true);
                    listOfDirectBilledClaims.Add(row);
                }

                row.Billed = true;
                Transactions.Update(row);
            }

            if (arDoc != null)
            {
                arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                arGraph.Document.Update(arDoc);

                arGraph.RowPersisted.AddHandler <ARInvoice>(
                    delegate(PXCache sender, PXRowPersistedEventArgs e)
                {
                    if (e.TranStatus == PXTranStatus.Open)
                    {
                        foreach (EPExpenseClaimDetails claimdetail in listOfDirectBilledClaims)
                        {
                            EPExpenseClaimDetails row = Transactions.Locate(claimdetail);

                            row.ARDocType = ((ARInvoice)e.Row).DocType;
                            row.ARRefNbr  = ((ARInvoice)e.Row).RefNbr;
                        }
                    }
                });

                arGraph.Save.Press();
            }
            if (pmDoc != null)
            {
                pmGraph.Save.Press();
            }

            this.Persist(typeof(EPExpenseClaimDetails), PXDBOperation.Update);

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Exemplo n.º 14
0
        private static ARInvoice CreatePPDCreditMemo(ARInvoiceEntry ie, ARPPDCreditMemoParameters filter, ARSetup setup, List <PendingPPDCreditMemoApp> list)
        {
            int       index = 0;
            ARInvoice invoice;

            try
            {
                ie.Clear(PXClearOption.ClearAll);
                PXUIFieldAttribute.SetError(ie.Document.Cache, null, null, null);

                Customer customer = null;
                invoice = (ARInvoice)ie.Document.Cache.CreateInstance();

                bool firstApp = true;
                foreach (PendingPPDCreditMemoApp doc in list)
                {
                    if (firstApp)
                    {
                        firstApp = false;
                        index    = doc.Index;

                        customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(ie, doc.AdjdCustomerID);

                        CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, doc.InvCuryInfoID);

                        info.CuryInfoID = null;
                        info            = ie.currencyinfo.Insert(info);

                        invoice.DocType     = ARDocType.CreditMemo;
                        invoice.DocDate     = filter.GenerateOnePerCustomer == true ? filter.CreditMemoDate : doc.AdjgDocDate;
                        invoice.FinPeriodID = filter.GenerateOnePerCustomer == true ? filter.FinPeriodID : doc.AdjgFinPeriodID;
                        invoice             = PXCache <ARInvoice> .CreateCopy(ie.Document.Insert(invoice));

                        invoice.CustomerID         = doc.AdjdCustomerID;
                        invoice.CustomerLocationID = doc.InvCustomerLocationID;
                        invoice.CuryInfoID         = info.CuryInfoID;
                        invoice.CuryID             = info.CuryID;
                        invoice.DocDesc            = setup.PPDCreditMemoDescr;
                        invoice.BranchID           = doc.AdjdBranchID;
                        invoice.ARAccountID        = doc.AdjdARAcct;
                        invoice.ARSubID            = doc.AdjdARSub;
                        invoice.TaxZoneID          = doc.InvTaxZoneID;
                        invoice.Hold       = false;
                        invoice.PendingPPD = true;

                        invoice = ie.Document.Update(invoice);

                        invoice.DontPrint = true;
                        invoice.DontEmail = true;
                    }

                    AddTaxesAndApplications(ie, doc, customer, invoice);
                }

                ie.ARDiscountDetails.Select().RowCast <ARInvoiceDiscountDetail>().
                ForEach(discountDetail => ie.ARDiscountDetails.Cache.Delete(discountDetail));

                if (setup.RequireControlTotal == true)
                {
                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    ie.Document.Cache.Update(invoice);
                }

                ie.Save.Press();
                string refNbr = invoice.RefNbr;
                list.ForEach(doc => PXUpdate <Set <ARAdjust.pPDCrMemoRefNbr, Required <ARAdjust.pPDCrMemoRefNbr> >, ARAdjust,
                                              Where <ARAdjust.adjdDocType, Equal <Required <ARAdjust.adjdDocType> >,
                                                     And <ARAdjust.adjdRefNbr, Equal <Required <ARAdjust.adjdRefNbr> >,
                                                          And <ARAdjust.adjgDocType, Equal <Required <ARAdjust.adjgDocType> >,
                                                               And <ARAdjust.adjgRefNbr, Equal <Required <ARAdjust.adjgRefNbr> >,
                                                                    And <ARAdjust.released, Equal <True>,
                                                                         And <ARAdjust.voided, NotEqual <True>,
                                                                              And <ARAdjust.pendingPPD, Equal <True> > > > > > > > >
                             .Update(ie, refNbr, doc.AdjdDocType, doc.AdjdRefNbr, doc.AdjgDocType, doc.AdjgRefNbr));
                PXProcessing <PendingPPDCreditMemoApp> .SetInfo(index, ActionsMessages.RecordProcessed);
            }
            catch (Exception e)
            {
                PXProcessing <PendingPPDCreditMemoApp> .SetError(index, e);

                invoice = null;
            }

            return(invoice);
        }
Exemplo n.º 15
0
        public virtual void GenerateProc(Schedule s, short Times, DateTime runDate)
        {
            List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate);

            ARInvoiceEntry docgraph = CreateGraph();

            foreach (ScheduleDet sdet in sd)
            {
                foreach (PXResult <ARInvoice, Customer, CurrencyInfo> res in PXSelectJoin <ARInvoice, InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >, Where <ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >, And <ARInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID))
                {
                    docgraph.Clear();
                    docgraph.customer.Current = (Customer)res;
                    ARInvoice    apdoc = (ARInvoice)res;
                    CurrencyInfo info  = (CurrencyInfo)res;

                    CurrencyInfo new_info = PXCache <CurrencyInfo> .CreateCopy(info);

                    new_info.CuryInfoID = null;
                    new_info            = docgraph.currencyinfo.Insert(new_info);

                    ARInvoice new_ardoc = PXCache <ARInvoice> .CreateCopy(apdoc);

                    new_ardoc.CuryInfoID          = new_info.CuryInfoID;
                    new_ardoc.DocDate             = sdet.ScheduledDate;
                    new_ardoc.FinPeriodID         = sdet.ScheduledPeriod;
                    new_ardoc.TranPeriodID        = null;
                    new_ardoc.DueDate             = null;
                    new_ardoc.DiscDate            = null;
                    new_ardoc.CuryOrigDiscAmt     = null;
                    new_ardoc.OrigDiscAmt         = null;
                    new_ardoc.RefNbr              = null;
                    new_ardoc.Scheduled           = false;
                    new_ardoc.CuryLineTotal       = 0m;
                    new_ardoc.CuryVatTaxableTotal = 0m;
                    new_ardoc.CuryVatExemptTotal  = 0m;
                    new_ardoc.NoteID              = null;
                    bool forceClear = false;
                    bool clearPM    = false;
                    if (new_ardoc.PMInstanceID.HasValue)
                    {
                        PXResult <CustomerPaymentMethod, CA.PaymentMethod> pmiResult = (PXResult <CustomerPaymentMethod, CA.PaymentMethod>) PXSelectJoin <CustomerPaymentMethod, InnerJoin <CA.PaymentMethod, On <CA.PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >, Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(docgraph, new_ardoc.PMInstanceID);

                        if (pmiResult != null)
                        {
                            CustomerPaymentMethod pmInstance    = pmiResult;
                            CA.PaymentMethod      paymentMethod = pmiResult;
                            if (pmInstance == null || pmInstance.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                        else
                        {
                            clearPM    = true;
                            forceClear = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(new_ardoc.PaymentMethodID) == false)
                        {
                            CA.PaymentMethod pm = PXSelect <CA.PaymentMethod, Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > > .Select(docgraph, new_ardoc.PaymentMethodID);

                            if (pm == null || pm.IsActive != true || pm.UseForAR != true)
                            {
                                clearPM    = true;
                                forceClear = true;
                            }
                        }
                    }

                    if (clearPM)
                    {
                        new_ardoc.PMInstanceID    = null;
                        new_ardoc.PaymentMethodID = null;
                        new_ardoc.CashAccountID   = null;
                    }

                    new_ardoc = docgraph.Document.Insert(new_ardoc);

                    //force creditrule back
                    docgraph.customer.Current = (Customer)res;

                    if (forceClear == true)
                    {
                        ARInvoice copy = PXCache <ARInvoice> .CreateCopy(new_ardoc);

                        copy.PMInstanceID    = null;
                        copy.PaymentMethodID = null;
                        copy.CashAccountID   = null;
                        new_ardoc            = docgraph.Document.Update(copy);
                    }
                    AddressAttribute.CopyRecord <ARInvoice.billAddressID>(docgraph.Document.Cache, new_ardoc, apdoc, false);
                    ContactAttribute.CopyRecord <ARInvoice.billContactID>(docgraph.Document.Cache, new_ardoc, apdoc, false);

                    TaxAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    PXNoteAttribute.SetNote(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetNote(Caches[typeof(ARInvoice)], apdoc));
                    PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetFileNotes(Caches[typeof(ARInvoice)], apdoc));

                    foreach (ARTran aptran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTran new_aptran = PXCache <ARTran> .CreateCopy(aptran);

                        new_aptran.RefNbr     = null;
                        new_aptran.CuryInfoID = null;
                        docgraph.Transactions.Insert(new_aptran);
                    }

                    foreach (ARTaxTran tax in PXSelect <ARTaxTran, Where <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >, And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr))
                    {
                        ARTaxTran new_artax = new ARTaxTran();
                        new_artax.TaxID = tax.TaxID;

                        new_artax = docgraph.Taxes.Insert(new_artax);

                        if (new_artax != null)
                        {
                            new_artax = PXCache <ARTaxTran> .CreateCopy(new_artax);

                            new_artax.TaxRate        = tax.TaxRate;
                            new_artax.CuryTaxableAmt = tax.CuryTaxableAmt;
                            new_artax.CuryTaxAmt     = tax.CuryTaxAmt;
                            new_artax = docgraph.Taxes.Update(new_artax);
                        }
                    }

                    docgraph.Save.Press();
                }
                s.LastRunDate = sdet.ScheduledDate;
                Running_Schedule.Cache.Update(s);
            }

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                Running_Schedule.Cache.Persist(PXDBOperation.Update);
                ts.Complete(this);
            }
            Running_Schedule.Cache.Persisted(false);
        }
Exemplo n.º 16
0
        public virtual void Bill(CustomersList customer, EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

            arGraph.Clear();
            pmGraph.Clear();

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

            List <ARRegister>            doclist = new List <ARRegister>();
            List <EPExpenseClaimDetails> listOfDirectBilledClaims = new List <EPExpenseClaimDetails>();

            PXSelectBase <EPExpenseClaimDetails> select = new PXSelectJoin <EPExpenseClaimDetails,
                                                                            LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                    And <Where <Contract.baseType, Equal <CTPRType.contract>,
                                                                                                                Or <Contract.nonProject, Equal <True> > > > >,
                                                                                      LeftJoin <Account, On <EPExpenseClaimDetails.expenseAccountID, Equal <Account.accountID> > > >,
                                                                            Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                   And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                        And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                             And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                  And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                       And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                            And <Where <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                                        Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > >,
                                                                            OrderBy <Asc <EPExpenseClaimDetails.branchID> > >(this);

            arGraph.RowPersisted.AddHandler <ARInvoice>(
                delegate(PXCache sender, PXRowPersistedEventArgs e)
            {
                if (e.TranStatus == PXTranStatus.Open)
                {
                    foreach (EPExpenseClaimDetails row in listOfDirectBilledClaims.Select(claimdetail => Transactions.Locate(claimdetail)))
                    {
                        row.ARDocType = ((ARInvoice)e.Row).DocType;
                        row.ARRefNbr  = ((ARInvoice)e.Row).RefNbr;
                    }
                }
            });

            decimal signOperation = 1m;
            decimal tipQty        = 1m;

            var resultset = select.Select(customer.CustomerID, customer.LocationID, filter.EndDate).AsEnumerable();

            FinPeriodUtils.ValidateFinPeriod <EPExpenseClaimDetails>(
                resultset.RowCast <EPExpenseClaimDetails>(),
                m => filter.InvFinPeriodID,
                m => m.BranchID.SingleToArray());

            foreach (PXResult <EPExpenseClaimDetails, Contract, Account> res in resultset)
            {
                EPExpenseClaimDetails row = (EPExpenseClaimDetails)res;

                if (row.ContractID != null && !ProjectDefaultAttribute.IsNonProject(row.ContractID))
                {
                    if (pmDoc == null)
                    {
                        EPExpenseClaim claim = PXSelect <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(this, row.RefNbr);

                        pmDoc             = (PMRegister)pmGraph.Document.Cache.Insert();
                        pmDoc.OrigDocType = PMOrigDocType.ExpenseClaim;
                        pmDoc.OrigNoteID  = claim.NoteID;
                    }

                    PMTran usage = InsertPMTran(pmGraph, res);
                    if (usage.Released == true)                     //contract trans are created as released
                    {
                        UsageMaint.AddUsage(pmGraph.Transactions.Cache, usage.ProjectID, usage.InventoryID, usage.BillableQty ?? 0m, usage.UOM);
                    }
                }
                else
                {
                    if (arDoc == null || arDoc.BranchID != row.BranchID)
                    {
                        if (arDoc != null)
                        {
                            arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                            arGraph.Document.Update(arDoc);
                            arGraph.Save.Press();
                            listOfDirectBilledClaims.Clear();
                        }

                        EPExpenseClaimDetails summDetail = PXSelectJoinGroupBy <EPExpenseClaimDetails,
                                                                                LeftJoin <Contract, On <EPExpenseClaimDetails.contractID, Equal <Contract.contractID>,
                                                                                                        And <Where <Contract.baseType, Equal <CTPRType.contract>,
                                                                                                                    Or <Contract.nonProject, Equal <True> > > > > >,
                                                                                Where <EPExpenseClaimDetails.released, Equal <boolTrue>,
                                                                                       And <EPExpenseClaimDetails.billable, Equal <boolTrue>,
                                                                                            And <EPExpenseClaimDetails.billed, Equal <boolFalse>,
                                                                                                 And <EPExpenseClaimDetails.customerID, Equal <Required <EPExpenseClaimDetails.customerID> >,
                                                                                                      And <EPExpenseClaimDetails.customerLocationID, Equal <Required <EPExpenseClaimDetails.customerLocationID> >,
                                                                                                           And <EPExpenseClaimDetails.expenseDate, LessEqual <Required <EPExpenseClaimDetails.expenseDate> >,
                                                                                                                And <EPExpenseClaimDetails.branchID, Equal <Required <EPExpenseClaimDetails.branchID> >,
                                                                                                                     And <Where <Contract.nonProject, Equal <True>,
                                                                                                                                 Or <EPExpenseClaimDetails.contractID, IsNull> > > > > > > > > >,
                                                                                Aggregate <Sum <EPExpenseClaimDetails.curyTranAmt> > >
                                                           .Select(this, customer.CustomerID, customer.LocationID, filter.EndDate, row.BranchID);

                        signOperation = summDetail.CuryTranAmt < 0 ? -1 : 1;

                        // OrigModule should be set before Insert() method
                        // to organize proper defaulting for any other fields
                        // which depend on OrigModule value.
                        //
                        arDoc            = new ARInvoice();
                        arDoc.OrigModule = BatchModule.EP;
                        arGraph.Document.Cache.SetValueExt <ARInvoice.docType>(arDoc,
                                                                               signOperation < 0 ? ARDocType.CreditMemo : ARDocType.Invoice);

                        arDoc = (ARInvoice)arGraph.Document.Cache.Insert(arDoc);

                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerID>(arDoc, row.CustomerID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.customerLocationID>(arDoc, row.CustomerLocationID);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.docDate>(arDoc, filter.InvoiceDate);
                        arGraph.Document.Cache.SetValueExt <ARInvoice.branchID>(arDoc, row.BranchID);
                        arDoc.OrigRefNbr  = row.RefNbr;
                        arDoc             = arGraph.Document.Update(arDoc);
                        arDoc.FinPeriodID = filter.InvFinPeriodID;
                        doclist.Add(arDoc);
                    }

                    // Insert ARTran.
                    //
                    InsertARTran(arGraph, row, signOperation);
                    if ((row.CuryTipAmt ?? 0) != 0)
                    {
                        tipQty = signOperation < 0 == row.ClaimCuryTranAmtWithTaxes < 0 ? 1 : -1;
                        InsertARTran(arGraph, row, signOperation, tipQty, true);
                    }

                    listOfDirectBilledClaims.Add(row);
                }

                row.Billed = true;
                Transactions.Update(row);
            }

            if (arDoc != null)
            {
                arDoc.CuryOrigDocAmt = arDoc.CuryDocBal;
                if (arGraph.ARSetup.Current.HoldEntry == false || Setup.Current.AutomaticReleaseAR == true)
                {
                    arDoc = PXCache <ARInvoice> .CreateCopy(arDoc);

                    arDoc.Hold = false;
                    arDoc      = arGraph.Document.Update(arDoc);
                }
                arGraph.Document.Update(arDoc);
                arGraph.Save.Press();
            }

            if (pmDoc != null)
            {
                pmGraph.Save.Press();
            }

            Persist(typeof(EPExpenseClaimDetails), PXDBOperation.Update);

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }