Exemplo n.º 1
0
        protected virtual void PMTran_InventoryID_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            PMTran row = (PMTran)e.Row;

            if (row?.InventoryID == null)
            {
                return;
            }
            InventoryItem inventory = PXSelect <InventoryItem,
                                                Where <InventoryItem.inventoryID, Equal <Required <PMTran.inventoryID> > > > .Select(this, row.InventoryID);

            if (inventory != null)
            {
                row.Description = inventory.Descr;

                PMProject project = PXSelect <PMProject,
                                              Where <PMProject.contractID, Equal <Required <PMTran.projectID> > > > .Select(this, row.ProjectID);

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

                    if (customer != null && !string.IsNullOrEmpty(customer.LocaleName))
                    {
                        row.Description = PXDBLocalizableStringAttribute.GetTranslation(Caches[typeof(InventoryItem)], inventory, nameof(InventoryItem.Descr), customer.LocaleName);
                    }
                }
            }
        }
Exemplo n.º 2
0
        protected virtual PMTran InsertPMTran(RegisterEntry pmGraph, PXResult <EPExpenseClaimDetails, Contract, Account> res)
        {
            EPExpenseClaimDetails detail = res;
            Contract contract            = res;
            Account  account             = res;

            if (account.AccountGroupID == null && contract.BaseType == CTPRType.Project)
            {
                throw new PXException(Messages.AccountGroupIsNotAssignedForAccount, account.AccountCD);
            }

            bool released = contract.BaseType == CTPRType.Contract;             //contract trans are created as released

            PMTran tran = (PMTran)pmGraph.Transactions.Cache.Insert();

            tran.AccountGroupID   = account.AccountGroupID;
            tran.BAccountID       = detail.CustomerID;
            tran.LocationID       = detail.CustomerLocationID;
            tran.ProjectID        = detail.ContractID;
            tran.TaskID           = detail.TaskID;
            tran.CostCodeID       = detail.CostCodeID;
            tran.InventoryID      = detail.InventoryID;
            tran.Qty              = detail.Qty;
            tran.Billable         = true;
            tran.BillableQty      = detail.Qty;
            tran.UOM              = detail.UOM;
            tran.TranCuryID       = detail.CuryID;
            tran.BaseCuryInfoID   = detail.CuryInfoID;
            tran.TranCuryAmount   = detail.ClaimCuryTranAmt;
            tran.Amount           = detail.ClaimTranAmt;
            tran.TranCuryUnitRate = detail.CuryUnitCost;
            tran.UnitRate         = detail.UnitCost;

            //TODO: Review the following code (exists only to support MA302 case when UnitCost is not entered):
            if (detail.CuryUnitCost == 0m && detail.Qty != 0)
            {
                tran.TranCuryUnitRate = detail.ClaimCuryTranAmt / detail.Qty;
                tran.UnitRate         = detail.ClaimTranAmt / detail.Qty;
            }
            tran.AccountID  = detail.ExpenseAccountID;
            tran.SubID      = detail.ExpenseSubID;
            tran.StartDate  = detail.ExpenseDate;
            tran.EndDate    = detail.ExpenseDate;
            tran.Date       = detail.ExpenseDate;
            tran.ResourceID = detail.EmployeeID;
            tran.Released   = released;

            tran = pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = released;
            if (released)
            {
                pmGraph.Document.Current.Status = PMRegister.status.Released;
            }

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], detail, pmGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.pm>());

            return(tran);
        }
        protected void EPEarningType_RowDeleting(PXCache sender, PXRowDeletingEventArgs e)
        {
            EPEarningType row = (EPEarningType)e.Row;

            if (row == null)
            {
                return;
            }

            EPSetup setup = PXSelect <
                EPSetup
                , Where <EPSetup.regularHoursType, Equal <Required <EPEarningType.typeCD> >
                         , Or <EPSetup.holidaysType, Equal <Required <EPEarningType.typeCD> >
                               , Or <EPSetup.vacationsType, Equal <Required <EPEarningType.typeCD> > >
                               >
                         >
                > .Select(this, row.TypeCD, row.TypeCD, row.TypeCD);

            if (setup != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }

            CRCaseClassLaborMatrix caseClassLabor = PXSelect <CRCaseClassLaborMatrix, Where <CRCaseClassLaborMatrix.earningType, Equal <Required <EPEarningType.typeCD> > > > .Select(this, row.TypeCD);

            if (caseClassLabor != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }

            EPContractRate contractRate = PXSelect <EPContractRate, Where <EPContractRate.earningType, Equal <Required <EPEarningType.typeCD> > > > .Select(this, row.TypeCD);

            if (contractRate != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }

            EPEmployeeClassLaborMatrix employeeLabor = PXSelect <EPEmployeeClassLaborMatrix, Where <EPEmployeeClassLaborMatrix.earningType, Equal <Required <EPEarningType.typeCD> > > > .Select(this, row.TypeCD);

            if (employeeLabor != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }

            PMTimeActivity activity = PXSelect <PMTimeActivity, Where <PMTimeActivity.earningTypeID, Equal <Required <EPEarningType.typeCD> > > > .Select(this, row.TypeCD);

            if (activity != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }

            PMTran pmTran = PXSelect <PMTran, Where <PMTran.earningType, Equal <Required <EPEarningType.typeCD> > > > .Select(this, row.TypeCD);

            if (pmTran != null)
            {
                throw new PXException(Messages.CannotDeleteInUse);
            }
        }
Exemplo n.º 4
0
        protected virtual void PMTran_RowDeleted(PXCache sender, PXRowDeletedEventArgs e)
        {
            PMTran row = e.Row as PMTran;

            if (row != null && row.BillableQty != 0)
            {
                SubtractUsage(sender, row.ProjectID, row.InventoryID, row.BillableQty ?? 0m, row.UOM);
            }
        }
Exemplo n.º 5
0
        protected virtual void PMTran_BillableQty_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            PMTran row = e.Row as PMTran;

            if (row != null)
            {
                AddUsage(sender, row.ProjectID, row.InventoryID, (row.BillableQty ?? 0m) - ((decimal?)e.OldValue ?? 0m), row.UOM);
            }
        }
Exemplo n.º 6
0
        protected virtual void PMTran_UOM_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
        {
            PMTran row = e.Row as PMTran;

            if (row != null && row.BillableQty != 0)
            {
                SubtractUsage(sender, row.ProjectID, row.InventoryID, row.BillableQty ?? 0m, (string)e.OldValue);
                AddUsage(sender, row.ProjectID, row.InventoryID, row.BillableQty ?? 0m, row.UOM);
            }
        }
Exemplo n.º 7
0
        protected virtual void InsertPMTran(RegisterEntry pmGraph, EPExpenseClaimDetails row, EPExpenseClaim doc, bool copyNotes, bool copyFiles)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(pmGraph, row.ContractID);

            Account account = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(this, row.ExpenseAccountID);

            if (account.AccountGroupID == null && project.BaseType == PMProject.ProjectBaseType.Project)
            {
                throw new PXException(Messages.AccountGroupIsNotAssignedForAccount, account.AccountCD);
            }

            PMTran tran = (PMTran)pmGraph.Transactions.Cache.Insert();

            tran.AccountGroupID = account.AccountGroupID;
            tran.BAccountID     = row.CustomerID;
            tran.LocationID     = row.CustomerLocationID;
            tran.ProjectID      = row.ContractID;
            tran.TaskID         = row.TaskID;
            tran.InventoryID    = row.InventoryID;
            tran.Qty            = row.Qty;
            tran.Billable       = true;
            tran.BillableQty    = row.Qty;
            tran.UOM            = row.UOM;
            tran.UnitRate       = row.UnitCost;
            tran.Amount         = row.TranAmt;
            tran.AccountID      = row.ExpenseAccountID;
            tran.SubID          = row.ExpenseSubID;
            tran.StartDate      = row.ExpenseDate;
            tran.EndDate        = row.ExpenseDate;
            tran.Date           = row.ExpenseDate;
            tran.ResourceID     = doc.EmployeeID;
            tran.Released       = project.BaseType == PMProject.ContractBaseType.Contract;      //contract trans are created as released

            pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = project.BaseType == PMProject.ContractBaseType.Contract;

            if (copyNotes)
            {
                string note = PXNoteAttribute.GetNote(Caches[typeof(EPExpenseClaimDetails)], row);
                if (note != null)
                {
                    PXNoteAttribute.SetNote(pmGraph.Transactions.Cache, tran, note);
                }
            }
            if (copyFiles)
            {
                Guid[] files = PXNoteAttribute.GetFileNotes(Caches[typeof(EPExpenseClaimDetails)], row);
                if (files != null && files.Length > 0)
                {
                    PXNoteAttribute.SetFileNotes(pmGraph.Transactions.Cache, tran, files);
                }
            }
        }
Exemplo n.º 8
0
        protected virtual PMTran InsertPMTran(RegisterEntry pmGraph, PXResult <EPExpenseClaimDetails, Contract, Account> res)
        {
            EPExpenseClaimDetails detail = res;
            Contract contract            = res;
            Account  account             = res;

            if (account.AccountGroupID == null && contract.BaseType == PMProject.ProjectBaseType.Project)
            {
                throw new PXException(Messages.AccountGroupIsNotAssignedForAccount, account.AccountCD);
            }

            bool released = contract.BaseType == Contract.ContractBaseType.Contract;             //contract trans are created as released

            PMTran tran = (PMTran)pmGraph.Transactions.Cache.Insert();

            tran.AccountGroupID = account.AccountGroupID;
            tran.BAccountID     = detail.CustomerID;
            tran.LocationID     = detail.CustomerLocationID;
            tran.ProjectID      = detail.ContractID;
            tran.TaskID         = detail.TaskID;
            tran.InventoryID    = detail.InventoryID;
            tran.Qty            = detail.Qty;
            tran.Billable       = true;
            tran.BillableQty    = detail.Qty;
            tran.UOM            = detail.UOM;
            if (detail.CuryInfoID == detail.ClaimCuryInfoID && detail.EmployeePart == 0m)
            {
                tran.UnitRate = detail.UnitCost;
            }
            else
            {
                tran.UnitRate = detail.ClaimTranAmt / detail.Qty;
            }
            tran.Amount     = detail.ClaimTranAmt;
            tran.AccountID  = detail.ExpenseAccountID;
            tran.SubID      = detail.ExpenseSubID;
            tran.StartDate  = detail.ExpenseDate;
            tran.EndDate    = detail.ExpenseDate;
            tran.Date       = detail.ExpenseDate;
            tran.ResourceID = detail.EmployeeID;
            tran.Released   = released;

            tran = pmGraph.Transactions.Update(tran);

            pmGraph.Document.Current.Released = released;

            PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(EPExpenseClaimDetails)], detail, pmGraph.Transactions.Cache, tran, Setup.Current.GetCopyNoteSettings <PXModule.pm>());

            return(tran);
        }
 public TranNotePair(PMTran tran, Note note)
 {
     this.Tran = tran;
     this.Note = note;
 }
Exemplo n.º 10
0
        ///NO CRM Mode
        public static PMTran CreateContractUsage(RegisterEntry graph, int?contractID, PMTimeActivity timeActivity, int billableMinutes)
        {
            if (timeActivity.ApprovalStatus == ActivityStatusListAttribute.Canceled)
            {
                return(null);
            }

            if (timeActivity.IsBillable != true)
            {
                return(null);
            }

            Contract contract = PXSelect <Contract,
                                          Where <Contract.contractID, Equal <Required <Contract.contractID> > > > .Select(graph, contractID);

            if (contract == null)
            {
                return(null);               //activity has no contract and will be billed through Project using the cost-transaction. Contract-Usage is not created in this case.
            }
            int?laborItemID = GetContractLaborClassID(graph, contractID, timeActivity);;

            if (laborItemID == null)
            {
                EPEmployee employeeSettings = PXSelect <EPEmployee,
                                                        Where <EPEmployee.userID, Equal <Required <EPEmployee.userID> > > > .Select(graph, timeActivity.OwnerID);

                if (employeeSettings != null)
                {
                    laborItemID =
                        EPEmployeeClassLaborMatrix.GetLaborClassID(graph, employeeSettings.BAccountID, timeActivity.EarningTypeID) ??
                        employeeSettings.LabourItemID;
                }
            }

            InventoryItem laborItem = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(graph, laborItemID);

            if (laborItem == null)
            {
                throw new PXException(PX.Objects.CR.Messages.LaborNotConfigured);
            }

            //save the sign of the value and do the rounding against absolute value.
            //reuse sign later when setting value to resulting transaction.
            int sign = billableMinutes < 0 ? -1 : 1;

            billableMinutes = Math.Abs(billableMinutes);


            if (billableMinutes > 0)
            {
                PMTran newLabourTran = new PMTran();
                newLabourTran.ProjectID      = contractID;
                newLabourTran.InventoryID    = laborItem.InventoryID;
                newLabourTran.AccountGroupID = contract.ContractAccountGroup;
                newLabourTran.OrigRefID      = timeActivity.NoteID;
                newLabourTran.BAccountID     = contract.CustomerID;
                newLabourTran.LocationID     = contract.LocationID;
                newLabourTran.Description    = timeActivity.Summary;
                newLabourTran.StartDate      = timeActivity.Date;
                newLabourTran.EndDate        = timeActivity.Date;
                newLabourTran.Date           = timeActivity.Date;
                newLabourTran.UOM            = laborItem.SalesUnit;
                newLabourTran.Qty            = sign * Convert.ToDecimal(TimeSpan.FromMinutes(billableMinutes).TotalHours);
                newLabourTran.BillableQty    = newLabourTran.Qty;
                newLabourTran.Released       = true;
                newLabourTran.Allocated      = true;
                newLabourTran.IsQtyOnly      = true;
                newLabourTran.BillingID      = contract.BillingID;
                return(graph.Transactions.Insert(newLabourTran));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 11
0
        public static List <EPActivityApprove> RecordContractUsage(List <EPActivityApprove> activities, string description)
        {
            RegisterEntry registerEntry = CreateInstance <RegisterEntry>();

            registerEntry.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });
            registerEntry.FieldVerifying.AddHandler <PMTran.inventoryID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; });//restriction should be applicable only for budgeting.
            registerEntry.Document.Cache.Insert();
            registerEntry.Document.Current.Description = description;
            registerEntry.Document.Current.Released    = true;
            registerEntry.Document.Current.Status      = PMRegister.status.Released;
            registerEntry.Views.Caches.Add(typeof(EPActivityApprove));
            PXCache activityCache = registerEntry.Caches <EPActivityApprove>();
            List <EPActivityApprove> useActivities = new List <EPActivityApprove>();

            for (int i = 0; i < activities.Count; i++)
            {
                EPActivityApprove activity = activities[i];
                try
                {
                    PMTran usage = null;
                    if (activity.ContractID != null)
                    {
                        //Contract without CRM mode
                        usage           = CreateContractUsage(registerEntry, activity.ContractID, activity, activity.TimeBillable.GetValueOrDefault());
                        activity.Billed = true;
                        activityCache.Update(activity);
                    }
                    else if (activity.RefNoteID != null &&
                             PXSelectJoin <CRCase,
                                           InnerJoin <CRActivityLink,
                                                      On <CRActivityLink.refNoteID, Equal <CRCase.noteID> > >,
                                           Where <CRActivityLink.noteID, Equal <Required <PMTimeActivity.refNoteID> > > > .Select(registerEntry, activity.RefNoteID).Count == 1)
                    {
                        //Add Contract-Usage
                        usage           = registerEntry.CreateContractUsage(activity, activity.TimeBillable.GetValueOrDefault());
                        activity.Billed = true;
                        activityCache.Update(activity);
                    }
                    if (usage != null)
                    {
                        UsageMaint.AddUsage(activityCache, usage.ProjectID, usage.InventoryID, usage.BillableQty ?? 0m, usage.UOM);
                    }

                    useActivities.Add(activity);
                }
                catch (Exception e)
                {
                    PXProcessing <EPActivityApprove> .SetError(i, e is PXOuterException?e.Message + "\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message);
                }
            }

            if (registerEntry.Transactions.Cache.IsInsertedUpdatedDeleted)
            {
                registerEntry.Save.Press();
            }
            else
            {
                activityCache.Persist(PXDBOperation.Update);
            }

            return(useActivities);
        }
Exemplo n.º 12
0
        public virtual void CreateInvoice(PXGraph graphProcess, List <DocLineExt> docLines, List <DocLineExt> docLinesGrouped, short invtMult, DateTime?invoiceDate, string invoiceFinPeriodID, OnDocumentHeaderInsertedDelegate onDocumentHeaderInserted, OnTransactionInsertedDelegate onTransactionInserted, PXQuickProcess.ActionFlow quickProcessFlow)
        {
            if (docLines.Count == 0)
            {
                return;
            }

            FSServiceOrder fsServiceOrderRow = docLines[0].fsServiceOrder;
            FSSrvOrdType   fsSrvOrdTypeRow   = docLines[0].fsSrvOrdType;
            FSPostDoc      fsPostDocRow      = docLines[0].fsPostDoc;
            FSAppointment  fsAppointmentRow  = docLines[0].fsAppointment;

            PMRegister pmRegisterRow = new PMRegister();

            pmRegisterRow.Module      = BatchModule.PM;
            pmRegisterRow.Date        = invoiceDate;
            pmRegisterRow.Description = fsAppointmentRow != null ? fsAppointmentRow.DocDesc : fsServiceOrderRow.DocDesc;
            pmRegisterRow.Status      = PMRegister.status.Balanced;
            pmRegisterRow.OrigDocType = fsAppointmentRow != null ? PMOrigDocType.Appointment : PMOrigDocType.ServiceOrder;
            pmRegisterRow.OrigNoteID  = fsAppointmentRow != null ? fsAppointmentRow.NoteID : fsServiceOrderRow.NoteID;

            pmRegisterRow = PXCache <PMRegister> .CreateCopy(Base.Document.Insert(pmRegisterRow));

            IDocLine docLine   = null;
            PMTask   pmTaskRow = null;
            PMTran   pmTranRow = null;

            foreach (DocLineExt docLineExt in docLinesGrouped)
            {
                docLine           = docLineExt.docLine;
                fsPostDocRow      = docLineExt.fsPostDoc;
                fsServiceOrderRow = docLineExt.fsServiceOrder;
                fsSrvOrdTypeRow   = docLineExt.fsSrvOrdType;
                fsAppointmentRow  = docLineExt.fsAppointment;

                pmTranRow = new PMTran();

                pmTranRow.Date     = invoiceDate;
                pmTranRow.BranchID = docLine.BranchID;

                pmTranRow = PXCache <PMTran> .CreateCopy(Base.Transactions.Insert(pmTranRow));

                pmTaskRow = docLineExt.pmTask;

                if (pmTaskRow != null && pmTaskRow.Status == ProjectTaskStatus.Completed)
                {
                    throw new PXException(TX.Error.POSTING_PMTASK_ALREADY_COMPLETED, fsServiceOrderRow.RefNbr, docLine.LineRef, pmTaskRow.TaskCD);
                }

                if (docLine.ProjectID != null)
                {
                    pmTranRow.ProjectID = docLine.ProjectID;
                }

                if (docLine.ProjectID != null && docLine.ProjectTaskID != null)
                {
                    pmTranRow.TaskID = docLine.ProjectTaskID;
                }

                pmTranRow.TranCuryID       = fsAppointmentRow != null ? fsAppointmentRow.CuryID : fsServiceOrderRow.CuryID;
                pmTranRow.UOM              = docLine.UOM;
                pmTranRow.BAccountID       = fsServiceOrderRow.BillCustomerID;
                pmTranRow.Billable         = true;
                pmTranRow.InventoryID      = docLine.InventoryID;
                pmTranRow.CostCodeID       = docLine.CostCodeID;
                pmTranRow.LocationID       = fsServiceOrderRow.BillLocationID;
                pmTranRow.Qty              = docLine.GetQty(FieldType.BillableField);
                pmTranRow.FinPeriodID      = invoiceFinPeriodID;
                pmTranRow.TranCuryUnitRate = docLine.CuryUnitPrice * invtMult;
                pmTranRow.TranCuryAmount   = docLine.GetTranAmt(FieldType.BillableField) * invtMult;
                pmTranRow.AccountGroupID   = fsSrvOrdTypeRow.AccountGroupID;
                pmTranRow.Description      = docLine.TranDesc;

                fsPostDocRow.DocLineRef = pmTranRow = Base.Transactions.Update(pmTranRow);
            }
        }
Exemplo n.º 13
0
 public virtual void AssignAdditionalFields(GLTran glTran, PMTran pmTran)
 {
 }
Exemplo n.º 14
0
 public virtual void AssignCustomerVendorEmployee(GLTran glTran, PMTran pmTran)
 {
     pmTran.BAccountID = glTran.ReferenceID;
 }
Exemplo n.º 15
0
        public virtual List <PMTask> CreateProjectTrans()
        {
            var autoAllocateTasks = new List <PMTask>();

            if (Base.BatchModule.Current != null && Base.BatchModule.Current.Module != BatchModule.GL)
            {
                PXResultset <GLTran> trans = new PXSelect <GLTran,
                                                           Where <GLTran.module, Equal <Current <Batch.module> >,
                                                                  And <GLTran.batchNbr, Equal <Current <Batch.batchNbr> >,
                                                                       And <GLTran.pMTranID, IsNull,
                                                                            And <GLTran.isNonPM, NotEqual <True> > > > > >(Base).Select();

                if (trans.Count > 0)
                {
                    ProjectBalance pb = CreateProjectBalance();
                    var            tasksToAutoAllocate = new Dictionary <string, PMTask>();
                    var            sourceForAllocation = new List <PMTran>();

                    var doc = new PMRegister();
                    doc.Module      = Base.BatchModule.Current.Module;
                    doc.Date        = Base.BatchModule.Current.DateEntered;
                    doc.Description = Base.BatchModule.Current.Description;
                    doc.Released    = true;
                    doc.Status      = PMRegister.status.Released;
                    bool docInserted = false;                     //to prevent creating empty batch
                    JournalEntryTranRef entryRefGraph = PXGraph.CreateInstance <JournalEntryTranRef>();

                    foreach (GLTran tran in trans)
                    {
                        var acc = (Account)PXSelect <Account,
                                                     Where <Account.accountID, Equal <Required <GLTran.accountID> >,
                                                            And <Account.accountGroupID, IsNotNull> > > .Select(Base, tran.AccountID);

                        if (acc == null)
                        {
                            continue;
                        }

                        var ag = (PMAccountGroup)PXSelect <PMAccountGroup,
                                                           Where <PMAccountGroup.groupID, Equal <Required <Account.accountGroupID> >,
                                                                  And <PMAccountGroup.type, NotEqual <PMAccountType.offBalance> > > > .Select(Base, acc.AccountGroupID);

                        if (ag == null)
                        {
                            continue;
                        }

                        var project = (PMProject)PXSelect <PMProject,
                                                           Where <PMProject.contractID, Equal <Required <GLTran.projectID> >,
                                                                  And <PMProject.nonProject, Equal <False> > > > .Select(Base, tran.ProjectID);

                        if (project == null)
                        {
                            continue;
                        }

                        var task = (PMTask)PXSelect <PMTask,
                                                     Where <PMTask.projectID, Equal <Required <GLTran.projectID> >,
                                                            And <PMTask.taskID, Equal <Required <GLTran.taskID> > > > > .Select(Base, tran.ProjectID, tran.TaskID);

                        if (task == null)
                        {
                            continue;
                        }

                        APTran apTran = null;
                        if (Base.BatchModule.Current.Module == BatchModule.AP)
                        {
                            apTran = (APTran)PXSelect <APTran,
                                                       Where <APTran.refNbr, Equal <Required <GLTran.refNbr> >,
                                                              And <APTran.lineNbr, Equal <Required <GLTran.tranLineNbr> >,
                                                                   And <APTran.tranType, Equal <Required <GLTran.tranType> > > > > > .Select(Base, tran.RefNbr, tran.TranLineNbr, tran.TranType);
                        }

                        ARTran arTran = null;
                        if (Base.BatchModule.Current.Module == BatchModule.AR)
                        {
                            arTran = (ARTran)PXSelect <ARTran,
                                                       Where <ARTran.refNbr, Equal <Required <GLTran.refNbr> >,
                                                              And <ARTran.lineNbr, Equal <Required <GLTran.tranLineNbr> >,
                                                                   And <ARTran.tranType, Equal <Required <GLTran.tranType> > > > > > .Select(Base, tran.RefNbr, tran.TranLineNbr, tran.TranType);
                        }

                        if (!docInserted)
                        {
                            doc         = ProjectDocs.Insert(doc);
                            docInserted = true;
                        }

                        doc.OrigDocType = entryRefGraph.GetDocType(apTran, arTran, tran);
                        doc.OrigNoteID  = entryRefGraph.GetNoteID(apTran, arTran, tran);

                        PMTran pmt = (PMTran)ProjectTrans.Cache.Insert();

                        pmt.BranchID       = tran.BranchID;
                        pmt.AccountGroupID = acc.AccountGroupID;
                        pmt.AccountID      = tran.AccountID;
                        pmt.SubID          = tran.SubID;
                        entryRefGraph.AssignCustomerVendorEmployee(tran, pmt);                         //CustomerLocation is lost.
                        //pmt.BatchNbr = tran.BatchNbr;
                        pmt.Date         = tran.TranDate;
                        pmt.TranDate     = tran.TranDate;
                        pmt.Description  = tran.TranDesc;
                        pmt.FinPeriodID  = tran.FinPeriodID;
                        pmt.TranPeriodID = tran.TranPeriodID;
                        pmt.InventoryID  = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID;
                        pmt.OrigLineNbr  = tran.LineNbr;
                        pmt.OrigModule   = tran.Module;
                        pmt.OrigRefNbr   = tran.RefNbr;
                        pmt.OrigTranType = tran.TranType;
                        pmt.ProjectID    = tran.ProjectID;
                        pmt.TaskID       = tran.TaskID;
                        pmt.CostCodeID   = tran.CostCodeID;
                        if (arTran != null)
                        {
                            pmt.Billable                  = false;
                            pmt.ExcludedFromBilling       = true;
                            pmt.ExcludedFromBillingReason = arTran.TranType == ARDocType.CreditMemo ?
                                                            PXMessages.LocalizeFormatNoPrefix(Messages.ExcludedFromBillingAsCreditMemoResult, arTran.RefNbr) :
                                                            PXMessages.LocalizeFormatNoPrefix(Messages.ExcludedFromBillingAsARInvoiceResult, arTran.RefNbr);
                        }
                        else
                        {
                            pmt.Billable = tran.NonBillable != true;
                        }
                        pmt.Released = true;

                        if (apTran != null && apTran.Date != null)
                        {
                            pmt.Date = apTran.Date;
                        }

                        pmt.UseBillableQty = true;
                        pmt.UOM            = tran.UOM;

                        pmt.Amount = tran.DebitAmt - tran.CreditAmt;

                        CurrencyInfo projectCuryInfo = null;
                        if (PXAccess.FeatureInstalled <FeaturesSet.projectMultiCurrency>())
                        {
                            pmt.TranCuryID     = Base.BatchModule.Current.CuryID;
                            pmt.ProjectCuryID  = project.CuryID;
                            pmt.BaseCuryInfoID = tran.CuryInfoID;
                            pmt.TranCuryAmount = tran.CuryDebitAmt - tran.CuryCreditAmt;

                            if (project.CuryID == Base.ledger.Current.BaseCuryID)
                            {
                                pmt.ProjectCuryInfoID = tran.CuryInfoID;
                                pmt.ProjectCuryAmount = pmt.Amount;
                            }
                            else if (project.CuryID == Base.BatchModule.Current.CuryID)
                            {
                                projectCuryInfo                = new CurrencyInfo();
                                projectCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                projectCuryInfo.BaseCuryID     = project.CuryID;
                                projectCuryInfo.CuryID         = project.CuryID;
                                projectCuryInfo.CuryRateTypeID = project.RateTypeID ?? Base.CMSetup.Current.PMRateTypeDflt;
                                projectCuryInfo.CuryEffDate    = tran.TranDate;
                                projectCuryInfo.CuryRate       = 1;
                                projectCuryInfo.RecipRate      = 1;
                                projectCuryInfo                = Base.currencyinfo.Insert(projectCuryInfo);
                                pmt.ProjectCuryInfoID          = projectCuryInfo.CuryInfoID;
                                pmt.ProjectCuryAmount          = pmt.TranCuryAmount;
                            }
                            else
                            {
                                CM.Extensions.IPXCurrencyService currencyService = ServiceLocator.Current.GetInstance <Func <PXGraph, CM.Extensions.IPXCurrencyService> >()(Base);

                                projectCuryInfo                = new CurrencyInfo();
                                projectCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                projectCuryInfo.BaseCuryID     = project.CuryID;
                                projectCuryInfo.CuryID         = Base.BatchModule.Current.CuryID;
                                projectCuryInfo.CuryRateTypeID = project.RateTypeID ?? currencyService.DefaultRateTypeID(BatchModule.PM);
                                projectCuryInfo.CuryEffDate    = tran.TranDate;

                                var rate = currencyService.GetRate(projectCuryInfo.CuryID, projectCuryInfo.BaseCuryID, projectCuryInfo.CuryRateTypeID, projectCuryInfo.CuryEffDate);
                                if (rate == null)
                                {
                                    throw new PXException(PM.Messages.FxTranToProjectNotFound, projectCuryInfo.CuryID, projectCuryInfo.BaseCuryID, projectCuryInfo.CuryRateTypeID, tran.TranDate);
                                }

                                projectCuryInfo       = Base.currencyinfo.Insert(projectCuryInfo);
                                pmt.ProjectCuryInfoID = projectCuryInfo.CuryInfoID;
                                decimal val;
                                PXCurrencyAttribute.CuryConvBase(Base.BatchModule.Cache, projectCuryInfo, pmt.TranCuryAmount.GetValueOrDefault(), out val);
                                pmt.ProjectCuryAmount = val;
                            }
                        }
                        else
                        {
                            pmt.TranCuryAmount    = pmt.Amount;
                            pmt.ProjectCuryAmount = pmt.Amount;
                            pmt.TranCuryID        = Base.ledger.Current.BaseCuryID;
                            pmt.ProjectCuryID     = Base.ledger.Current.BaseCuryID;

                            if (Base.BatchModule.Current.CuryID != Base.ledger.Current.BaseCuryID)
                            {
                                CurrencyInfo baseCuryInfo = new CurrencyInfo();
                                baseCuryInfo.ModuleCode     = GL.BatchModule.PM;
                                baseCuryInfo.BaseCuryID     = Base.ledger.Current.BaseCuryID;
                                baseCuryInfo.CuryID         = Base.ledger.Current.BaseCuryID;
                                baseCuryInfo.CuryRateTypeID = null;
                                baseCuryInfo.CuryEffDate    = tran.TranDate;
                                baseCuryInfo.CuryRate       = 1;
                                baseCuryInfo.RecipRate      = 1;
                                baseCuryInfo          = Base.currencyinfo.Insert(baseCuryInfo);
                                pmt.ProjectCuryInfoID = baseCuryInfo.CuryInfoID;
                                pmt.BaseCuryInfoID    = baseCuryInfo.CuryInfoID;
                            }
                            else
                            {
                                pmt.ProjectCuryInfoID = tran.CuryInfoID;
                                pmt.BaseCuryInfoID    = tran.CuryInfoID;
                            }
                        }

                        pmt.Qty = tran.Qty;                        //pmt.Amount >= 0 ? tran.Qty : (tran.Qty * -1);
                        int sign = 1;
                        if (acc.Type == AccountType.Income || acc.Type == AccountType.Liability)
                        {
                            sign = -1;
                        }

                        if (ProjectBalance.IsFlipRequired(acc.Type, ag.Type))
                        {
                            pmt.ProjectCuryAmount = -pmt.ProjectCuryAmount;
                            pmt.TranCuryAmount    = -pmt.TranCuryAmount;
                            pmt.Amount            = -pmt.Amount;
                            pmt.Qty = -pmt.Qty;
                        }
                        pmt.BillableQty = pmt.Qty;


                        Base.GLTranModuleBatNbr.SetValueExt <GLTran.pMTranID>(tran, pmt.TranID);

                        if (apTran != null && apTran.NoteID != null)
                        {
                            PXNoteAttribute.CopyNoteAndFiles(Base.Caches[typeof(AP.APTran)], apTran, ProjectTrans.Cache, pmt);
                        }
                        else if (arTran != null && arTran.NoteID != null)
                        {
                            PXNoteAttribute.CopyNoteAndFiles(Base.Caches[typeof(AR.ARTran)], arTran, ProjectTrans.Cache, pmt);
                        }

                        ProjectBalance.Result balance = pb.Calculate(project, pmt, ag, acc.Type, sign, 1);

                        if (balance.Status != null)
                        {
                            PMBudgetAccum ps = new PMBudgetAccum();
                            ps.ProjectID      = balance.Status.ProjectID;
                            ps.ProjectTaskID  = balance.Status.ProjectTaskID;
                            ps.AccountGroupID = balance.Status.AccountGroupID;
                            ps.InventoryID    = balance.Status.InventoryID;
                            ps.CostCodeID     = balance.Status.CostCodeID;
                            ps.UOM            = balance.Status.UOM;
                            ps.IsProduction   = balance.Status.IsProduction;
                            ps.Type           = balance.Status.Type;
                            ps.Description    = balance.Status.Description;
                            ps.CuryInfoID     = balance.Status.CuryInfoID;

                            ps                   = ProjectBudget.Insert(ps);
                            ps.ActualQty        += balance.Status.ActualQty.GetValueOrDefault();
                            ps.CuryActualAmount += balance.Status.CuryActualAmount.GetValueOrDefault();
                            ps.ActualAmount     += balance.Status.ActualAmount.GetValueOrDefault();

                            if (arTran != null && arTran.LineNbr != null && ag.Type == GL.AccountType.Income)
                            {
                                ps.CuryInvoicedAmount -= balance.Status.CuryActualAmount.GetValueOrDefault();
                                ps.InvoicedAmount     -= balance.Status.ActualAmount.GetValueOrDefault();
                            }
                        }

                        if (balance.ForecastHistory != null)
                        {
                            PMForecastHistoryAccum forecast = new PMForecastHistoryAccum();
                            forecast.ProjectID      = balance.ForecastHistory.ProjectID;
                            forecast.ProjectTaskID  = balance.ForecastHistory.ProjectTaskID;
                            forecast.AccountGroupID = balance.ForecastHistory.AccountGroupID;
                            forecast.InventoryID    = balance.ForecastHistory.InventoryID;
                            forecast.CostCodeID     = balance.ForecastHistory.CostCodeID;
                            forecast.PeriodID       = balance.ForecastHistory.PeriodID;

                            forecast = ForecastHistory.Insert(forecast);

                            forecast.ActualQty        += balance.ForecastHistory.ActualQty.GetValueOrDefault();
                            forecast.CuryActualAmount += balance.ForecastHistory.CuryActualAmount.GetValueOrDefault();
                            forecast.ActualAmount     += balance.ForecastHistory.ActualAmount.GetValueOrDefault();
                        }

                        if (balance.TaskTotal != null)
                        {
                            PMTaskTotal ta = new PMTaskTotal();
                            ta.ProjectID = balance.TaskTotal.ProjectID;
                            ta.TaskID    = balance.TaskTotal.TaskID;

                            ta                = ProjectTaskTotals.Insert(ta);
                            ta.CuryAsset     += balance.TaskTotal.CuryAsset.GetValueOrDefault();
                            ta.Asset         += balance.TaskTotal.Asset.GetValueOrDefault();
                            ta.CuryLiability += balance.TaskTotal.CuryLiability.GetValueOrDefault();
                            ta.Liability     += balance.TaskTotal.Liability.GetValueOrDefault();
                            ta.CuryIncome    += balance.TaskTotal.CuryIncome.GetValueOrDefault();
                            ta.Income        += balance.TaskTotal.Income.GetValueOrDefault();
                            ta.CuryExpense   += balance.TaskTotal.CuryExpense.GetValueOrDefault();
                            ta.Expense       += balance.TaskTotal.Expense.GetValueOrDefault();
                        }

                        RegisterReleaseProcess.AddToUnbilledSummary(Base, pmt);

                        sourceForAllocation.Add(pmt);
                        if (pmt.Allocated != true && pmt.ExcludedFromAllocation != true && project.AutoAllocate == true)
                        {
                            if (!tasksToAutoAllocate.ContainsKey(string.Format("{0}.{1}", task.ProjectID, task.TaskID)))
                            {
                                tasksToAutoAllocate.Add(string.Format("{0}.{1}", task.ProjectID, task.TaskID), task);
                            }
                        }

                        entryRefGraph.AssignAdditionalFields(tran, pmt);
                    }
                    autoAllocateTasks.AddRange(tasksToAutoAllocate.Values);
                }
            }
            return(autoAllocateTasks);
        }
        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.º 17
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);
            }
        }