protected virtual void _(Events.RowSelected <PMBudget> e)
        {
            if (e.Row != null)
            {
                PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, e.Row.ProjectID);

                PXUIFieldAttribute.SetEnabled <PMCostBudget.curyUnitRate>(e.Cache, null, project?.BudgetFinalized != true);
                PXUIFieldAttribute.SetEnabled <PMCostBudget.qty>(e.Cache, null, project?.BudgetFinalized != true);
                PXUIFieldAttribute.SetEnabled <PMCostBudget.curyAmount>(e.Cache, null, project?.BudgetFinalized != true);

                PXUIFieldAttribute.SetEnabled <PMCostBudget.revisedQty>(e.Cache, null, project?.ChangeOrderWorkflow != true);
                PXUIFieldAttribute.SetEnabled <PMCostBudget.curyRevisedAmount> (e.Cache, null, project?.ChangeOrderWorkflow != true);
            }
        }
        protected virtual void PMTask_RowInserted(PXCache sender, PXRowInsertedEventArgs e)
        {
            PMTask    row     = e.Row as PMTask;
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Current <PMTask.projectID> > > > .Select(this);

            if (row != null && project != null)
            {
                row.CustomerID       = project.CustomerID;
                row.BillingID        = project.BillingID;
                row.AllocationID     = project.AllocationID;
                row.DefaultAccountID = project.DefaultAccountID;
                row.DefaultSubID     = project.DefaultSubID;
            }
        }
        public override List <PMTask> SelectBillableTasks(PMProject project)
        {
            List <PMTask>         tasks       = new List <PMTask>();
            PXSelectBase <PMTask> selectTasks = new PXSelect <PMTask,
                                                              Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                                     And <PMTask.billingID, IsNotNull> > >(this);


            foreach (PMTask task in selectTasks.Select(project.ContractID))
            {
                tasks.Add(task);
            }

            return(tasks);
        }
        protected virtual void PMProject_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            PMProject project = e.Row as PMProject;

            PX.SM.RelationGroup group = Group.Current;
            if (project != null && project.GroupMask != null && group != null && group.GroupMask != null && sender.GetStatus(project) == PXEntryStatus.Notchanged)
            {
                for (int i = 0; i < project.GroupMask.Length && i < group.GroupMask.Length; i++)
                {
                    if (group.GroupMask[i] != 0x00 && (project.GroupMask[i] & group.GroupMask[i]) == group.GroupMask[i])
                    {
                        project.Included = true;
                    }
                }
            }
        }
Exemplo n.º 5
0
        protected virtual void PMTask_CustomerID_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
        {
            PMTask row = e.Row as PMTask;

            if (row == null)
            {
                return;
            }

            PMProject prj = PXSelect <PMProject, Where <PMProject.contractID, Equal <Current <PMTask.projectID> > > > .SelectSingleBound(this, new object[] { row });

            if (prj != null && prj.NonProject == true)
            {
                e.Cancel = true;
            }
        }
Exemplo n.º 6
0
        protected virtual void PMTask_IsActive_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
        {
            PMTask row = e.Row as PMTask;

            if (row != null && e.NewValue != null && ((bool)e.NewValue) == true)
            {
                PMProject project = Project.Select();
                if (project != null)
                {
                    if (project.IsActive == false)
                    {
                        sender.RaiseExceptionHandling <PMTask.status>(e.Row, e.NewValue, new PXSetPropertyException(Warnings.ProjectIsNotActive, PXErrorLevel.Warning));
                    }
                }
            }
        }
        protected virtual void _(Events.FieldDefaulting <PMBudget, PMBudget.costCodeID> e)
        {
            if (e.Row == null)
            {
                return;
            }

            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, e.Row.ProjectID);

            if (project != null)
            {
                if (project.BudgetLevel != BudgetLevels.CostCode)
                {
                    e.NewValue = CostCodeAttribute.GetDefaultCostCode();
                }
            }
        }
Exemplo n.º 8
0
        protected virtual void PMTask_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
        {
            PMTask row = e.Row as PMTask;

            if (row == null)
            {
                return;
            }

            PXUIFieldAttribute.SetEnabled <PMTask.visibleInGL>(sender, row, Setup.Current.VisibleInGL == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInAP>(sender, row, Setup.Current.VisibleInAP == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInAR>(sender, row, Setup.Current.VisibleInAR == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInSO>(sender, row, Setup.Current.VisibleInSO == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInPO>(sender, row, Setup.Current.VisibleInPO == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInTA>(sender, row, Setup.Current.VisibleInTA == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInEA>(sender, row, Setup.Current.VisibleInEA == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInIN>(sender, row, Setup.Current.VisibleInIN == true);
            PXUIFieldAttribute.SetEnabled <PMTask.visibleInCA>(sender, row, Setup.Current.VisibleInCA == true);

            PMProject project = Project.Select();

            if (project == null)
            {
                return;
            }

            string status          = GetStatusFromFlags(row);
            bool   projectEditable = !(project.Status == ProjectStatus.Completed || project.Status == ProjectStatus.Cancelled);

            PXUIFieldAttribute.SetEnabled <PMTask.status>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.description>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.rateTableID>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.allocationID>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.billingID>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.billingOption>(sender, row, status == ProjectTaskStatus.Planned);
            PXUIFieldAttribute.SetEnabled <PMTask.completedPercent>(sender, row, row.CompletedPctMethod == PMCompletedPctMethod.Manual && status != ProjectTaskStatus.Planned && projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.taxCategoryID>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.approverID>(sender, row, projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.startDate>(sender, row, (status == ProjectTaskStatus.Planned || status == ProjectTaskStatus.Active) && projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.endDate>(sender, row, status != ProjectTaskStatus.Completed && projectEditable);
            PXUIFieldAttribute.SetEnabled <PMTask.plannedStartDate>(sender, row, status == ProjectTaskStatus.Planned);
            PXUIFieldAttribute.SetEnabled <PMTask.plannedEndDate>(sender, row, status == ProjectTaskStatus.Planned);
            PXUIFieldAttribute.SetEnabled <PMTask.isDefault>(sender, row, projectEditable);
        }
Exemplo n.º 9
0
        protected virtual ProjectsList CreateListItem(PXResult item)
        {
            PMProject project = PXResult.Unwrap <PMProject>(item);
            ContractBillingSchedule schedule = PXResult.Unwrap <ContractBillingSchedule>(item);
            Customer customer = PXResult.Unwrap <Customer>(item);

            ProjectsList result = new ProjectsList();

            result.ProjectID   = project.ContractID;
            result.ProjectCD   = project.ContractCD;
            result.Description = project.Description;
            result.CustomerID  = project.CustomerID;
            result.LastDate    = schedule.LastDate;

            DateTime?fromDate = null;

            if (schedule.NextDate != null)
            {
                switch (schedule.Type)
                {
                case BillingType.Annual:
                    fromDate = schedule.NextDate.Value.AddYears(-1);
                    break;

                case BillingType.Monthly:
                    fromDate = schedule.NextDate.Value.AddMonths(-1);
                    break;

                case BillingType.Weekly:
                    fromDate = schedule.NextDate.Value.AddDays(-7);
                    break;

                case BillingType.Quarterly:
                    fromDate = schedule.NextDate.Value.AddMonths(-3);
                    break;
                }
            }

            result.FromDate = fromDate;
            result.NextDate = schedule.NextDate;

            return(result);
        }
Exemplo n.º 10
0
        public virtual void PMSetup_RowInserted(PXCache sender, PXRowInsertedEventArgs e)
        {
            PMSetup row = (PMSetup)e.Row;

            if (row == null)
            {
                return;
            }

            PMProject rec = DefaultProject.SelectWindowed(0, 1);

            if (rec == null)
            {
                InsertDefaultProject(row);
            }
            else
            {
                rec.ContractCD             = row.NonProjectCode;
                rec.IsActive               = true;
                rec.Status                 = ProjectStatus.Active;
                rec.VisibleInAP            = true;
                rec.VisibleInAR            = true;
                rec.VisibleInCA            = true;
                rec.VisibleInCR            = true;
                rec.VisibleInEA            = true;
                rec.VisibleInGL            = true;
                rec.VisibleInIN            = true;
                rec.VisibleInPO            = true;
                rec.VisibleInSO            = true;
                rec.VisibleInTA            = true;
                rec.RestrictToEmployeeList = false;
                rec.RestrictToResourceList = false;

                if (DefaultProject.Cache.GetStatus(rec) == PXEntryStatus.Notchanged)
                {
                    DefaultProject.Cache.SetStatus(rec, PXEntryStatus.Updated);
                }
            }

            EnsureDefaultCostCode(row);
            EnsureEmptyItem(row);
        }
        public virtual void RebuildAllocationTotals(PMProject project)
        {
            PXSelectBase <PMTran> select2 = new PXSelect <PMTran,
                                                          Where <PMTran.origProjectID, Equal <Required <PMTran.origProjectID> >,
                                                                 And <PMTran.origTaskID, IsNotNull,
                                                                      And <PMTran.origAccountGroupID, IsNotNull> > > >(this);

            foreach (PMTran tran in select2.Select(project.ContractID))
            {
                PMTaskAllocTotalAccum tat = new PMTaskAllocTotalAccum();
                tat.ProjectID      = tran.OrigProjectID;
                tat.TaskID         = tran.OrigTaskID;
                tat.AccountGroupID = tran.OrigAccountGroupID;
                tat.InventoryID    = tran.InventoryID.GetValueOrDefault(PMInventorySelectorAttribute.EmptyInventoryID);

                tat           = AllocationTotals.Insert(tat);
                tat.Amount   += tran.Amount.GetValueOrDefault();
                tat.Quantity += tran.Qty.GetValueOrDefault();
            }
        }
Exemplo n.º 12
0
        public virtual void PMSetup_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
        {
            PMProject rec = DefaultProject.SelectWindowed(0, 1);
            PMSetup   row = (PMSetup)e.Row;

            if (row == null)
            {
                return;
            }

            if (rec == null)
            {
                InsertDefaultProject(row);
            }
            else if (!sender.ObjectsEqual <PMSetup.nonProjectCode>(e.Row, e.OldRow))
            {
                rec.ContractCD = row.NonProjectCode;

                if (DefaultProject.Cache.GetStatus(rec) == PXEntryStatus.Notchanged)
                {
                    DefaultProject.Cache.SetStatus(rec, PXEntryStatus.Updated);
                }
            }

            InventoryItem item = EmptyItem.SelectWindowed(0, 1);

            if (item == null)
            {
                InsertEmptyItem(row);
            }
            else if (!sender.ObjectsEqual <PMSetup.emptyItemCode>(e.Row, e.OldRow))
            {
                item.InventoryCD = row.EmptyItemCode;

                if (EmptyItem.Cache.GetStatus(rec) == PXEntryStatus.Notchanged)
                {
                    EmptyItem.Cache.SetStatus(rec, PXEntryStatus.Updated);
                }
            }
        }
        public virtual PMTran ExpenseTransactionFromBudget(PMBudget budget, PMProject project, PMTask task, PMAccountGroup accountGroup, InventoryItem item, PMCostCode costcode)
        {
            PMTran tran = new PMTran();

            tran.AccountGroupID = budget.AccountGroupID;
            tran.ProjectID      = budget.ProjectID;
            tran.TaskID         = budget.ProjectTaskID;
            tran.InventoryID    = budget.InventoryID;
            tran.AccountID      = item.InventoryID != null ? item.COGSAcctID : accountGroup.AccountID;
            tran.SubID          = item.InventoryID != null ? item.COGSSubID : accountGroup.AccountID;
            tran.Amount         = budget.RevisedAmount;
            tran.Qty            = budget.RevisedQty;
            tran.UOM            = budget.UOM;
            tran.BAccountID     = task.CustomerID;
            tran.LocationID     = task.LocationID;
            tran.Billable       = true;
            tran.UseBillableQty = true;
            tran.BillableQty    = budget.RevisedQty;
            tran.Released       = true;

            return(tran);
        }
Exemplo n.º 14
0
        public ProjectTaskEntry()
        {
            if (Setup.Current == null)
            {
                throw new PXException(Messages.SetupNotConfigured);
            }

            Activities.GetNewEmailAddress =
                () =>
            {
                PMProject current = Project.Select();
                if (current != null)
                {
                    Contact customerContact = PXSelectJoin <Contact, InnerJoin <BAccount, On <BAccount.defContactID, Equal <Contact.contactID> > >, Where <BAccount.bAccountID, Equal <Required <BAccount.bAccountID> > > > .Select(this, current.CustomerID);

                    if (customerContact != null && !string.IsNullOrWhiteSpace(customerContact.EMail))
                    {
                        return(PXDBEmailAttribute.FormatAddressesWithSingleDisplayName(customerContact.EMail, customerContact.DisplayName));
                    }
                }
                return(String.Empty);
            };
        }
Exemplo n.º 15
0
        public virtual void AddToInvoiced(ARTran line, int?revenueAccountGroup, int mult = 1)
        {
            if (line.TaskID == null)
            {
                return;
            }

            if (revenueAccountGroup == null)
            {
                return;
            }

            if (CostCodeAttribute.UseCostCode() && line.CostCodeID == null)
            {
                return;
            }

            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(Base, line.ProjectID);

            if (project != null && project.NonProject != true)
            {
                PMBudgetAccum invoiced = GetTargetBudget(revenueAccountGroup, line);
                invoiced = Base.Budget.Insert(invoiced);


                if (project.CuryID == project.BillingCuryID)
                {
                    invoiced.CuryInvoicedAmount += mult * (line.CuryTranAmt.GetValueOrDefault() + line.CuryRetainageAmt.GetValueOrDefault());
                    invoiced.InvoicedAmount     += mult * (line.TranAmt.GetValueOrDefault() + line.RetainageAmt.GetValueOrDefault());
                }
                else
                {
                    invoiced.CuryInvoicedAmount += mult * (line.TranAmt.GetValueOrDefault() + line.RetainageAmt.GetValueOrDefault());
                    invoiced.InvoicedAmount     += mult * (line.TranAmt.GetValueOrDefault() + line.RetainageAmt.GetValueOrDefault());
                }
            }
        }
        public virtual void PMSetup_RowInserted(PXCache sender, PXRowInsertedEventArgs e)
        {
            PMSetup row = (PMSetup)e.Row;

            if (row == null)
            {
                return;
            }

            PMProject rec = DefaultProject.SelectWindowed(0, 1);

            if (rec == null)
            {
                InsertDefaultProject(row);
            }
            else
            {
                rec.ContractCD = row.NonProjectCode;
                if (DefaultProject.Cache.GetStatus(rec) == PXEntryStatus.Notchanged)
                {
                    DefaultProject.Cache.SetStatus(rec, PXEntryStatus.Updated);
                }
            }
        }
        public virtual void ProcessPOCommitments(PMProject project)
        {
            foreach (PXResult <POLine, POOrder> res in polines.Select(project.ContractID))
            {
                POLine  poline = (POLine)res;
                POOrder order  = (POOrder)res;
                PXParentAttribute.SetParent(polines.Cache, poline, typeof(POOrder), order);

                PMCommitmentAttribute.Sync(polines.Cache, poline);
            }

            foreach (APTran tran in aptran.Select(project.ContractID))
            {
                POLine poline = new POLine();
                poline.OrderType = tran.POOrderType;
                poline.OrderNbr  = tran.PONbr;
                poline.LineNbr   = tran.POLineNbr;

                poline = polines.Locate(poline);

                if (poline != null && poline.CommitmentID != null)
                {
                    decimal sign = (tran.DrCr == DrCr.Debit) ? Decimal.One : Decimal.MinusOne;

                    PMCommitment container = new PMCommitment();
                    container.CommitmentID   = poline.CommitmentID;
                    container.UOM            = tran.UOM;
                    container.InventoryID    = tran.InventoryID;
                    container.CostCodeID     = tran.CostCodeID.GetValueOrDefault(CostCodeAttribute.GetDefaultCostCode());
                    container.InvoicedAmount = sign * tran.LineAmt.GetValueOrDefault();
                    container.InvoicedQty    = sign * tran.Qty.GetValueOrDefault();

                    PMCommitmentAttribute.AddToInvoiced(polines.Cache, container);
                }
            }
        }
Exemplo n.º 18
0
        protected virtual void _(Events.RowSelected <PMTimeActivity> e)
        {
            if (e.Row == null)
            {
                return;
            }

            if (e.Row.Released == true)
            {
                PXUIFieldAttribute.SetEnabled(e.Cache, e.Row, false);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.noteID>(e.Cache, e.Row, true);
            }
            else if (e.Row.ApprovalStatus == CR.ActivityStatusListAttribute.Open)
            {
                PXUIFieldAttribute.SetEnabled(e.Cache, e.Row, true);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.timeBillable>(e.Cache, e.Row);
                PMProject project = (PMProject)PXSelectorAttribute.Select <PMTimeActivity.projectID>(e.Cache, e.Row);

                if (project != null)
                {
                    PXUIFieldAttribute.SetEnabled <PMTimeActivity.projectTaskID>(e.Cache, e.Row, project.BaseType == PMProject.ProjectBaseType.Project);
                }
                PXDBDateAndTimeAttribute.SetTimeEnabled <PMTimeActivity.date>(e.Cache, e.Row, true);
                PXDBDateAndTimeAttribute.SetDateEnabled <PMTimeActivity.date>(e.Cache, e.Row, true);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.approverID>(e.Cache, e.Row, false);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.timeCardCD>(e.Cache, e.Row, false);
            }
            else
            {
                PXUIFieldAttribute.SetEnabled(e.Cache, e.Row, false);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.noteID>(e.Cache, e.Row, true);
                PXUIFieldAttribute.SetEnabled <PMTimeActivity.approvalStatus>(e.Cache, e.Row, true);
            }

            PXUIFieldAttribute.SetEnabled <PMTimeActivity.employeeRate>(e.Cache, e.Row, false);
        }
        public virtual void ProcessSOCommitments(PMProject project)
        {
            foreach (PXResult <SOLine, SOOrder> res in solines.Select(project.ContractID))
            {
                SOLine  soline = (SOLine)res;
                SOOrder order  = (SOOrder)res;
                PXParentAttribute.SetParent(solines.Cache, soline, typeof(SOOrder), order);

                PMCommitmentAttribute.Sync(solines.Cache, soline);
            }

            foreach (ARTran tran in artran.Select(project.ContractID))
            {
                SOLine soline = new SOLine();
                soline.OrderType = tran.SOOrderType;
                soline.OrderNbr  = tran.SOOrderNbr;
                soline.LineNbr   = tran.SOOrderLineNbr;

                soline = solines.Locate(soline);

                if (soline != null && soline.CommitmentID != null)
                {
                    decimal sign = (tran.DrCr == DrCr.Credit) ? Decimal.One : Decimal.MinusOne;

                    PMCommitment container = new PMCommitment();
                    container.CommitmentID   = soline.CommitmentID;
                    container.UOM            = tran.UOM;
                    container.InventoryID    = tran.InventoryID;
                    container.CostCodeID     = tran.CostCodeID.GetValueOrDefault(CostCodeAttribute.GetDefaultCostCode());
                    container.InvoicedAmount = sign * tran.TranAmt.GetValueOrDefault();
                    container.InvoicedQty    = sign * tran.Qty.GetValueOrDefault();

                    PMCommitmentAttribute.AddToInvoiced(solines.Cache, container);
                }
            }
        }
 private static void Validate(ProjectBalanceValidationProcess graph, PMProject item)
 {
     graph.Clear();
     graph.RunProjectBalanceVerification(item);
     graph.Actions.PressSave();
 }
        public virtual void RecalculateDraftInvoicesAmount(PMProject project, ProjectBalance pb)
        {
            var selectProforma = new PXSelectJoinGroupBy <PMProformaLine,
                                                          InnerJoin <Account, On <PMProformaLine.accountID, Equal <Account.accountID> > >,
                                                          Where <PMProformaLine.projectID, Equal <Required <PMProformaLine.projectID> >,
                                                                 And <PMProformaLine.released, Equal <False> > >,
                                                          Aggregate <GroupBy <PMProformaLine.projectID,
                                                                              GroupBy <PMProformaLine.taskID,
                                                                                       GroupBy <PMProformaLine.accountID,
                                                                                                GroupBy <PMProformaLine.inventoryID,
                                                                                                         GroupBy <PMProformaLine.costCodeID,
                                                                                                                  Sum <PMProformaLine.lineTotal> > > > > > > >(this);

            var selectInvoice = new PXSelectJoinGroupBy <ARTran,
                                                         InnerJoin <Account, On <ARTran.accountID, Equal <Account.accountID> > >,
                                                         Where <ARTran.projectID, Equal <Required <ARTran.projectID> >,
                                                                And <ARTran.released, Equal <False> > >,
                                                         Aggregate <GroupBy <ARTran.tranType,
                                                                             GroupBy <ARTran.projectID,
                                                                                      GroupBy <ARTran.taskID,
                                                                                               GroupBy <ARTran.accountID,
                                                                                                        GroupBy <ARTran.inventoryID,
                                                                                                                 GroupBy <ARTran.costCodeID,
                                                                                                                          Sum <ARTran.tranAmt> > > > > > > > >(this);


            var selectRevenueBudget = new PXSelect <PMRevenueBudget,
                                                    Where <PMRevenueBudget.projectID, Equal <Required <PMRevenueBudget.projectID> >,
                                                           And <PMRevenueBudget.type, Equal <GL.AccountType.income> > > >(this);
            var revenueBudget = selectRevenueBudget.Select(project.ContractID);

            foreach (PXResult <PMProformaLine, Account> res in selectProforma.Select(project.ContractID))
            {
                PMProformaLine line    = (PMProformaLine)res;
                Account        account = (Account)res;

                int?inventoryID = PMInventorySelectorAttribute.EmptyInventoryID;

                foreach (PMRevenueBudget rev in revenueBudget)
                {
                    foreach (PMRevenueBudget budget in revenueBudget)
                    {
                        if (budget.TaskID == line.TaskID && line.InventoryID == budget.InventoryID)
                        {
                            inventoryID = line.InventoryID;
                        }
                    }
                }

                PMBudgetAccum invoiced = new PMBudgetAccum();
                invoiced.Type           = GL.AccountType.Income;
                invoiced.ProjectID      = line.ProjectID;
                invoiced.ProjectTaskID  = line.TaskID;
                invoiced.AccountGroupID = account.AccountGroupID;
                invoiced.InventoryID    = inventoryID;
                invoiced.CostCodeID     = line.CostCodeID.GetValueOrDefault(CostCodeAttribute.GetDefaultCostCode());

                invoiced = Budget.Insert(invoiced);
                invoiced.InvoicedAmount += line.LineTotal.GetValueOrDefault();

                if (line.IsPrepayment == true)
                {
                    invoiced.PrepaymentInvoiced += line.LineTotal.GetValueOrDefault();
                }
            }

            foreach (PXResult <ARTran, Account> res in selectInvoice.Select(project.ContractID))
            {
                ARTran  line    = (ARTran)res;
                Account account = (Account)res;

                int?inventoryID = PMInventorySelectorAttribute.EmptyInventoryID;

                foreach (PMRevenueBudget rev in revenueBudget)
                {
                    foreach (PMRevenueBudget budget in revenueBudget)
                    {
                        if (budget.TaskID == line.TaskID && line.InventoryID == budget.InventoryID)
                        {
                            inventoryID = line.InventoryID;
                        }
                    }
                }

                PMBudgetAccum invoiced = new PMBudgetAccum();
                invoiced.Type           = GL.AccountType.Income;
                invoiced.ProjectID      = line.ProjectID;
                invoiced.ProjectTaskID  = line.TaskID;
                invoiced.AccountGroupID = account.AccountGroupID;
                invoiced.InventoryID    = inventoryID;
                invoiced.CostCodeID     = line.CostCodeID.GetValueOrDefault(CostCodeAttribute.GetDefaultCostCode());

                invoiced = Budget.Insert(invoiced);
                invoiced.InvoicedAmount += line.TranAmt.GetValueOrDefault() * ARDocType.SignAmount(line.TranType);
            }
        }
Exemplo n.º 22
0
        public virtual bool IsInvalid(PMProject nonProject)
        {
            if (nonProject.IsActive == false)
            {
                return(true);
            }
            if (nonProject.Status != ProjectStatus.Active)
            {
                return(true);
            }
            if (nonProject.RestrictToEmployeeList == true)
            {
                return(true);
            }
            if (nonProject.RestrictToResourceList == true)
            {
                return(true);
            }
            if (nonProject.VisibleInAP == false)
            {
                return(true);
            }
            if (nonProject.VisibleInAR == false)
            {
                return(true);
            }
            if (nonProject.VisibleInCA == false)
            {
                return(true);
            }
            if (nonProject.VisibleInCR == false)
            {
                return(true);
            }
            if (nonProject.VisibleInEA == false)
            {
                return(true);
            }
            if (nonProject.VisibleInGL == false)
            {
                return(true);
            }
            if (nonProject.VisibleInIN == false)
            {
                return(true);
            }
            if (nonProject.VisibleInPO == false)
            {
                return(true);
            }
            if (nonProject.VisibleInSO == false)
            {
                return(true);
            }
            if (nonProject.VisibleInTA == false)
            {
                return(true);
            }
            if (nonProject.CustomerID != null)
            {
                return(true);
            }

            return(false);
        }
        protected virtual IEnumerable items()
        {
            BillingFilter filter = Filter.Current;

            if (filter == null)
            {
                yield break;
            }
            bool found = false;

            foreach (ProjectsList item in Items.Cache.Inserted)
            {
                found = true;
                yield return(item);
            }
            if (found)
            {
                yield break;
            }

            PXSelectBase <PMProject> selectUnbilled = new PXSelectJoinGroupBy <PMProject,
                                                                               InnerJoin <PMUnbilledDailySummary, On <PMUnbilledDailySummary.projectID, Equal <PMProject.contractID> >,
                                                                                          InnerJoin <ContractBillingSchedule, On <PMProject.contractID, Equal <ContractBillingSchedule.contractID> >,
                                                                                                     InnerJoin <Customer, On <PMProject.customerID, Equal <Customer.bAccountID> >,
                                                                                                                InnerJoin <PMTask, On <PMTask.projectID, Equal <PMUnbilledDailySummary.projectID>,
                                                                                                                                       And <PMTask.isActive, Equal <True>,
                                                                                                                                            And <PMTask.taskID, Equal <PMUnbilledDailySummary.taskID>,
                                                                                                                                                 And <Where <PMTask.billingOption, Equal <PMBillingOption.onBilling>,
                                                                                                                                                             Or2 <Where <PMTask.billingOption, Equal <PMBillingOption.onTaskCompletion>, And <PMTask.isCompleted, Equal <True> > >,
                                                                                                                                                                  Or <Where <PMTask.billingOption, Equal <PMBillingOption.onProjectCompetion>, And <PMProject.isCompleted, Equal <True> > > > > > > > > >,
                                                                                                                           InnerJoin <PMBillingRule, On <PMBillingRule.billingID, Equal <PMTask.billingID>,
                                                                                                                                                         And <PMBillingRule.accountGroupID, Equal <PMUnbilledDailySummary.accountGroupID> > > > > > > >,
                                                                               Where2 <Where <ContractBillingSchedule.nextDate, LessEqual <Current <BillingFilter.invoiceDate> >,
                                                                                              Or <ContractBillingSchedule.type, Equal <BillingType.BillingOnDemand> > >,
                                                                                       And2 <Where <PMBillingRule.includeNonBillable, Equal <False>, And <PMUnbilledDailySummary.billable, Greater <int0>,
                                                                                                                                                          Or <Where <PMBillingRule.includeNonBillable, Equal <True>, And <Where <PMUnbilledDailySummary.nonBillable, Greater <int0>, Or <PMUnbilledDailySummary.billable, Greater <int0> > > > > > > >,
                                                                                             And2 <Where <PMUnbilledDailySummary.date, LessEqual <Current <BillingFilter.invoiceDate> > >, And <Match <Current <AccessInfo.userName> > > > > >,
                                                                               Aggregate <GroupBy <PMProject.contractID> > >(this);

            if (Setup.Current.CutoffDate == PMCutOffDate.Excluded)
            {
                selectUnbilled = new PXSelectJoinGroupBy <PMProject,
                                                          InnerJoin <PMUnbilledDailySummary, On <PMUnbilledDailySummary.projectID, Equal <PMProject.contractID> >,
                                                                     InnerJoin <ContractBillingSchedule, On <PMProject.contractID, Equal <ContractBillingSchedule.contractID> >,
                                                                                InnerJoin <Customer, On <PMProject.customerID, Equal <Customer.bAccountID> >,
                                                                                           InnerJoin <PMTask, On <PMTask.projectID, Equal <PMUnbilledDailySummary.projectID>,
                                                                                                                  And <PMTask.isActive, Equal <True>,
                                                                                                                       And <PMTask.taskID, Equal <PMUnbilledDailySummary.taskID>,
                                                                                                                            And <Where <PMTask.billingOption, Equal <PMBillingOption.onBilling>,
                                                                                                                                        Or2 <Where <PMTask.billingOption, Equal <PMBillingOption.onTaskCompletion>, And <PMTask.isCompleted, Equal <True> > >,
                                                                                                                                             Or <Where <PMTask.billingOption, Equal <PMBillingOption.onProjectCompetion>, And <PMProject.isCompleted, Equal <True> > > > > > > > > >,
                                                                                                      InnerJoin <PMBillingRule, On <PMBillingRule.billingID, Equal <PMTask.billingID>,
                                                                                                                                    And <PMBillingRule.accountGroupID, Equal <PMUnbilledDailySummary.accountGroupID> > > > > > > >,
                                                          Where2 <Where <ContractBillingSchedule.nextDate, LessEqual <Current <BillingFilter.invoiceDate> >,
                                                                         Or <ContractBillingSchedule.type, Equal <BillingType.BillingOnDemand> > >,
                                                                  And2 <Where <PMBillingRule.includeNonBillable, Equal <False>, And <PMUnbilledDailySummary.billable, Greater <int0>,
                                                                                                                                     Or <Where <PMBillingRule.includeNonBillable, Equal <True>, And <Where <PMUnbilledDailySummary.nonBillable, Greater <int0>, Or <PMUnbilledDailySummary.billable, Greater <int0> > > > > > > >,
                                                                        And2 <Where <PMUnbilledDailySummary.date, Less <Current <BillingFilter.invoiceDate> > >, And <Match <Current <AccessInfo.userName> > > > > >,
                                                          Aggregate <GroupBy <PMProject.contractID> > >(this);
            }


            PXSelectBase <PMProject> selectRecurring = new PXSelectJoinGroupBy <PMProject,
                                                                                InnerJoin <ContractBillingSchedule, On <PMProject.contractID, Equal <ContractBillingSchedule.contractID> >,
                                                                                           InnerJoin <Customer, On <PMProject.customerID, Equal <Customer.bAccountID> >,
                                                                                                      InnerJoin <PMTask, On <PMTask.projectID, Equal <PMProject.contractID> >,
                                                                                                                 InnerJoin <PMBillingRule, On <PMBillingRule.billingID, Equal <PMTask.billingID> >,
                                                                                                                            InnerJoin <PMRecurringItem, On <PMTask.projectID, Equal <PMRecurringItem.projectID>,
                                                                                                                                                            And <PMTask.taskID, Equal <PMRecurringItem.taskID>,
                                                                                                                                                                 And <PMTask.isCompleted, Equal <False> > > > > > > > >,
                                                                                Where2 <Where <ContractBillingSchedule.nextDate, LessEqual <Current <BillingFilter.invoiceDate> >,
                                                                                               Or <ContractBillingSchedule.type, Equal <BillingType.BillingOnDemand> > >,
                                                                                        And <Match <Current <AccessInfo.userName> > > >,
                                                                                Aggregate <GroupBy <PMProject.contractID> > >(this);

            PXSelectBase <PMProject> selectProgressive = new PXSelectJoinGroupBy <PMProject,
                                                                                  InnerJoin <ContractBillingSchedule, On <PMProject.contractID, Equal <ContractBillingSchedule.contractID> >,
                                                                                             InnerJoin <Customer, On <PMProject.customerID, Equal <Customer.bAccountID> >,
                                                                                                        InnerJoin <PMTask, On <PMTask.projectID, Equal <PMProject.contractID> >,
                                                                                                                   InnerJoin <PMBillingRule, On <PMBillingRule.billingID, Equal <PMTask.billingID> >,
                                                                                                                              InnerJoin <PMBudget, On <PMTask.projectID, Equal <PMBudget.projectID>,
                                                                                                                                                       And <PMTask.taskID, Equal <PMBudget.projectTaskID>,
                                                                                                                                                            And <PMBudget.type, Equal <GL.AccountType.income>,
                                                                                                                                                                 And <PMBudget.amountToInvoice, NotEqual <decimal0> > > > > > > > > >,
                                                                                  Where <Match <Current <AccessInfo.userName> > >,
                                                                                  Aggregate <GroupBy <PMProject.contractID> > >(this);


            if (filter.StatementCycleId != null)
            {
                selectUnbilled.WhereAnd <Where <Customer.statementCycleId, Equal <Current <BillingFilter.statementCycleId> > > >();
                selectRecurring.WhereAnd <Where <Customer.statementCycleId, Equal <Current <BillingFilter.statementCycleId> > > >();
                selectProgressive.WhereAnd <Where <Customer.statementCycleId, Equal <Current <BillingFilter.statementCycleId> > > >();
            }
            if (filter.CustomerClassID != null)
            {
                selectUnbilled.WhereAnd <Where <Customer.customerClassID, Equal <Current <BillingFilter.customerClassID> > > >();
                selectRecurring.WhereAnd <Where <Customer.customerClassID, Equal <Current <BillingFilter.customerClassID> > > >();
                selectProgressive.WhereAnd <Where <Customer.customerClassID, Equal <Current <BillingFilter.customerClassID> > > >();
            }
            if (filter.CustomerID != null)
            {
                selectUnbilled.WhereAnd <Where <Customer.bAccountID, Equal <Current <BillingFilter.customerID> > > >();
                selectRecurring.WhereAnd <Where <Customer.bAccountID, Equal <Current <BillingFilter.customerID> > > >();
                selectProgressive.WhereAnd <Where <Customer.bAccountID, Equal <Current <BillingFilter.customerID> > > >();
            }
            if (filter.TemplateID != null)
            {
                selectUnbilled.WhereAnd <Where <PMProject.templateID, Equal <Current <BillingFilter.templateID> > > >();
                selectRecurring.WhereAnd <Where <PMProject.templateID, Equal <Current <BillingFilter.templateID> > > >();
                selectProgressive.WhereAnd <Where <PMProject.templateID, Equal <Current <BillingFilter.templateID> > > >();
            }

            foreach (PXResult item in selectUnbilled.Select().Union(selectRecurring.Select()).Union(selectProgressive.Select()))
            {
                PMProject project = PXResult.Unwrap <PMProject>(item);
                ContractBillingSchedule schedule = PXResult.Unwrap <ContractBillingSchedule>(item);
                Customer customer = PXResult.Unwrap <Customer>(item);

                ProjectsList result = new ProjectsList();
                result.ProjectID    = project.ContractID;
                result.ProjectCD    = project.ContractCD;
                result.Description  = project.Description;
                result.CustomerID   = project.CustomerID;
                result.CustomerName = customer.AcctName;
                result.LastDate     = schedule.LastDate;

                DateTime?fromDate = null;

                if (schedule.NextDate != null)
                {
                    switch (schedule.Type)
                    {
                    case BillingType.Annual:
                        fromDate = schedule.NextDate.Value.AddYears(-1);
                        break;

                    case BillingType.Monthly:
                        fromDate = schedule.NextDate.Value.AddMonths(-1);
                        break;

                    case BillingType.Weekly:
                        fromDate = schedule.NextDate.Value.AddDays(-7);
                        break;

                    case BillingType.Quarterly:
                        fromDate = schedule.NextDate.Value.AddMonths(-3);
                        break;
                    }
                }

                result.FromDate = fromDate;
                result.NextDate = schedule.NextDate;

                if (Items.Locate(result) == null)
                {
                    yield return(Items.Insert(result));
                }
            }

            Items.Cache.IsDirty = false;
        }
        public virtual void RunProjectBalanceVerification(PMProject project)
        {
            PXDatabase.Delete <PMTaskTotal>(new PXDataFieldRestrict(typeof(PMTaskTotal.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            PXDatabase.Delete <PMTaskAllocTotal>(new PXDataFieldRestrict(typeof(PMTaskAllocTotal.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            PXDatabase.Delete <PMHistory>(new PXDataFieldRestrict(typeof(PMHistory.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));

            foreach (PMProjectStatusEx status in PXSelect <PMProjectStatusEx, Where <PMProjectStatusEx.projectID, Equal <Required <PMProjectStatusEx.projectID> > > > .Select(this, project.ContractID))
            {
                PXDatabase.Update <PMProjectStatus>(new PXDataFieldRestrict(typeof(PMProjectStatus.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ),
                                                    new PXDataFieldAssign(typeof(PMProjectStatus.actualAmount).Name, PXDbType.Decimal, 0m),
                                                    new PXDataFieldAssign(typeof(PMProjectStatus.actualQty).Name, PXDbType.Decimal, 0m));

                PMHistory2Accum hist2 = new PMHistory2Accum();
                hist2.ProjectID      = status.ProjectID;
                hist2.ProjectTaskID  = status.ProjectTaskID;
                hist2.AccountGroupID = status.AccountGroupID;
                hist2.InventoryID    = status.InventoryID ?? PMProjectStatus.EmptyInventoryID;
                hist2.PeriodID       = status.PeriodID;

                hist2 = History2.Insert(hist2);
                hist2.PTDBudgetAmount  += status.Amount;
                hist2.PTDBudgetQty     += status.Qty;
                hist2.BudgetAmount     += status.Amount;
                hist2.BudgetQty        += status.Qty;
                hist2.PTDRevisedAmount += status.RevisedAmount;
                hist2.PTDRevisedQty    += status.RevisedQty;
                hist2.RevisedAmount    += status.RevisedAmount;
                hist2.RevisedQty       += status.RevisedQty;
            }

            PXSelectBase <PMTran> select = new PXSelectJoin <PMTran,
                                                             LeftJoin <Account, On <PMTran.accountID, Equal <Account.accountID> >,
                                                                       InnerJoin <PMProject, On <PMProject.contractID, Equal <PMTran.projectID> >,
                                                                                  LeftJoin <PMTask, On <PMTask.projectID, Equal <PMTran.projectID>, And <PMTask.taskID, Equal <PMTran.taskID> > >,
                                                                                            LeftJoin <OffsetAccount, On <PMTran.offsetAccountID, Equal <OffsetAccount.accountID> >,
                                                                                                      LeftJoin <PMAccountGroup, On <PMAccountGroup.groupID, Equal <Account.accountGroupID> >,
                                                                                                                LeftJoin <OffsetPMAccountGroup, On <OffsetPMAccountGroup.groupID, Equal <OffsetAccount.accountGroupID> > > > > > > >,
                                                             Where <PMTran.projectID, Equal <Required <PMTran.projectID> >,
                                                                    And <PMTran.released, Equal <True> > > >(this);


            foreach (PXResult <PMTran, Account, PMProject, PMTask, OffsetAccount, PMAccountGroup, OffsetPMAccountGroup> res in select.Select(project.ContractID))
            {
                PMTran               tran      = (PMTran)res;
                Account              acc       = (Account)res;
                PMAccountGroup       ag        = (PMAccountGroup)res;
                OffsetAccount        offsetAcc = (OffsetAccount)res;
                OffsetPMAccountGroup offsetAg  = (OffsetPMAccountGroup)res;
                PMTask               task      = (PMTask)res;

                IList <PMHistory> list = RegisterReleaseProcess.UpdateProjectBalance(this, task, tran, acc, ag, offsetAcc, offsetAg);

                #region History Update
                foreach (PMHistory item in list)
                {
                    PMHistoryAccum hist = new PMHistoryAccum();
                    hist.ProjectID      = item.ProjectID;
                    hist.ProjectTaskID  = item.ProjectTaskID;
                    hist.AccountGroupID = item.AccountGroupID;
                    hist.InventoryID    = item.InventoryID;
                    hist.PeriodID       = item.PeriodID;

                    hist = History.Insert(hist);
                    hist.FinPTDAmount  += item.FinPTDAmount.GetValueOrDefault();
                    hist.FinYTDAmount  += item.FinYTDAmount.GetValueOrDefault();
                    hist.FinPTDQty     += item.FinPTDQty.GetValueOrDefault();
                    hist.FinYTDQty     += item.FinYTDQty.GetValueOrDefault();
                    hist.TranPTDAmount += item.TranPTDAmount.GetValueOrDefault();
                    hist.TranYTDAmount += item.TranYTDAmount.GetValueOrDefault();
                    hist.TranPTDQty    += item.TranPTDQty.GetValueOrDefault();
                    hist.TranYTDQty    += item.TranYTDQty.GetValueOrDefault();
                }



                #endregion
            }



            PXSelectBase <PMTran> select2 = new PXSelect <PMTran,
                                                          Where <PMTran.origProjectID, Equal <Required <PMTran.origProjectID> >,
                                                                 And <PMTran.origTaskID, IsNotNull,
                                                                      And <PMTran.origAccountGroupID, IsNotNull> > > >(this);

            foreach (PMTran tran in select2.Select(project.ContractID))
            {
                PMTaskAllocTotalAccum tat = new PMTaskAllocTotalAccum();
                tat.ProjectID      = tran.OrigProjectID;
                tat.TaskID         = tran.OrigTaskID;
                tat.AccountGroupID = tran.OrigAccountGroupID;
                tat.InventoryID    = tran.InventoryID;

                tat           = AllocationTotals.Insert(tat);
                tat.Amount   += tran.Amount;
                tat.Quantity += tran.Qty;
            }

            foreach (PMProjectStatusAccum item in this.Caches[typeof(PMProjectStatusAccum)].Inserted)
            {
                Debug.Print("Task={0} AG={1} Qty={2} Amt={3}", item.ProjectTaskID, item.AccountGroupID, item.ActualQty, item.ActualAmount);
            }
        }
Exemplo n.º 25
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.º 26
0
        protected virtual List <BillingData> BillTask(PMTask task, PMBillingRule rule, DateTime billingDate)
        {
            PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, task.ProjectID);

            Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(this, project.CustomerID);

            List <BillingData>               list         = new List <BillingData>();
            Dictionary <int, decimal>        availableQty = new Dictionary <int, decimal>();
            Dictionary <int, ContractDetail> billingItems = new Dictionary <int, ContractDetail>();

            //recurent Billing:
            PXSelectBase <ContractDetail> selectBilling = new PXSelect <ContractDetail,
                                                                        Where <ContractDetail.contractID, Equal <Required <ContractDetail.contractID> >,
                                                                               And <ContractDetail.taskID, Equal <Required <ContractDetail.taskID> > > > >(this);

            foreach (ContractDetail billing in selectBilling.Select(task.ProjectID, task.TaskID))
            {
                billingItems.Add(billing.InventoryID.Value, billing);

                if (billing.Included > 0)
                {
                    if (billing.ResetUsage == ResetUsageOption.OnBilling)
                    {
                        availableQty.Add(billing.InventoryID.Value, billing.Included.Value);
                    }
                    else
                    {
                        decimal qtyLeft = billing.Included.Value - billing.LastBilledQty ?? 0;

                        if (qtyLeft > 0)
                        {
                            availableQty.Add(billing.InventoryID.Value, qtyLeft);
                        }
                    }
                }

                bool bill = false;
                if (billing.ResetUsage == ResetUsageOption.OnBilling)
                {
                    bill = true;
                }
                else
                {
                    if (billing.LastBilledDate == null)
                    {
                        bill = true;
                    }
                }

                if (bill)
                {
                    ARTran arTran = new ARTran();
                    arTran.InventoryID    = billing.InventoryID;
                    arTran.TranDesc       = billing.Description;
                    arTran.Qty            = billing.Included;
                    arTran.UOM            = billing.UOM;
                    arTran.ExtPrice       = billing.ItemFee;
                    arTran.TranAmt        = arTran.ExtPrice;
                    arTran.ProjectID      = task.ProjectID;
                    arTran.TaskID         = task.TaskID;
                    arTran.Commissionable = false;                     //todo

                    string subCD = null;
                    #region Set Account and Subaccount
                    if (billing.AccountSource != PMAccountSource.None)
                    {
                        if (rule.AccountSource == PMAccountSource.RecurringBillingItem)
                        {
                            if (billing.AccountID != null)
                            {
                                arTran.AccountID = billing.AccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.BillingRuleAccountIsNotConfiguredForBillingRecurent, item.InventoryCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Project)
                        {
                            if (project.DefaultAccountID != null)
                            {
                                arTran.AccountID = project.DefaultAccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.ProjectAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, project.ContractCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Task)
                        {
                            if (task.DefaultAccountID != null)
                            {
                                arTran.AccountID = task.DefaultAccountID;
                            }
                            else
                            {
                                InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                throw new PXException(Messages.TaskAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, project.ContractCD, task.TaskCD);
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.InventoryItem)
                        {
                            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                            if (item != null)
                            {
                                if (item.SalesAcctID != null)
                                {
                                    arTran.AccountID = item.SalesAcctID;
                                }
                                else
                                {
                                    throw new PXException(Messages.InventoryAccountIsNotConfiguredForBillingRecurent, item.InventoryCD);
                                }
                            }
                        }
                        else if (billing.AccountSource == PMAccountSource.Customer && customer != null)
                        {
                            CR.Location customerLoc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(this, customer.BAccountID, customer.DefLocationID);

                            if (customerLoc != null)
                            {
                                if (customerLoc.CSalesAcctID != null)
                                {
                                    arTran.AccountID = customerLoc.CSalesAcctID;
                                }
                                else
                                {
                                    InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                                    throw new PXException(Messages.CustomerAccountIsNotConfiguredForBillingRecurent, item.InventoryCD, customer.AcctCD);
                                }
                            }
                        }

                        if (arTran.AccountID == null && !string.IsNullOrEmpty(billing.SubMask))
                        {
                            InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, billing.InventoryID);

                            throw new PXException(Messages.SubAccountCannotBeComposed, item.InventoryCD);
                        }
                        else if (arTran.AccountID != null && !string.IsNullOrEmpty(billing.SubMask))
                        {
                            subCD = PMRecurentBillSubAccountMaskAttribute.MakeSub <PMBillingRule.subMask>(this, billing.SubMask,
                                                                                                          new object[] { billing.SubID, project.DefaultSubID, task.DefaultSubID },
                                                                                                          new Type[] { typeof(PMBillingRule.subID), typeof(PMProject.defaultSubID), typeof(PMTask.defaultSubID) });
                        }
                    }

                    #endregion

                    list.Add(new BillingData(arTran, rule, null, subCD, null, null));

                    billing.LastBilledDate = billingDate;
                    ContractDetail.Update(billing);
                }
            }



            int            mult = 1;
            PMAccountGroup ag   = PXSelect <PMAccountGroup, Where <PMAccountGroup.groupID, Equal <Required <PMAccountGroup.groupID> > > > .Select(this, rule.AccountGroupID);

            if (ag == null)
            {
                throw new PXException(Messages.AccountGroupInBillingRuleNotFound, rule.BillingID, rule.AccountGroupID);
            }
            if (ag.Type == GL.AccountType.Liability || ag.Type == GL.AccountType.Income)
            {
                mult = -1;
            }

            DateTime cuttofDate = billingDate;            //all transactions  excluding the current day.
            ContractBillingSchedule schedule = PXSelect <ContractBillingSchedule> .Search <ContractBillingSchedule.contractID>(this, task.ProjectID);

            if (schedule != null && schedule.Type == BillingType.OnDemand)
            {
                cuttofDate = billingDate.AddDays(1);                //all transactions including the current day.
            }
            else
            {
                if (IncludeTodaysTransactions)
                {
                    cuttofDate = billingDate.AddDays(1);
                }
            }

            List <PMTran> billingBase = SelectBillingBase(task.ProjectID, task.TaskID, rule.AccountGroupID, cuttofDate,
                                                          rule.IncludeNonBillable == true);

            foreach (PMTran tran in billingBase)
            {
                ARTran arTran = new ARTran();
                arTran.BranchID = tran.BranchID;
                if (tran.InventoryID != PMInventorySelectorAttribute.EmptyInventoryID)
                {
                    arTran.InventoryID = tran.InventoryID;
                }
                arTran.TranDesc = tran.Description;
                arTran.UOM      = tran.UOM;
                arTran.Qty      = tran.BillableQty * mult;
                arTran.ExtPrice = tran.Amount * mult;
                if (arTran.Qty != 0)
                {
                    arTran.UnitPrice = arTran.ExtPrice / arTran.Qty;
                }
                else
                {
                    arTran.UnitPrice = 0;
                }
                arTran.TranAmt        = arTran.ExtPrice;
                arTran.ProjectID      = task.ProjectID;
                arTran.TaskID         = task.TaskID;
                arTran.PMTranID       = tran.TranID;
                arTran.Commissionable = false;                 //todo
                arTran.Date           = tran.Date;

                string subCD = null;
                #region Set Account and Subaccount

                int?employeeSubID = null;

                if (tran.ResourceID != null)
                {
                    EP.EPEmployee emp = PXSelect <EP.EPEmployee, Where <EP.EPEmployee.bAccountID, Equal <Required <EP.EPEmployee.bAccountID> > > > .Select(this, tran.ResourceID);

                    if (emp != null)
                    {
                        employeeSubID = emp.SalesSubID;
                    }
                }

                if (rule.AccountSource != PMAccountSource.None)
                {
                    if (rule.AccountSource == PMAccountSource.BillingRule)
                    {
                        if (rule.AccountID != null)
                        {
                            arTran.AccountID = rule.AccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.BillingRuleAccountIsNotConfiguredForBilling, rule.BillingID);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Project)
                    {
                        if (project.DefaultAccountID != null)
                        {
                            arTran.AccountID = project.DefaultAccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.ProjectAccountIsNotConfiguredForBilling, rule.BillingID, project.ContractCD);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Task)
                    {
                        if (task.DefaultAccountID != null)
                        {
                            arTran.AccountID = task.DefaultAccountID;
                        }
                        else
                        {
                            throw new PXException(Messages.TaskAccountIsNotConfiguredForBilling, rule.BillingID, project.ContractCD, task.TaskCD);
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.InventoryItem)
                    {
                        InventoryItem item = PXSelect <InventoryItem, Where <InventoryItem.inventoryID, Equal <Required <InventoryItem.inventoryID> > > > .Select(this, tran.InventoryID);

                        if (item != null)
                        {
                            if (item.SalesAcctID != null)
                            {
                                arTran.AccountID = item.SalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.InventoryAccountIsNotConfiguredForBilling, rule.BillingID, item.InventoryCD);
                            }
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Customer && customer != null)
                    {
                        CR.Location customerLoc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(this, customer.BAccountID, customer.DefLocationID);

                        if (customerLoc != null)
                        {
                            if (customerLoc.CSalesAcctID != null)
                            {
                                arTran.AccountID = customerLoc.CSalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.CustomerAccountIsNotConfiguredForBilling, rule.BillingID, customer.AcctCD);
                            }
                        }
                    }
                    else if (rule.AccountSource == PMAccountSource.Resource)
                    {
                        EP.EPEmployee emp = PXSelect <EP.EPEmployee, Where <EP.EPEmployee.bAccountID, Equal <Required <EP.EPEmployee.bAccountID> > > > .Select(this, tran.ResourceID);

                        if (emp != null)
                        {
                            if (emp.SalesAcctID != null)
                            {
                                arTran.AccountID = emp.SalesAcctID;
                            }
                            else
                            {
                                throw new PXException(Messages.EmployeeAccountIsNotConfiguredForBilling, rule.BillingID, emp.AcctCD);
                            }
                        }
                    }

                    if (arTran.AccountID == null && !string.IsNullOrEmpty(rule.SubMask))
                    {
                        throw new PXException(Messages.SubAccountCannotBeComposed, rule.BillingID);
                    }
                    else if (arTran.AccountID != null && !string.IsNullOrEmpty(rule.SubMask))
                    {
                        subCD = PMBillSubAccountMaskAttribute.MakeSub <PMBillingRule.subMask>(this, rule.SubMask,
                                                                                              new object[] { tran.SubID, rule.SubID, project.DefaultSubID, task.DefaultSubID, employeeSubID },
                                                                                              new Type[] { typeof(PMTran.subID), typeof(PMBillingRule.subID), typeof(PMProject.defaultSubID), typeof(PMTask.defaultSubID), typeof(EP.EPEmployee.salesSubID) });
                    }
                }

                #endregion

                string note  = PXNoteAttribute.GetNote(Transactions.Cache, tran);
                Guid[] files = PXNoteAttribute.GetFileNotes(Transactions.Cache, tran);
                list.Add(new BillingData(arTran, rule, tran, subCD, note, files));

                if (billingItems.ContainsKey(tran.InventoryID.Value))
                {
                    if (availableQty.ContainsKey(tran.InventoryID.Value))
                    {
                        decimal available = availableQty[tran.InventoryID.Value];

                        if (tran.BillableQty <= available)
                        {
                            //Transaction is already payed for as a post payment included. Thus it should be free.
                            arTran.TranDesc = PXMessages.LocalizeNoPrefix(CT.Messages.PrefixIncludedUsage) + " " + tran.Description;
                            availableQty[tran.InventoryID.Value] -= arTran.Qty.Value;                            //decrease available qty
                            arTran.UnitPrice = 0;
                            arTran.ExtPrice  = 0;
                            arTran.TranAmt   = 0;
                        }
                        else
                        {
                            arTran.TranDesc = PXMessages.LocalizeNoPrefix(CT.Messages.PrefixOverused) + " " + tran.Description;
                            arTran.Qty      = arTran.Qty - available;
                            availableQty[tran.InventoryID.Value] = 0;                            //all available qty was used.
                        }
                    }
                }

                tran.Billed     = true;
                tran.BilledDate = billingDate;

                Transactions.Update(tran);
            }

            return(list);
        }
Exemplo n.º 27
0
 public virtual PMBudgetLite SelectProjectBalance(IProjectFilter filter, PMAccountGroup ag, PMProject project, out bool isExisting)
 {
     return(SelectProjectBalance(ag, project, filter.TaskID, filter.InventoryID, filter.CostCodeID, out isExisting));
 }
Exemplo n.º 28
0
        protected virtual IEnumerable items()
        {
            BillingFilter filter = Filter.Current;

            if (filter == null)
            {
                yield break;
            }
            bool found = false;

            foreach (ProjectsList item in Items.Cache.Inserted)
            {
                found = true;
                yield return(item);
            }
            if (found)
            {
                yield break;
            }

            PXSelectBase <PMProject> select = new PXSelectJoin <PMProject,
                                                                InnerJoin <ContractBillingSchedule, On <PMProject.contractID, Equal <ContractBillingSchedule.contractID> >,
                                                                           InnerJoin <Customer, On <PMProject.customerID, Equal <Customer.bAccountID> > > >,
                                                                Where2 <Where <ContractBillingSchedule.nextDate, LessEqual <Current <BillingFilter.invoiceDate> >, Or <ContractBillingSchedule.type, Equal <BillingType.BillingOnDemand> > >,
                                                                        And <PMProject.baseType, Equal <PMProject.ProjectBaseType>,
                                                                             And <PMProject.nonProject, Equal <False>,
                                                                                  And <PMProject.isTemplate, Equal <False> > > > > >(this);

            if (filter.StatementCycleId != null)
            {
                select.WhereAnd <Where <Customer.statementCycleId, Equal <Current <BillingFilter.statementCycleId> > > >();
            }
            if (filter.CustomerClassID != null)
            {
                select.WhereAnd <Where <Customer.customerClassID, Equal <Current <BillingFilter.customerClassID> > > >();
            }
            if (filter.CustomerID != null)
            {
                select.WhereAnd <Where <Customer.bAccountID, Equal <Current <BillingFilter.customerID> > > >();
            }
            if (filter.TemplateID != null)
            {
                select.WhereAnd <Where <PMProject.templateID, Equal <Current <BillingFilter.templateID> > > >();
            }

            foreach (PXResult <PMProject, ContractBillingSchedule, Customer> item in select.Select())
            {
                PMProject project = (PMProject)item;
                ContractBillingSchedule schedule = (ContractBillingSchedule)item;
                Customer customer = (Customer)item;

                ProjectsList result = new ProjectsList();
                result.ProjectID    = project.ContractID;
                result.ProjectCD    = project.ContractCD;
                result.Description  = project.Description;
                result.CustomerID   = project.CustomerID;
                result.CustomerName = customer.AcctName;
                result.LastDate     = schedule.LastDate;

                DateTime?fromDate = null;

                if (schedule.NextDate != null)
                {
                    switch (schedule.Type)
                    {
                    case BillingType.Annual:
                        fromDate = schedule.NextDate.Value.AddYears(-1);
                        break;

                    case BillingType.Monthly:
                        fromDate = schedule.NextDate.Value.AddMonths(-1);
                        break;

                    case BillingType.Weekly:
                        fromDate = schedule.NextDate.Value.AddDays(-7);
                        break;

                    case BillingType.Quarterly:
                        fromDate = schedule.NextDate.Value.AddMonths(-3);
                        break;
                    }
                }

                result.FromDate = fromDate;
                result.NextDate = schedule.NextDate;

                yield return(Items.Insert(result));
            }

            Items.Cache.IsDirty = false;
        }
        public virtual void RunProjectBalanceVerification(PMProject project, PMValidationFilter options)
        {
            InitAccountGroup();

            PXDatabase.Delete <PMTaskTotal>(new PXDataFieldRestrict(typeof(PMTaskTotal.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            PXDatabase.Delete <PMTaskAllocTotal>(new PXDataFieldRestrict(typeof(PMTaskAllocTotal.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            PXDatabase.Delete <PMHistory>(new PXDataFieldRestrict(typeof(PMHistory.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            PXDatabase.Delete <PMCommitment>(new PXDataFieldRestrict(typeof(PMCommitment.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ),
                                             new PXDataFieldRestrict(typeof(PMCommitment.type).Name, PXDbType.Char, 1, PMCommitmentType.Internal, PXComp.EQ));

            if (options.RecalculateUnbilledSummary == true)
            {
                PXDatabase.Delete <PMUnbilledDailySummary>(new PXDataFieldRestrict(typeof(PMUnbilledDailySummary.projectID).Name, PXDbType.Int, 4, project.ContractID, PXComp.EQ));
            }

            ProjectBalance pb = CreateProjectBalance();

            Dictionary <BudgetKeyTuple, PMBudgetEx> existingBudgetRecords = new Dictionary <BudgetKeyTuple, PMBudgetEx>();

            if (options.RecalculateChangeOrders == true && project.ChangeOrderWorkflow == true)
            {
                var selectBudget = new PXSelect <PMBudgetEx, Where <PMBudgetEx.projectID, Equal <Required <PMBudgetEx.projectID> > > >(this);
                using (new PXFieldScope(selectBudget.View, typeof(PMBudgetEx.projectID), typeof(PMBudgetEx.projectTaskID)
                                        , typeof(PMBudgetEx.accountGroupID), typeof(PMBudgetEx.inventoryID), typeof(PMBudgetEx.costCodeID)
                                        , typeof(PMBudgetEx.uOM), typeof(PMBudgetEx.qty), typeof(PMBudgetEx.amount)))
                {
                    foreach (PMBudgetEx record in selectBudget.Select(project.ContractID))
                    {
                        existingBudgetRecords.Add(GetKey(record), record);

                        List <PXDataFieldParam> list = BuildBudgetClearCommandWithChangeOrders(options, record);
                        PXDatabase.Update <PMBudget>(list.ToArray());
                    }
                }
            }
            else
            {
                HashSet <int> clearedAccountGroups = new HashSet <int>();
                var           selectBudget         = new PXSelect <PMBudgetEx, Where <PMBudgetEx.projectID, Equal <Required <PMBudgetEx.projectID> > > >(this);
                using (new PXFieldScope(selectBudget.View, typeof(PMBudgetEx.projectID), typeof(PMBudgetEx.projectTaskID)
                                        , typeof(PMBudgetEx.accountGroupID), typeof(PMBudgetEx.inventoryID), typeof(PMBudgetEx.costCodeID)
                                        , typeof(PMBudgetEx.uOM)))
                {
                    foreach (PMBudgetEx record in selectBudget.Select(project.ContractID))
                    {
                        existingBudgetRecords.Add(GetKey(record), record);

                        if (!clearedAccountGroups.Contains(record.AccountGroupID.Value))
                        {
                            List <PXDataFieldParam> list = BuildBudgetClearCommand(options, record);
                            PXDatabase.Update <PMBudget>(list.ToArray());
                            clearedAccountGroups.Add(record.AccountGroupID.Value);
                        }
                    }
                }
            }

            PXSelectBase <PMTran> select = null;

            if (options.RecalculateUnbilledSummary == true)
            {
                select = new PXSelectJoinGroupBy <PMTran,
                                                  LeftJoin <Account, On <PMTran.accountID, Equal <Account.accountID> >,
                                                            LeftJoin <OffsetAccount, On <PMTran.offsetAccountID, Equal <OffsetAccount.accountID> >,
                                                                      LeftJoin <PMAccountGroup, On <PMAccountGroup.groupID, Equal <Account.accountGroupID> >,
                                                                                LeftJoin <OffsetPMAccountGroup, On <OffsetPMAccountGroup.groupID, Equal <OffsetAccount.accountGroupID> > > > > >,
                                                  Where <PMTran.projectID, Equal <Required <PMTran.projectID> >,
                                                         And <PMTran.released, Equal <True> > >,
                                                  Aggregate <GroupBy <PMTran.tranType,
                                                                      GroupBy <PMTran.finPeriodID,
                                                                               GroupBy <PMTran.tranPeriodID,
                                                                                        GroupBy <PMTran.projectID,
                                                                                                 GroupBy <PMTran.taskID,
                                                                                                          GroupBy <PMTran.inventoryID,
                                                                                                                   GroupBy <PMTran.costCodeID,
                                                                                                                            GroupBy <PMTran.date,
                                                                                                                                     GroupBy <PMTran.accountID,
                                                                                                                                              GroupBy <PMTran.accountGroupID,
                                                                                                                                                       GroupBy <PMTran.offsetAccountID,
                                                                                                                                                                GroupBy <PMTran.offsetAccountGroupID,
                                                                                                                                                                         GroupBy <PMTran.uOM,
                                                                                                                                                                                  GroupBy <PMTran.released,
                                                                                                                                                                                           GroupBy <PMTran.remainderOfTranID,
                                                                                                                                                                                                    GroupBy <PMTran.duplicateOfTranID,
                                                                                                                                                                                                             Sum <PMTran.qty,
                                                                                                                                                                                                                  Sum <PMTran.amount,
                                                                                                                                                                                                                       Max <PMTran.billable,
                                                                                                                                                                                                                            GroupBy <PMTran.billed,
                                                                                                                                                                                                                                     GroupBy <PMTran.reversed> > > > > > > > > > > > > > > > > > > > > > >(this);
            }
            else
            {
                select = new PXSelectJoinGroupBy <PMTran,
                                                  LeftJoin <Account, On <PMTran.accountID, Equal <Account.accountID> >,
                                                            LeftJoin <OffsetAccount, On <PMTran.offsetAccountID, Equal <OffsetAccount.accountID> >,
                                                                      LeftJoin <PMAccountGroup, On <PMAccountGroup.groupID, Equal <Account.accountGroupID> >,
                                                                                LeftJoin <OffsetPMAccountGroup, On <OffsetPMAccountGroup.groupID, Equal <OffsetAccount.accountGroupID> > > > > >,
                                                  Where <PMTran.projectID, Equal <Required <PMTran.projectID> >,
                                                         And <PMTran.released, Equal <True> > >,
                                                  Aggregate <GroupBy <PMTran.tranType,
                                                                      GroupBy <PMTran.finPeriodID,
                                                                               GroupBy <PMTran.tranPeriodID,
                                                                                        GroupBy <PMTran.projectID,
                                                                                                 GroupBy <PMTran.taskID,
                                                                                                          GroupBy <PMTran.inventoryID,
                                                                                                                   GroupBy <PMTran.costCodeID,
                                                                                                                            GroupBy <PMTran.accountID,
                                                                                                                                     GroupBy <PMTran.accountGroupID,
                                                                                                                                              GroupBy <PMTran.offsetAccountID,
                                                                                                                                                       GroupBy <PMTran.offsetAccountGroupID,
                                                                                                                                                                GroupBy <PMTran.uOM,
                                                                                                                                                                         GroupBy <PMTran.released,
                                                                                                                                                                                  GroupBy <PMTran.remainderOfTranID,
                                                                                                                                                                                           GroupBy <PMTran.duplicateOfTranID,
                                                                                                                                                                                                    Sum <PMTran.qty,
                                                                                                                                                                                                         Sum <PMTran.amount> > > > > > > > > > > > > > > > > > >(this);
            }

            foreach (PXResult <PMTran, Account, OffsetAccount, PMAccountGroup, OffsetPMAccountGroup> res in select.Select(project.ContractID))
            {
                PMTran tran = (PMTran)res;

                RegisterReleaseProcess.AddToUnbilledSummary(this, tran);

                //suppose we have allocated unbilled 100 - unearned 100
                //during billing we reduced the amount to 80.
                //as a result of this. only 80 will be reversed. leaving 20 on the unbilled.
                //plus a remainder transaction will be generated. (if we allow this remainder to update balance it will add additional 20 to the unbilled.)
                if (tran.RemainderOfTranID != null)
                {
                    continue;                     //skip remainder transactions.
                }
                ProcessTransaction(project, res, pb);
            }

            RebuildAllocationTotals(project);

            if (options.RebuildCommitments == true)
            {
                ProcessPOCommitments(project);
                ProcessSOCommitments(project);
                ProcessExternalCommitments(project);
            }

            if (options.RecalculateDraftInvoicesAmount == true)
            {
                RecalculateDraftInvoicesAmount(project, pb);
            }

            if (options.RecalculateChangeOrders == true && project.ChangeOrderWorkflow == true)
            {
                RecalculateChangeOrders(project, pb, existingBudgetRecords);
            }

            InitCostCodeOnModifiedEntities();
        }
        public virtual void ProcessTransaction(PMProject project, PXResult <PMTran, Account, OffsetAccount, PMAccountGroup, OffsetPMAccountGroup> res, ProjectBalance pb)
        {
            PMTran               tran      = (PMTran)res;
            Account              acc       = (Account)res;
            PMAccountGroup       ag        = (PMAccountGroup)res;
            OffsetAccount        offsetAcc = (OffsetAccount)res;
            OffsetPMAccountGroup offsetAg  = (OffsetPMAccountGroup)res;

            IList <ProjectBalance.Result> balances = pb.Calculate(project, tran, acc, ag, offsetAcc, offsetAg);

            foreach (ProjectBalance.Result balance in balances)
            {
                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 = Budget.Insert(ps);

                    ps.ActualQty    += balance.Status.ActualQty.GetValueOrDefault();
                    ps.ActualAmount += balance.Status.ActualAmount.GetValueOrDefault();
                }

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

                    ta            = TaskTotals.Insert(ta);
                    ta.Asset     += balance.TaskTotal.Asset.GetValueOrDefault();
                    ta.Liability += balance.TaskTotal.Liability.GetValueOrDefault();
                    ta.Income    += balance.TaskTotal.Income.GetValueOrDefault();
                    ta.Expense   += balance.TaskTotal.Expense.GetValueOrDefault();
                }


                foreach (PMHistory item in balance.History)
                {
                    PMHistoryAccum hist = new PMHistoryAccum();
                    hist.ProjectID      = item.ProjectID;
                    hist.ProjectTaskID  = item.ProjectTaskID;
                    hist.AccountGroupID = item.AccountGroupID;
                    hist.InventoryID    = item.InventoryID;
                    hist.CostCodeID     = item.CostCodeID;
                    hist.PeriodID       = item.PeriodID;

                    hist = History.Insert(hist);
                    hist.FinPTDAmount  += item.FinPTDAmount.GetValueOrDefault();
                    hist.FinYTDAmount  += item.FinYTDAmount.GetValueOrDefault();
                    hist.FinPTDQty     += item.FinPTDQty.GetValueOrDefault();
                    hist.FinYTDQty     += item.FinYTDQty.GetValueOrDefault();
                    hist.TranPTDAmount += item.TranPTDAmount.GetValueOrDefault();
                    hist.TranYTDAmount += item.TranYTDAmount.GetValueOrDefault();
                    hist.TranPTDQty    += item.TranPTDQty.GetValueOrDefault();
                    hist.TranYTDQty    += item.TranYTDQty.GetValueOrDefault();
                }
            }
        }