Ejemplo n.º 1
0
        public virtual void VerifyExchangeRateExistsForProject(int?newProjectID)
        {
            if (!PXAccess.FeatureInstalled <FeaturesSet.projectMultiCurrency>())
            {
                return;
            }

            if (!IsCommitmentsEnabled())
            {
                return;
            }

            PMProject project;

            if (ProjectDefaultAttribute.IsProject(Base, newProjectID, out project) && Base.Document.Current != null)
            {
                var curySettings = PMCommitmentAttribute.GetCurrencySettings(Base, newProjectID, Base.Document.Current.CuryID);

                if (!curySettings.UseBaseCurrency && curySettings.ConverionRequired)
                {
                    CM.Extensions.IPXCurrencyService currencyService = ServiceLocator.Current.GetInstance <Func <PXGraph, CM.Extensions.IPXCurrencyService> >()(Base);
                    var rate = currencyService.GetRate(curySettings.FromCuryID, curySettings.ToCuryID, curySettings.RateTypeID, Base.Document.Current.OrderDate.GetValueOrDefault(DateTime.Now));

                    if (rate == null)
                    {
                        var ex = new PXSetPropertyException(Messages.ConversionRateNotDefinedForCommitment, curySettings.FromCuryID, curySettings.ToCuryID, curySettings.RateTypeID, Base.Document.Current.OrderDate.GetValueOrDefault(DateTime.Now));
                        ex.ErrorValue = project.ContractCD;

                        throw ex;
                    }
                }
            }
        }
 protected virtual void _(Events.FieldUpdated <EPActivityApprove, EPActivityApprove.earningTypeID> e)
 {
     if (e.Row.ProjectID == null || ProjectDefaultAttribute.IsNonProject(e.Row.ProjectID))
     {
         e.Cache.SetDefaultExt <EPActivityApprove.projectID>(e.Row);
     }
 }
        public virtual int?GetDefaultLaborItem(PXGraph graph, EPEmployee employee, string earningType, int?projectID)
        {
            if (employee == null)
            {
                return(null);
            }

            int?result = null;

            if (ProjectDefaultAttribute.IsProject(graph, projectID))
            {
                result = EPContractRate.GetProjectLaborClassID(graph, projectID.Value, employee.BAccountID.Value, earningType);
            }

            if (result == null)
            {
                result = EPEmployeeClassLaborMatrix.GetLaborClassID(graph, employee.BAccountID, earningType);
            }

            if (result == null)
            {
                result = employee.LabourItemID;
            }

            return(result);
        }
Ejemplo n.º 4
0
        public virtual int?GetDefaultLaborItem(int?employeeID, string earningType, int?projectID)
        {
            if (employeeID == null)
            {
                return(null);
            }

            int?result = null;

            if (ProjectDefaultAttribute.IsProject(this, projectID))
            {
                result = EPContractRate.GetProjectLaborClassID(this, projectID.Value, employeeID.Value, earningType);
            }

            if (result == null)
            {
                result = EPEmployeeClassLaborMatrix.GetLaborClassID(this, employeeID, earningType);
            }

            if (result == null)
            {
                EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Current <EPTimeCard.employeeID> > > > .Select(this);

                if (employee != null)
                {
                    result = employee.LabourItemID;
                }
            }

            return(result);
        }
        public void FieldDefaulting(PXCache sender, PXFieldDefaultingEventArgs e)
        {
            EPEmployee employee = null;

            if (employeeSearch != null)
            {
                BqlCommand cmd  = BqlCommand.CreateInstance(employeeSearch);
                PXView     view = new PXView(sender.Graph, false, cmd);

                employee = view.SelectSingle() as EPEmployee;
            }

            if (employee != null && !string.IsNullOrEmpty(employee.UnionID))
            {
                HashSet <string> validUnions = new HashSet <string>();
                if (projectField != null)
                {
                    int?projectID = (int?)sender.GetValue(e.Row, projectField.Name);

                    if (ProjectDefaultAttribute.IsProject(sender.Graph, projectID))
                    {
                        var select = new PXSelect <PMProjectUnion, Where <PMProjectUnion.projectID, Equal <Required <PMProjectUnion.projectID> > > >(sender.Graph);
                        foreach (PMProjectUnion union in select.Select(projectID))
                        {
                            validUnions.Add(union.UnionID);
                        }
                    }
                }

                if (validUnions.Count == 0 || validUnions.Contains(employee.UnionID))
                {
                    e.NewValue = employee.UnionID;
                }
            }
        }
Ejemplo n.º 6
0
 protected virtual void OnProjectUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
 {
     if (ProjectField != null)
     {
         object projectID = sender.GetValue(e.Row, ProjectField.Name);
         if (projectID == null || ProjectDefaultAttribute.IsNonProject((int?)projectID))
         {
             sender.SetValueExt(e.Row, _FieldName, null);
         }
     }
 }
Ejemplo n.º 7
0
        private void SetViewPMTransEnabled(ARInvoice doc)
        {
            var       enabled = false;
            PMProject project;

            if (doc != null && ProjectDefaultAttribute.IsProject(Base, doc.ProjectID, out project))
            {
                enabled = project.BaseType == CT.CTPRType.Project;
            }

            Base.inquiry.SetEnabled(Messages.ViewPMTrans, enabled);
        }
Ejemplo n.º 8
0
        protected virtual void _(Events.FieldDefaulting <ARTran, ARTran.costCodeID> e)
        {
            PMProject project;

            if (CostCodeAttribute.UseCostCode() && ProjectDefaultAttribute.IsProject(Base, e.Row.ProjectID, out project))
            {
                if (project.BudgetLevel == BudgetLevels.Task)
                {
                    e.NewValue = CostCodeAttribute.GetDefaultCostCode();
                }
            }
        }
        public bool ValidateRelatedProjectField <TEntity, TEntityField>(TEntity entity, object fieldValue)
            where TEntity : class, IBqlTable, new()
            where TEntityField : IBqlField
        {
            var cache = graph.Caches <TEntity>();
            var hasExpiredDocuments   = DoExpiredDocumentsExist <ComplianceDocument.projectID>(fieldValue);
            var isDefaultProject      = fieldValue as int? == ProjectDefaultAttribute.NonProject();
            var validationErrorNeeded = hasExpiredDocuments && !isDefaultProject;

            RaiseOrClearExceptionForRelatedField <TEntityField>(cache, entity, validationErrorNeeded,
                                                                PXErrorLevel.Warning);
            return(validationErrorNeeded);
        }
Ejemplo n.º 10
0
        public virtual void VerifyProjectLockCommitments(int?newProjectID)
        {
            if (!PXAccess.FeatureInstalled <FeaturesSet.changeOrder>())
            {
                return;
            }

            PMProject project;

            if (ProjectDefaultAttribute.IsProject(Base, newProjectID, out project) && project.LockCommitments == true)
            {
                var ex = new PXSetPropertyException(PM.Messages.ProjectCommintmentsLocked);
                ex.ErrorValue = project.ContractCD;

                throw ex;
            }
        }
Ejemplo n.º 11
0
        private bool IsInventoryItemValid(POLine subcontractLine)
        {
            if (subcontractLine.InventoryID == null || !ShouldValidateInventoryItem() ||
                subcontractLine.ProjectID == null || ProjectDefaultAttribute.IsNonProject(subcontractLine.ProjectID))
            {
                return(true);
            }

            var project = GetProject(subcontractLine.ProjectID);

            if (IsNonProjectAccountGroupsAllowed(project) || !IsItemLevel(project))
            {
                return(true);
            }
            var result = IsInventoryItemUsedInProject(subcontractLine, subcontractLine.InventoryID);

            return(result);
        }
Ejemplo n.º 12
0
        public IEnumerable ViewTransactions(PXAdapter adapter)
        {
            if (ProjectStatus.Current != null)
            {
                TransactionInquiry target = PXGraph.CreateInstance <TransactionInquiry>();
                target.Filter.Insert(new TransactionInquiry.TranFilter());
                target.Filter.Current.AccountGroupID = ProjectStatus.Current.AccountGroupID;
                target.Filter.Current.ProjectID      = ProjectStatus.Current.ProjectID;
                target.Filter.Current.ProjectTaskID  = ProjectStatus.Current.ProjectTaskID;
                if (ProjectStatus.Current.InventoryID != null && !ProjectDefaultAttribute.IsNonProject(this, ProjectStatus.Current.InventoryID))
                {
                    target.Filter.Current.InventoryID = ProjectStatus.Current.InventoryID;
                }

                throw new PXPopupRedirectException(target, Messages.TransactionInquiry + " - " + Messages.ViewTransactions, false);
            }
            return(adapter.Get());
        }
Ejemplo n.º 13
0
        private bool IsInventoryItemUsedInProject(POLine subcontractLine, int?inventoryID)
        {
            if (subcontractLine.ProjectID == null || ProjectDefaultAttribute.IsNonProject(subcontractLine.ProjectID))
            {
                return(false);
            }

            var project = GetProject(subcontractLine.ProjectID);

            if (!IsItemLevel(project))
            {
                return(false);
            }

            var query      = new PXSelect <PMCostBudget, Where <PMCostBudget.projectID, Equal <Required <PMCostBudget.projectID> > > >(this);
            var parameters = new List <object>();

            parameters.Add(subcontractLine.ProjectID);

            if (subcontractLine.TaskID.HasValue)
            {
                query.WhereAnd <Where <PMCostBudget.projectTaskID, Equal <Required <PMCostBudget.projectTaskID> > > >();
                parameters.Add(subcontractLine.TaskID);
            }

            var accountGroupID = GetAccountGroup(subcontractLine, inventoryID);

            if (accountGroupID.HasValue)
            {
                query.WhereAnd <Where <PMCostBudget.accountGroupID, Equal <Required <PMCostBudget.accountGroupID> > > >();
                parameters.Add(accountGroupID);
            }

            if (subcontractLine.CostCodeID.HasValue)
            {
                query.WhereAnd <Where <PMCostBudget.costCodeID, Equal <Required <PMCostBudget.costCodeID> > > >();
                parameters.Add(subcontractLine.CostCodeID);
            }

            var result = query.Select(parameters.ToArray()).AsEnumerable()
                         .Any(b => ((PMCostBudget)b).InventoryID == inventoryID);

            return(result);
        }
Ejemplo n.º 14
0
        protected virtual void INTran_ReasonCode_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
        {
            INTran row = e.Row as INTran;

            if (row != null)
            {
                ReasonCode reasoncd = PXSelect <ReasonCode, Where <ReasonCode.reasonCodeID, Equal <Optional <ReasonCode.reasonCodeID> > > > .Select(this, e.NewValue);

                if (reasoncd != null && row.ProjectID != null && !ProjectDefaultAttribute.IsNonProject(this, row.ProjectID))
                {
                    PX.Objects.GL.Account account = PXSelect <PX.Objects.GL.Account, Where <PX.Objects.GL.Account.accountID, Equal <Required <PX.Objects.GL.Account.accountID> > > > .Select(this, reasoncd.AccountID);

                    if (account != null && account.AccountGroupID == null)
                    {
                        sender.RaiseExceptionHandling <INTran.reasonCode>(e.Row, account.AccountCD, new PXSetPropertyException(PM.Messages.NoAccountGroup, PXErrorLevel.Warning, account.AccountCD));
                    }
                }

                e.Cancel = (reasoncd != null) &&
                           (row.TranType != INTranType.Issue && row.TranType != INTranType.Receipt && reasoncd.Usage == ReasonCodeUsages.Sales || reasoncd.Usage == row.DocType);
            }
        }
Ejemplo n.º 15
0
        public virtual List <APRegister> ReleaseClaimDetails
        <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>
            (ExpenseClaimEntry expenseClaimGraph, EPExpenseClaim claim, IEnumerable <EPExpenseClaimDetails> receipts, string receiptGroupPaidWithType)
            where TGraph : PXGraph, new()
            where TAPDocument : InvoiceBase, new()
            where TInvoiceMapping : IBqlMapping
            where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping>
        {
            #region prepare required variable

            var docgraph = PXGraph.CreateInstance <TGraph>();

            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            TAPDocumentGraphExtension apDocumentGraphExtension = docgraph.FindImplementation <TAPDocumentGraphExtension>();

            List <List <EPExpenseClaimDetails> > receiptsForDocument = new List <List <EPExpenseClaimDetails> >();

            if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
            {
                receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode })
                                      .Select(group => group.ToList())
                                      .ToList();
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
            {
                if (epsetup.PostSummarizedCorpCardExpenseReceipts == true)
                {
                    receiptsForDocument = receipts.GroupBy(item =>
                                                           new
                    {
                        item.TaxZoneID,
                        item.TaxCalcMode,
                        item.CorpCardID,
                        item.ExpenseDate,
                        item.ExpenseRefNbr
                    })
                                          .Select(group => group.ToList())
                                          .ToList();
                }
                else
                {
                    receiptsForDocument = receipts.Select(receipt => receipt.SingleToList()).ToList();
                }
            }
            else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
            {
                receiptsForDocument = new List <List <EPExpenseClaimDetails> >()
                {
                    receipts.ToList()
                };
            }
            else
            {
                throw new NotImplementedException();
            }

            if (!receiptsForDocument.Any())
            {
                receiptsForDocument.Add(new List <EPExpenseClaimDetails>());
            }

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();


            if (claim.FinPeriodID != null)
            {
                FinPeriodUtils.ValidateFinPeriod(claim.SingleToArray());
            }
            #endregion

            foreach (var receiptGroup in receiptsForDocument)
            {
                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count > 1)
                {
                    EPExpenseClaimDetails[] matchedReceipts = receiptGroup.Where(receipt => receipt.BankTranDate != null).Take(11).ToArray();

                    if (matchedReceipts.Any())
                    {
                        PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran>[] rows =
                            PXSelectJoin <EPExpenseClaimDetails,
                                          InnerJoin <CABankTranMatch,
                                                     On <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                                         And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                              And <CABankTranMatch.docRefNbr, Equal <EPExpenseClaimDetails.claimDetailCD> > > >,
                                                     InnerJoin <CABankTran,
                                                                On <CABankTran.tranID, Equal <CABankTranMatch.tranID> > > >,
                                          Where <EPExpenseClaimDetails.claimDetailCD, In <Required <EPExpenseClaimDetails.claimDetailCD> > > >
                            .Select(expenseClaimGraph, matchedReceipts.Select(receipt => receipt.ClaimDetailCD).ToArray())
                            .Cast <PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran> >()
                            .ToArray();

                        throw new PXException(Messages.ExpenseReceiptCannotBeSummarized,
                                              rows.Select(row => String.Concat(PXMessages.LocalizeNoPrefix(Messages.Receipt),
                                                                               " ",
                                                                               ((EPExpenseClaimDetails)row).ClaimDetailCD,
                                                                               " - ",
                                                                               ((CABankTran)row).GetFriendlyKeyImage(Caches[typeof(CABankTran)])))
                                              .ToArray()
                                              .JoinIntoStringForMessageNoQuotes(maxCount: 10));
                    }
                }

                docgraph.Clear(PXClearOption.ClearAll);
                docgraph.SelectTimeStamp();
                apDocumentGraphExtension.Contragent.Current = apDocumentGraphExtension.Contragent.Cache.GetExtension <Contragent>(employee);
                apDocumentGraphExtension.Location.Current   = emplocation;

                CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                      Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

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

                info.CuryInfoID = null;
                info            = apDocumentGraphExtension.CurrencyInfo.Insert(info);

                #region CreateInvoiceHeader

                var invoice = new TAPDocument();

                CABankTranMatch bankTranMatch = null;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount)
                {
                    invoice.DocType = receiptGroup.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0
                        ? APInvoiceType.DebitAdj
                        : APInvoiceType.Invoice;
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense)
                {
                    EPExpenseClaimDetails receipt = receiptGroup.First();

                    invoice.DocType = APDocType.QuickCheck;

                    CACorpCard card = CACorpCard.PKID.Find(this, receipt.CorpCardID);

                    PaymentMethodAccount paymentMethodAccount = PXSelect <PaymentMethodAccount,
                                                                          Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> > > >
                                                                .Select(this, card.CashAccountID);

                    invoice.CashAccountID   = card.CashAccountID;
                    invoice.PaymentMethodID = paymentMethodAccount.PaymentMethodID;
                    invoice.ExtRefNbr       = receipt.ExpenseRefNbr;

                    if (receiptGroup.Count == 1)
                    {
                        bankTranMatch =
                            PXSelect <CABankTranMatch,
                                      Where <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>,
                                             And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>,
                                                  And <CABankTranMatch.docRefNbr, Equal <Required <CABankTranMatch.docRefNbr> > > > > >
                            .Select(expenseClaimGraph, receipt.ClaimDetailCD);

                        if (bankTranMatch != null)
                        {
                            CABankTran bankTran = CABankTran.PK.Find(expenseClaimGraph, bankTranMatch.TranID);

                            invoice.ClearDate = bankTran.ClearDate;
                            invoice.Cleared   = true;
                        }
                    }
                }
                else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.DocType = APDocType.DebitAdj;
                }
                else
                {
                    throw new NotImplementedException();
                }

                invoice.CuryInfoID = info.CuryInfoID;

                invoice.Hold     = true;
                invoice.Released = false;
                invoice.Printed  = invoice.DocType == APDocType.QuickCheck;
                invoice.OpenDoc  = true;

                invoice.HeaderDocDate        = claim.DocDate;
                invoice.FinPeriodID          = claim.FinPeriodID;
                invoice.InvoiceNbr           = claim.RefNbr;
                invoice.DocDesc              = claim.DocDesc;
                invoice.ContragentID         = claim.EmployeeID;
                invoice.CuryID               = info.CuryID;
                invoice.ContragentLocationID = claim.LocationID;
                invoice.ModuleAccountID      = emplocation != null ? emplocation.APAccountID : null;
                invoice.ModuleSubID          = emplocation != null ? emplocation.APSubID : null;
                invoice.TaxCalcMode          = receiptGroup.Any() ? receiptGroup.First().TaxCalcMode: claim.TaxCalcMode;
                invoice.BranchID             = claim.BranchID;
                invoice.OrigModule           = BatchModule.EP;

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1)
                {
                    invoice.OrigDocType = EPExpenseClaimDetails.DocType;
                    invoice.OrigRefNbr  = receiptGroup.Single().ClaimDetailCD;
                }
                else
                {
                    invoice.OrigDocType = EPExpenseClaim.DocType;
                    invoice.OrigRefNbr  = claim.RefNbr;
                }

                bool reversedDocument = invoice.DocType == APInvoiceType.DebitAdj && receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount;

                decimal signOperation = reversedDocument ? -1 : 1;

                invoice = apDocumentGraphExtension.Documents.Insert(invoice);
                (apDocumentGraphExtension.Documents.Cache as PXModelExtension <TAPDocument>)?.UpdateExtensionMapping(invoice, MappingSyncDirection.BaseToExtension);

                invoice.TaxZoneID = receiptGroup.Any() ? receiptGroup.First().TaxZoneID : claim.TaxZoneID;

                invoice = apDocumentGraphExtension.Documents.Update(invoice);

                PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                info.CuryInfoID = invoice.CuryInfoID;

                PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, apDocumentGraphExtension.Documents.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                #endregion

                TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc);

                decimal?claimCuryTaxRoundDiff = 0m;
                decimal?claimTaxRoundDiff     = 0m;
                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    #region AddDetails

                    decimal tipQty;
                    if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                    {
                        tipQty = 1;
                    }
                    else
                    {
                        tipQty = -1;
                    }
                    Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                    if (claimdetail.TaskID != null)
                    {
                        PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                        if (task != null && !(bool)task.VisibleInAP)
                        {
                            throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                        }
                    }

                    InvoiceTran tran = new InvoiceTran();
                    tran.InventoryID = claimdetail.InventoryID;
                    tran.TranDesc    = claimdetail.TranDesc;
                    decimal unitCost;
                    decimal amount;
                    decimal taxableAmt;
                    decimal taxAmt;
                    if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                    {
                        unitCost   = claimdetail.CuryUnitCost ?? 0m;
                        amount     = claimdetail.CuryTaxableAmt ?? 0m;
                        taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                        taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                    }
                    else
                    {
                        if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                        {
                            unitCost = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                        }
                        if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                        {
                            amount = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                        }
                        if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                        {
                            taxableAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                        }
                        if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                        {
                            taxAmt = 0m;
                        }
                        else
                        {
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                        }
                    }

                    tran.ManualPrice       = true;
                    tran.CuryUnitCost      = unitCost;
                    tran.Qty               = claimdetail.Qty * signOperation;
                    tran.UOM               = claimdetail.UOM;
                    tran.NonBillable       = claimdetail.Billable != true;
                    claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                    claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                    tran.Date              = claimdetail.ExpenseDate;

                    if (contract.BaseType == CT.CTPRType.Project)
                    {
                        tran.ProjectID = claimdetail.ContractID;
                    }
                    else
                    {
                        tran.ProjectID = ProjectDefaultAttribute.NonProject();
                    }

                    tran.TaskID     = claimdetail.TaskID;
                    tran.CostCodeID = claimdetail.CostCodeID;

                    if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        CACorpCard  card        = CACorpCard.PKID.Find(this, claimdetail.CorpCardID);
                        CashAccount cashAccount = CashAccount.PK.Find(this, card.CashAccountID);

                        tran.AccountID = cashAccount.AccountID;
                        tran.SubID     = cashAccount.SubID;
                    }
                    else
                    {
                        tran.AccountID = claimdetail.ExpenseAccountID;
                        tran.SubID     = claimdetail.ExpenseSubID;
                    }

                    tran.BranchID = claimdetail.BranchID;


                    tran = InsertInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });

                    if (claimdetail.PaidWith == EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        claimdetail.APLineNbr = tran.LineNbr;
                    }

                    tran.CuryLineAmt    = amount * signOperation;
                    tran.CuryTaxAmt     = 0;
                    tran.CuryTaxableAmt = taxableAmt * signOperation;
                    tran.CuryTaxAmt     = taxAmt * signOperation;
                    tran.TaxCategoryID  = claimdetail.TaxCategoryID;


                    tran = UpdateInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran,
                                                    new InvoiceTranContext {
                        EPClaim = claim, EPClaimDetails = claimdetail
                    });


                    if ((claimdetail.CuryTipAmt ?? 0) != 0)
                    {
                        InvoiceTran tranTip = new InvoiceTran();
                        if (epsetup.NonTaxableTipItem == null)
                        {
                            throw new PXException(Messages.TipItemIsNotDefined);
                        }
                        IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                             Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                        if (tipItem == null)
                        {
                            string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                            throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                        }
                        tranTip.InventoryID = epsetup.NonTaxableTipItem;
                        tranTip.TranDesc    = tipItem.Descr;
                        if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                            tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                        }
                        else
                        {
                            decimal tipAmt;
                            PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                            tranTip.CuryUnitCost = Math.Abs(tipAmt);
                            tranTip.CuryTranAmt  = tipAmt * signOperation;
                        }
                        tranTip.Qty         = tipQty;
                        tranTip.UOM         = tipItem.BaseUnit;
                        tranTip.NonBillable = claimdetail.Billable != true;
                        tranTip.Date        = claimdetail.ExpenseDate;

                        tranTip.BranchID = claimdetail.BranchID;

                        tranTip = InsertInvoiceTipTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                              new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });


                        if (epsetup.UseReceiptAccountForTips == true)
                        {
                            tranTip.AccountID = claimdetail.ExpenseAccountID;
                            tranTip.SubID     = claimdetail.ExpenseSubID;
                        }
                        else
                        {
                            tranTip.AccountID = tipItem.COGSAcctID;
                            Location companyloc = (Location)PXSelectJoin <Location,
                                                                          InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                    And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                     InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                          Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                            PMTask task = PXSelect <PMTask,
                                                    Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                           And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                            Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                            int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                            int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                            int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                            int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                            int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                            int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                            object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                    new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                    new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                            docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                            tranTip.SubID = (int?)value;
                        }

                        tranTip = UpdateInvoiceTipTransactionAccounts(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                      new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });

                        tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                        tranTip.ProjectID     = tran.ProjectID;
                        tranTip.TaskID        = tran.TaskID;
                        tranTip = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tranTip, true);


                        tranTip = UpdateInvoiceTipTransactionTaxesAndProject(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip,
                                                                             new InvoiceTranContext {
                            EPClaim = claim, EPClaimDetails = claimdetail
                        });
                    }

                    PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, apDocumentGraphExtension.InvoiceTrans.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    claimdetail.Released = true;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    #endregion

                    if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                    {
                        tran = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tran, false);
                    }
                }

                #region legacy taxes
                foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                 Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                {
                    #region Add taxes
                    GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(tax.TaxID);

                    if (new_aptax == null)
                    {
                        new_aptax       = new GenericTaxTran();
                        new_aptax.TaxID = tax.TaxID;
                        new_aptax       = apDocumentGraphExtension.TaxTrans.Insert(new_aptax);
                        if (new_aptax != null)
                        {
                            new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                            new_aptax.CuryTaxableAmt = 0m;
                            new_aptax.CuryTaxAmt     = 0m;
                            new_aptax.CuryExpenseAmt = 0m;
                            new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                        }
                    }

                    if (new_aptax != null)
                    {
                        new_aptax                = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax);
                        new_aptax.TaxRate        = tax.TaxRate;
                        new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                        new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                        new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                        new_aptax                = apDocumentGraphExtension.TaxTrans.Update(new_aptax);
                    }
                    #endregion
                }
                #endregion

                invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                invoice.Hold           = false;
                apDocumentGraphExtension.SuppressApproval();
                apDocumentGraphExtension.Documents.Update(invoice);

                if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense)
                {
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (InvoiceTran line in apDocumentGraphExtension.InvoiceTrans.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }
                }

                invoice = apDocumentGraphExtension.Documents.Update(invoice);
                docgraph.Actions.PressSave();

                if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense &&
                    receiptGroup.Count == 1 &&
                    bankTranMatch != null)
                {
                    CABankTransactionsMaint.RematchFromExpenseReceipt(this, bankTranMatch, invoice.CATranID, invoice.ContragentID, receiptGroup.Single());
                }

                foreach (EPExpenseClaimDetails claimdetail in receiptGroup)
                {
                    claimdetail.APDocType = invoice.DocType;
                    claimdetail.APRefNbr  = invoice.RefNbr;
                    expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                }

                claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                claim.Released = true;

                expenseClaimGraph.ExpenseClaim.Update(claim);


                #region EP History Update
                EPHistory hist = new EPHistory();
                hist.EmployeeID  = invoice.ContragentID;
                hist.FinPeriodID = invoice.FinPeriodID;
                hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                hist.FinPtdClaimed += invoice.DocBal;
                hist.FinYtdClaimed += invoice.DocBal;
                if (invoice.FinPeriodID == invoice.HeaderTranPeriodID)
                {
                    hist.TranPtdClaimed += invoice.DocBal;
                    hist.TranYtdClaimed += invoice.DocBal;
                }
                else
                {
                    EPHistory tranhist = new EPHistory();
                    tranhist.EmployeeID      = invoice.ContragentID;
                    tranhist.FinPeriodID     = invoice.HeaderTranPeriodID;
                    tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                    tranhist.TranPtdClaimed += invoice.DocBal;
                    tranhist.TranYtdClaimed += invoice.DocBal;
                }
                expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                #endregion

                expenseClaimGraph.Save.Press();

                Actions.PressSave();

                doclist.Add((APRegister)apDocumentGraphExtension.Documents.Current.Base);
            }

            return(doclist);
        }
Ejemplo n.º 16
0
        public List <Batch> Release(JournalEntry je, PMRegister doc, out List <PMTask> allocTasks)
        {
            doc = OnBeforeRelease(doc);

            allocTasks = new List <PMTask>();

            List <Batch> batches = new List <Batch>();
            Dictionary <string, PMTask> tasksToAutoAllocate = new Dictionary <string, PMTask>();
            List <PMTran> sourceForAllocation = new List <PMTran>();
            Dictionary <string, List <TranInfo> > transByFinPeriod = GetTransByBranchAndFinPeriod(doc);

            Debug.Assert(transByFinPeriod.Count > 0, "Failed to select transactions by finperiod in PMRegister Release.");

            ProjectBalance pb = CreateProjectBalance();

            using (var ts = new PXTransactionScope())
            {
                foreach (KeyValuePair <string, List <TranInfo> > kv in transByFinPeriod)
                {
                    string[] parts    = kv.Key.Split('.');
                    int?     branchID = parts[0] == "0" ? null : (int?)int.Parse(parts[0]);

                    je.Clear(PXClearOption.ClearAll);

                    CurrencyInfo info = new CurrencyInfo();
                    info.CuryID      = parts[2];
                    info.CuryEffDate = Accessinfo.BusinessDate;
                    info             = je.currencyinfo.Insert(info);

                    Batch newbatch = new Batch();
                    newbatch.Module      = doc.Module;
                    newbatch.Status      = BatchStatus.Unposted;
                    newbatch.Released    = true;
                    newbatch.Hold        = false;
                    newbatch.BranchID    = branchID;
                    newbatch.FinPeriodID = parts[1];
                    newbatch.CuryID      = parts[2];
                    newbatch.CuryInfoID  = info.CuryInfoID;
                    newbatch.Description = doc.Description;
                    je.BatchModule.Insert(newbatch);

                    bool tranAdded = false;
                    foreach (TranInfo t in kv.Value)
                    {
                        bool isGL = false;

                        if (t.Tran.Released != true && t.Tran.IsNonGL != true && t.Project.BaseType == CT.CTPRType.Project &&
                            !string.IsNullOrEmpty(t.AccountGroup.Type) && t.AccountGroup.Type != PMAccountType.OffBalance && !ProjectDefaultAttribute.IsNonProject(t.Tran.ProjectID) &&
                            t.Tran.AccountID != null && t.Tran.SubID != null && t.Tran.OffsetAccountID != null && t.Tran.OffsetSubID != null)
                        {
                            GLTran tran1 = new GLTran();
                            tran1.TranDate      = t.Tran.Date;
                            tran1.TranPeriodID  = t.Tran.TranPeriodID;
                            tran1.SummPost      = false;
                            tran1.BranchID      = t.Tran.BranchID;
                            tran1.PMTranID      = t.Tran.TranID;
                            tran1.ProjectID     = t.Tran.ProjectID;
                            tran1.TaskID        = t.Tran.TaskID;
                            tran1.CostCodeID    = t.Tran.CostCodeID;
                            tran1.TranDesc      = t.Tran.Description;
                            tran1.ReferenceID   = t.Tran.BAccountID;
                            tran1.InventoryID   = t.Tran.InventoryID == PMInventorySelectorAttribute.EmptyInventoryID ? null : t.Tran.InventoryID;
                            tran1.Qty           = t.Tran.Qty;
                            tran1.UOM           = t.Tran.UOM;
                            tran1.TranType      = t.Tran.TranType;
                            tran1.CuryInfoID    = t.Tran.BaseCuryInfoID;
                            tran1.CuryCreditAmt = 0;
                            tran1.CreditAmt     = 0;
                            tran1.CuryDebitAmt  = t.Tran.TranCuryAmount;
                            tran1.DebitAmt      = t.Tran.Amount;
                            tran1.AccountID     = t.Tran.AccountID;
                            tran1.SubID         = t.Tran.SubID;
                            tran1.Released      = true;
                            je.GLTranModuleBatNbr.Insert(tran1);

                            GLTran tran2 = new GLTran();
                            tran2.TranDate      = t.Tran.Date;
                            tran2.TranPeriodID  = t.Tran.TranPeriodID;
                            tran2.SummPost      = false;
                            tran2.BranchID      = t.Tran.BranchID;
                            tran2.PMTranID      = t.Tran.TranID;
                            tran2.ProjectID     = t.OffsetAccountGroup.GroupID != null ? t.Tran.ProjectID : ProjectDefaultAttribute.NonProject();
                            tran2.TaskID        = t.OffsetAccountGroup.GroupID != null ? t.Tran.TaskID : null;
                            tran2.CostCodeID    = tran2.TaskID != null ? t.Tran.CostCodeID : null;
                            tran2.TranDesc      = t.Tran.Description;
                            tran2.ReferenceID   = t.Tran.BAccountID;
                            tran2.InventoryID   = t.Tran.InventoryID == PMInventorySelectorAttribute.EmptyInventoryID ? null : t.Tran.InventoryID;
                            tran2.Qty           = t.Tran.Qty;
                            tran2.UOM           = t.Tran.UOM;
                            tran2.TranType      = t.Tran.TranType;
                            tran2.CuryInfoID    = t.Tran.BaseCuryInfoID;
                            tran2.CuryCreditAmt = t.Tran.TranCuryAmount;
                            tran2.CreditAmt     = t.Tran.Amount;
                            tran2.CuryDebitAmt  = 0;
                            tran2.DebitAmt      = 0;
                            tran2.AccountID     = t.Tran.OffsetAccountID;
                            tran2.SubID         = t.Tran.OffsetSubID;
                            tran2.Released      = true;
                            je.GLTranModuleBatNbr.Insert(tran2);

                            tranAdded       = true;
                            isGL            = true;
                            t.Tran.BatchNbr = je.BatchModule.Current.BatchNbr;
                        }

                        if (!isGL)
                        {
                            if (t.Tran.AccountGroupID == null && t.Project.BaseType == CT.CTPRType.Project && t.Project.NonProject != true)
                            {
                                throw new PXException(Messages.AccountGroupIsRequired, doc.RefNbr);
                            }
                        }

                        if (t.Tran.ExcludedFromBalance != true)
                        {
                            JournalEntryProjectExt        xje      = je.GetExtension <JournalEntryProjectExt>();
                            IList <ProjectBalance.Result> balances = pb.Calculate(t.Project, t.Tran, t.Account, t.AccountGroup, t.OffsetAccount, t.OffsetAccountGroup);
                            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.CuryInfoID     = balance.Status.CuryInfoID;

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

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

                                    forecast = xje.ForecastHistory.Insert(forecast);

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

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

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

                                if (!isGL)
                                {
                                    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.BranchID       = item.BranchID;

                                        hist = (PMHistoryAccum)je.Caches[typeof(PMHistoryAccum)].Insert(hist);
                                        hist.FinPTDCuryAmount  += item.FinPTDCuryAmount.GetValueOrDefault();
                                        hist.FinPTDAmount      += item.FinPTDAmount.GetValueOrDefault();
                                        hist.FinYTDCuryAmount  += item.FinYTDCuryAmount.GetValueOrDefault();
                                        hist.FinYTDAmount      += item.FinYTDAmount.GetValueOrDefault();
                                        hist.FinPTDQty         += item.FinPTDQty.GetValueOrDefault();
                                        hist.FinYTDQty         += item.FinYTDQty.GetValueOrDefault();
                                        hist.TranPTDCuryAmount += item.TranPTDCuryAmount.GetValueOrDefault();
                                        hist.TranPTDAmount     += item.TranPTDAmount.GetValueOrDefault();
                                        hist.TranYTDCuryAmount += item.TranYTDCuryAmount.GetValueOrDefault();
                                        hist.TranYTDAmount     += item.TranYTDAmount.GetValueOrDefault();
                                        hist.TranPTDQty        += item.TranPTDQty.GetValueOrDefault();
                                        hist.TranYTDQty        += item.TranYTDQty.GetValueOrDefault();
                                    }
                                }
                            }
                        }

                        AddToUnbilledSummary(je, t.Tran);

                        t.Tran.Released = true;
                        je.Caches[typeof(PMTran)].Update(t.Tran);

                        sourceForAllocation.Add(t.Tran);
                        if (t.Tran.Allocated != true && t.Tran.ExcludedFromAllocation != true && t.Project.AutoAllocate == true)
                        {
                            if (!tasksToAutoAllocate.ContainsKey(string.Format("{0}.{1}", t.Task.ProjectID, t.Task.TaskID)))
                            {
                                tasksToAutoAllocate.Add(string.Format("{0}.{1}", t.Task.ProjectID, t.Task.TaskID), t.Task);
                            }
                        }
                    }

                    if (tranAdded)
                    {
                        je.Save.Press();
                        batches.Add(je.BatchModule.Current);
                    }
                    else
                    {
                        je.Persist(typeof(PMTran), PXDBOperation.Update);
                        je.Persist(typeof(PMBudgetAccum), PXDBOperation.Insert);
                        je.Persist(typeof(PMForecastHistoryAccum), PXDBOperation.Insert);
                        je.Persist(typeof(PMTaskTotal), PXDBOperation.Insert);
                        je.Persist(typeof(PMTaskAllocTotalAccum), PXDBOperation.Insert);
                        je.Persist(typeof(PMHistoryAccum), PXDBOperation.Insert);                        //only non-gl balance is updated
                        je.Persist(typeof(PMUnbilledDailySummaryAccum), PXDBOperation.Insert);
                        je.SelectTimeStamp();
                    }
                }

                allocTasks.AddRange(tasksToAutoAllocate.Values);

                doc.Released = true;
                doc.Status   = PMRegister.status.Released;
                je.Caches[typeof(PMRegister)].Update(doc);

                je.Persist(typeof(PMTran), PXDBOperation.Update);
                je.Persist(typeof(PMRegister), PXDBOperation.Update);
                je.Persist(typeof(PMBudgetAccum), PXDBOperation.Insert);
                je.Persist(typeof(PMForecastHistoryAccum), PXDBOperation.Insert);
                je.Persist(typeof(PMTaskAllocTotalAccum), PXDBOperation.Insert);
                je.Persist(typeof(PMTaskTotal), PXDBOperation.Insert);


                ts.Complete();
            }

            return(batches);
        }
Ejemplo n.º 17
0
        public List <Batch> Release(JournalEntry je, PMRegister doc, out List <PMTask> allocTasks)
        {
            allocTasks = new List <PMTask>();

            List <Batch> batches = new List <Batch>();
            Dictionary <string, PMTask> tasksToAutoAllocate = new Dictionary <string, PMTask>();
            List <PMTran> sourceForAllocation = new List <PMTran>();
            Dictionary <string, List <TranInfo> > transByFinPeriod = GetTransByBranchAndFinPeriod(doc);

            Debug.Assert(transByFinPeriod.Count > 0, "Failed to select transactions by finperiod in PMRegister Release.");

            using (var ts = new PXTransactionScope())
            {
                foreach (KeyValuePair <string, List <TranInfo> > kv in transByFinPeriod)
                {
                    string[] parts    = kv.Key.Split('.');
                    int?     branchID = parts[0] == "0" ? null : (int?)int.Parse(parts[0]);

                    je.Clear(PXClearOption.ClearAll);

                    Batch newbatch = new Batch();
                    newbatch.Module      = doc.Module;
                    newbatch.Status      = BatchStatus.Unposted;
                    newbatch.Released    = true;
                    newbatch.Hold        = false;
                    newbatch.BranchID    = branchID;
                    newbatch.FinPeriodID = parts[1];
                    newbatch.Description = doc.Description;
                    je.BatchModule.Insert(newbatch);

                    bool tranAdded = false;
                    foreach (TranInfo t in kv.Value)
                    {
                        bool isGL = false;

                        if (t.Tran.Released != true && t.Tran.IsNonGL != true && t.Project.BaseType == PMProject.ProjectBaseType.Project &&
                            !string.IsNullOrEmpty(t.AccountGroup.Type) && t.AccountGroup.Type != PMAccountType.OffBalance && !ProjectDefaultAttribute.IsNonProject(this, t.Tran.ProjectID))
                        {
                            GLTran tran1 = new GLTran();
                            tran1.TranDate      = t.Tran.TranDate;
                            tran1.TranPeriodID  = t.Tran.TranPeriodID;
                            tran1.SummPost      = false;
                            tran1.BranchID      = t.Tran.BranchID;
                            tran1.PMTranID      = t.Tran.TranID;
                            tran1.ProjectID     = t.Tran.ProjectID;
                            tran1.TaskID        = t.Tran.TaskID;
                            tran1.TranDesc      = t.Tran.Description;
                            tran1.ReferenceID   = t.Tran.BAccountID;
                            tran1.InventoryID   = t.Tran.InventoryID == PMProjectStatus.EmptyInventoryID ? null : t.Tran.InventoryID;
                            tran1.Qty           = t.Tran.Qty;
                            tran1.UOM           = t.Tran.UOM;
                            tran1.TranType      = t.Tran.TranType;
                            tran1.CuryCreditAmt = 0;
                            tran1.CreditAmt     = 0;
                            tran1.CuryDebitAmt  = t.Tran.Amount;
                            tran1.DebitAmt      = t.Tran.Amount;
                            tran1.AccountID     = t.Tran.AccountID;
                            tran1.SubID         = t.Tran.SubID;
                            tran1.Released      = true;
                            je.GLTranModuleBatNbr.Insert(tran1);

                            GLTran tran2 = new GLTran();
                            tran2.TranDate      = t.Tran.TranDate;
                            tran2.TranPeriodID  = t.Tran.TranPeriodID;
                            tran2.SummPost      = false;
                            tran2.BranchID      = t.Tran.BranchID;
                            tran2.PMTranID      = t.Tran.TranID;
                            tran2.ProjectID     = t.OffsetAccountGroup.GroupID != null ? t.Tran.ProjectID : ProjectDefaultAttribute.NonProject(this);
                            tran2.TaskID        = t.OffsetAccountGroup.GroupID != null ? t.Tran.TaskID : null;
                            tran2.TranDesc      = t.Tran.Description;
                            tran2.ReferenceID   = t.Tran.BAccountID;
                            tran2.InventoryID   = t.Tran.InventoryID == PMProjectStatus.EmptyInventoryID ? null : t.Tran.InventoryID;
                            tran2.Qty           = t.Tran.Qty;
                            tran2.UOM           = t.Tran.UOM;
                            tran2.TranType      = t.Tran.TranType;
                            tran2.CuryCreditAmt = t.Tran.Amount;
                            tran2.CreditAmt     = t.Tran.Amount;
                            tran2.CuryDebitAmt  = 0;
                            tran2.DebitAmt      = 0;
                            tran2.AccountID     = t.Tran.OffsetAccountID;
                            tran2.SubID         = t.Tran.OffsetSubID;
                            tran2.Released      = true;
                            je.GLTranModuleBatNbr.Insert(tran2);

                            tranAdded       = true;
                            isGL            = true;
                            t.Tran.BatchNbr = je.BatchModule.Current.BatchNbr;
                        }

                        if (!isGL)
                        {
                            if (t.Tran.AccountGroupID == null && t.Project.BaseType == PMProject.ProjectBaseType.Project && t.Project.NonProject != true)
                            {
                                throw new PXException(Messages.AccountGroupIsRequired, doc.RefNbr);
                            }
                        }

                        IList <PMHistory> historyList = UpdateProjectBalance(je, t.Tran, t.Account, t.AccountGroup, t.OffsetAccount, t.OffsetAccountGroup);
                        if (!isGL)
                        {
                            #region History Update

                            foreach (PMHistory item in historyList)
                            {
                                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 = (PMHistoryAccum)je.Caches[typeof(PMHistoryAccum)].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
                        }

                        AddToUnbilledSummary(je, t.Tran);

                        t.Tran.Released = true;
                        je.Caches[typeof(PMTran)].Update(t.Tran);

                        sourceForAllocation.Add(t.Tran);
                        if (t.Tran.Allocated != true && t.Project.AutoAllocate == true)
                        {
                            if (!tasksToAutoAllocate.ContainsKey(string.Format("{0}.{1}", t.Task.ProjectID, t.Task.TaskID)))
                            {
                                tasksToAutoAllocate.Add(string.Format("{0}.{1}", t.Task.ProjectID, t.Task.TaskID), t.Task);
                            }
                        }
                    }

                    if (tranAdded)
                    {
                        je.Persist(typeof(PMHistoryAccum), PXDBOperation.Insert);                        //only non-gl balance is updated
                        je.Save.Press();
                        batches.Add(je.BatchModule.Current);
                    }
                    else
                    {
                        je.Persist(typeof(PMTran), PXDBOperation.Update);
                        je.Persist(typeof(PMProjectStatusAccum), PXDBOperation.Insert);
                        je.Persist(typeof(PMTaskTotal), PXDBOperation.Insert);
                        je.Persist(typeof(PMHistoryAccum), PXDBOperation.Insert);                        //only non-gl balance is updated
                        je.Persist(typeof(PMUnbilledDailySummaryAccum), PXDBOperation.Insert);
                        je.SelectTimeStamp();
                    }
                }

                allocTasks.AddRange(tasksToAutoAllocate.Values);

                doc.Released = true;
                je.Caches[typeof(PMRegister)].Update(doc);

                je.Persist(typeof(PMTran), PXDBOperation.Update);
                je.Persist(typeof(PMRegister), PXDBOperation.Update);
                je.Persist(typeof(PMProjectStatusAccum), PXDBOperation.Insert);
                je.Persist(typeof(PMTaskAllocTotalAccum), PXDBOperation.Insert);
                je.Persist(typeof(PMTaskTotal), PXDBOperation.Insert);


                ts.Complete();
            }

            return(batches);
        }
Ejemplo n.º 18
0
        private void SetReclassifyButtonState(Batch batch)
        {
            var enabled = Ledger != null && JournalEntry.IsBatchReclassifiable(batch, Ledger);

            if (enabled)
            {
                var trans = JournalEntry.GLTranModuleBatNbr.Select().RowCast <GLTran>();

                enabled = trans.Any(tran => JournalEntry.IsTransactionReclassifiable(tran, batch.BatchType, Ledger.BalanceType, ProjectDefaultAttribute.NonProject(JournalEntry)));
            }

            JournalEntry.reclassify.SetEnabled(enabled);
        }
Ejemplo n.º 19
0
        private void SetReclassifyButtonState(Batch batch)
        {
            if (JournalEntry.UnattendedMode)
            {
                // AC-89516 - the flag is used as a proxy for graph not being worked with
                // from the UI. The reasoning behind this is that on databases with many GL
                // transactions the below select of GLTrans takes up a considerable amount of
                // time during mass AR documents release.
                // TODO: perhaps all UI state controlling should be disabled in unattended mode,
                // but we were afraid of regression at the moment.
                // -
                return;
            }

            var enabled = Ledger != null && JournalEntry.IsBatchReclassifiable(batch, Ledger);

            if (enabled)
            {
                var trans = JournalEntry.GLTranModuleBatNbr.Select().RowCast <GLTran>();

                enabled = trans.Any(tran => JournalEntry.IsTransactionReclassifiable(tran, batch.BatchType, Ledger.BalanceType, ProjectDefaultAttribute.NonProject()));
            }

            JournalEntry.reclassify.SetEnabled(enabled);
        }
Ejemplo n.º 20
0
        protected virtual void EPExpenseClaimDetails_ExpenseAccountID_FieldVerifying(PXCache sender, PXFieldVerifyingEventArgs e)
        {
            EPExpenseClaimDetails row = e.Row as EPExpenseClaimDetails;

            if (row != null && row.ContractID != null)
            {
                Contract contract = PXSelect <Contract> .Search <Contract.contractID>(this, row.ContractID);

                if (contract != null && contract.BaseType == PMProject.ProjectBaseType.Project && !ProjectDefaultAttribute.IsNonProject(this, row.ContractID))
                {
                    Account account = PXSelect <Account> .Search <Account.accountID>(this, row.ExpenseAccountID);

                    if (account.AccountGroupID == null)
                    {
                        sender.RaiseExceptionHandling <EPExpenseClaimDetails.expenseAccountID>(e.Row, account.AccountCD,
                                                                                               new PXSetPropertyException(Messages.AccountGroupIsNotAssignedForAccount, account.AccountCD.Trim(), PXErrorLevel.Error));
                    }
                }
            }
        }
Ejemplo n.º 21
0
 private PMProject GetProject(int?projectId)
 {
     ProjectDefaultAttribute.IsProject(Base, projectId, out var project);
     return(project);
 }
Ejemplo n.º 22
0
        public static void ReleaseDoc(EPExpenseClaim claim)
        {
            #region prepare required variables
            APInvoiceEntry    docgraph          = PXGraph.CreateInstance <APInvoiceEntry>();
            ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>();


            var receipts = PXSelect <EPExpenseClaimDetails,
                                     Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr).Select(
                result => (EPExpenseClaimDetails)result).GroupBy(
                item => Tuple.Create(
                    item.TaxZoneID,
                    item.TaxCalcMode
                    )).ToDictionary(x => x.Key, group => group.ToList());

            if (receipts.Count() == 0)
            {
                receipts.Add(Tuple.Create(claim.TaxZoneID, claim.TaxCalcMode), new List <EPExpenseClaimDetails>());
            }
            EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph);

            APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph);

            EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID);

            Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID);

            List <APRegister> doclist = new List <APRegister>();
            expenseClaimGraph.SelectTimeStamp();
            #endregion

            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (var res in receipts)
                {
                    docgraph.Clear(PXClearOption.ClearAll);
                    docgraph.SelectTimeStamp();
                    docgraph.vendor.Current   = employee;
                    docgraph.location.Current = emplocation;

                    CurrencyInfo infoOriginal = PXSelect <CurrencyInfo,
                                                          Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID);

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

                    info.CuryInfoID = null;
                    info            = docgraph.currencyinfo.Insert(info);
                    #region CreateInoiceHeader
                    APInvoice invoice = new APInvoice();


                    bool reversedDocument = false;
                    if (res.Value.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0)
                    {
                        invoice.DocType  = APInvoiceType.DebitAdj;
                        reversedDocument = true;
                    }
                    else
                    {
                        invoice.DocType = APInvoiceType.Invoice;
                    }
                    decimal signOperation;
                    if (reversedDocument)
                    {
                        signOperation = -1;
                    }
                    else
                    {
                        signOperation = 1;
                    }

                    invoice.CuryInfoID = info.CuryInfoID;

                    invoice.Hold     = true;
                    invoice.Released = false;
                    invoice.Printed  = false;
                    invoice.OpenDoc  = true;

                    invoice.DocDate          = claim.DocDate;
                    invoice.FinPeriodID      = claim.FinPeriodID;
                    invoice.InvoiceNbr       = claim.RefNbr;
                    invoice.DocDesc          = claim.DocDesc;
                    invoice.VendorID         = claim.EmployeeID;
                    invoice.CuryID           = info.CuryID;
                    invoice.VendorLocationID = claim.LocationID;
                    invoice.APAccountID      = emplocation != null ? emplocation.APAccountID : null;
                    invoice.APSubID          = emplocation != null ? emplocation.APSubID : null;
                    invoice.TaxZoneID        = res.Key.Item1;
                    invoice.TaxCalcMode      = res.Key.Item2;
                    invoice.BranchID         = claim.BranchID;
                    invoice.OrigModule       = BatchModule.EP;
                    invoice.OrigRefNbr       = claim.RefNbr;

                    invoice = docgraph.Document.Insert(invoice);

                    PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal);

                    info.CuryInfoID = invoice.CuryInfoID;

                    PXCache claimcache       = docgraph.Caches[typeof(EPExpenseClaim)];
                    PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)];

                    PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, docgraph.Document.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>());
                    #endregion
                    TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
                    decimal?claimCuryTaxRoundDiff = 0m;
                    decimal?claimTaxRoundDiff     = 0m;
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        #region AddDetails

                        decimal tipQty;
                        if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0)
                        {
                            tipQty = 1;
                        }
                        else
                        {
                            tipQty = -1;
                        }
                        Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID);

                        if (claimdetail.TaskID != null)
                        {
                            PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID);

                            if (task != null && !(bool)task.VisibleInAP)
                            {
                                throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP);
                            }
                        }

                        APTran tran = new APTran();
                        tran.InventoryID = claimdetail.InventoryID;
                        tran.TranDesc    = claimdetail.TranDesc;
                        decimal unitCost;
                        decimal amount;
                        decimal taxableAmt;
                        decimal taxAmt;
                        if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                        {
                            unitCost   = claimdetail.CuryUnitCost ?? 0m;
                            amount     = claimdetail.CuryTaxableAmt ?? 0m;
                            taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m;
                            taxAmt     = claimdetail.CuryTaxAmt ?? 0m;
                        }
                        else
                        {
                            if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m)
                            {
                                unitCost = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost);
                            }
                            if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m)
                            {
                                amount = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount);
                            }
                            if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m)
                            {
                                taxableAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt);
                            }
                            if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m)
                            {
                                taxAmt = 0m;
                            }
                            else
                            {
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt);
                            }
                        }

                        tran.ManualPrice       = true;
                        tran.CuryUnitCost      = unitCost;
                        tran.Qty               = claimdetail.Qty * signOperation;
                        tran.UOM               = claimdetail.UOM;
                        tran.NonBillable       = claimdetail.Billable != true;
                        claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation;
                        claimTaxRoundDiff     += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation;
                        tran.Date              = claimdetail.ExpenseDate;

                        if (contract.BaseType == PMProject.ProjectBaseType.Project)
                        {
                            tran.ProjectID = claimdetail.ContractID;
                        }
                        else
                        {
                            tran.ProjectID = ProjectDefaultAttribute.NonProject();
                        }

                        tran.TaskID        = claimdetail.TaskID;
                        tran.CostCodeID    = claimdetail.CostCodeID;
                        tran.AccountID     = claimdetail.ExpenseAccountID;
                        tran.SubID         = claimdetail.ExpenseSubID;
                        tran.TaxCategoryID = claimdetail.TaxCategoryID;
                        tran.BranchID      = claimdetail.BranchID;
                        tran                = docgraph.Transactions.Insert(tran);
                        tran.CuryLineAmt    = amount * signOperation;
                        tran.CuryTaxAmt     = 0;
                        tran.CuryTaxableAmt = taxableAmt * signOperation;
                        tran.CuryTaxAmt     = taxAmt * signOperation;
                        tran                = docgraph.Transactions.Update(tran);


                        if ((claimdetail.CuryTipAmt ?? 0) != 0)
                        {
                            APTran tranTip = new APTran();
                            if (epsetup.NonTaxableTipItem == null)
                            {
                                throw new PXException(Messages.TipItemIsNotDefined);
                            }
                            IN.InventoryItem tipItem = PXSelect <IN.InventoryItem,
                                                                 Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem);

                            if (tipItem == null)
                            {
                                string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]);
                                throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem);
                            }
                            tranTip.InventoryID = epsetup.NonTaxableTipItem;
                            tranTip.TranDesc    = tipItem.Descr;
                            if (EPClaimReceiptController.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID))
                            {
                                tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m);
                                tranTip.CuryTranAmt  = claimdetail.CuryTipAmt * signOperation;
                            }
                            else
                            {
                                decimal tipAmt;
                                PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt);
                                tranTip.CuryUnitCost = Math.Abs(tipAmt);
                                tranTip.CuryTranAmt  = tipAmt * signOperation;
                            }
                            tranTip.Qty         = tipQty;
                            tranTip.UOM         = tipItem.BaseUnit;
                            tranTip.NonBillable = claimdetail.Billable != true;
                            tranTip.Date        = claimdetail.ExpenseDate;

                            tranTip.BranchID = claimdetail.BranchID;
                            tranTip          = docgraph.Transactions.Insert(tranTip);

                            if (epsetup.UseReceiptAccountForTips == true)
                            {
                                tranTip.AccountID = claimdetail.ExpenseAccountID;
                                tranTip.SubID     = claimdetail.ExpenseSubID;
                            }
                            else
                            {
                                tranTip.AccountID = tipItem.COGSAcctID;
                                Location companyloc = (Location)PXSelectJoin <Location,
                                                                              InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>,
                                                                                                        And <Location.locationID, Equal <BAccountR.defLocationID> > >,
                                                                                         InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >,
                                                                              Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph);

                                PMTask task = PXSelect <PMTask,
                                                        Where <PMTask.projectID, Equal <Required <PMTask.projectID> >,
                                                               And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID);

                                Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail);

                                int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee);
                                int?item_SubID     = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem);
                                int?company_SubID  = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc);
                                int?project_SubID  = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract);
                                int?task_SubID     = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task);
                                int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation);

                                object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask,
                                                                                                        new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID },
                                                                                                        new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) });

                                docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value);
                                tranTip.SubID = (int?)value;
                            }
                            tranTip = docgraph.Transactions.Update(tranTip);
                            tranTip.TaxCategoryID = tipItem.TaxCategoryID;
                            tranTip.ProjectID     = tran.ProjectID;
                            tranTip.TaskID        = tran.TaskID;
                            tranTip = AddTaxes(docgraph, invoice, signOperation, claimdetail, tranTip, true);
                            tranTip = docgraph.Transactions.Update(tranTip);
                        }

                        PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, docgraph.Transactions.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>());
                        claimdetail.Released = true;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                        #endregion


                        tran = AddTaxes(docgraph, invoice, signOperation, claimdetail, tran, false);
                    }

                    #region legacy taxes
                    foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate,
                                                                     Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr))
                    {
                        #region Add taxes
                        APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(tax.TaxID);

                        if (new_aptax == null)
                        {
                            new_aptax       = new APTaxTran();
                            new_aptax.TaxID = tax.TaxID;
                            new_aptax       = docgraph.Taxes.Insert(new_aptax);
                            if (new_aptax != null)
                            {
                                new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                                new_aptax.CuryTaxableAmt = 0m;
                                new_aptax.CuryTaxAmt     = 0m;
                                new_aptax.CuryExpenseAmt = 0m;
                                new_aptax = docgraph.Taxes.Update(new_aptax);
                            }
                        }

                        if (new_aptax != null)
                        {
                            new_aptax = PXCache <APTaxTran> .CreateCopy(new_aptax);

                            new_aptax.TaxRate        = tax.TaxRate;
                            new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation;
                            new_aptax.CuryTaxAmt     = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation;
                            new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation;
                            new_aptax = docgraph.Taxes.Update(new_aptax);
                        }
                        #endregion
                    }
                    #endregion

                    invoice.CuryOrigDocAmt = invoice.CuryDocBal;
                    invoice.CuryTaxAmt     = invoice.CuryTaxTotal;
                    invoice.Hold           = false;
                    docgraph.Document.Update(invoice);
                    invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff;
                    invoice.TaxRoundDiff     = invoice.RoundDiff = claimTaxRoundDiff;
                    bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                                         On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                                   Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                                          And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                               And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > >
                                     .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0;

                    if ((invoice.TaxCalcMode == TaxCalculationMode.Gross &&
                         PXSelectJoin <APTaxTran, InnerJoin <Tax,
                                                             On <APTaxTran.taxID, Equal <Tax.taxID> > >,
                                       Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >,
                                              And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >,
                                                   And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > >
                         .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) ||
                        inclusive)
                    {
                        decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                        decimal additionalDiff     = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m);
                        foreach (APTran line in docgraph.Transactions.Select())
                        {
                            curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m);
                            additionalDiff     += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m);
                        }

                        invoice.CuryTaxRoundDiff += curyAdditionalDiff;
                        invoice.TaxRoundDiff     += additionalDiff;
                    }

                    docgraph.Document.Update(invoice);
                    docgraph.Save.Press();
                    foreach (EPExpenseClaimDetails claimdetail in res.Value)
                    {
                        claimdetail.APDocType = invoice.DocType;
                        claimdetail.APRefNbr  = invoice.RefNbr;
                        expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail);
                    }
                    claim.Status   = EPExpenseClaimStatus.ReleasedStatus;
                    claim.Released = true;
                    expenseClaimGraph.ExpenseClaim.Update(claim);

                    #region EP History Update
                    EPHistory hist = new EPHistory();
                    hist.EmployeeID  = invoice.VendorID;
                    hist.FinPeriodID = invoice.FinPeriodID;
                    hist             = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist);

                    hist.FinPtdClaimed += invoice.DocBal;
                    hist.FinYtdClaimed += invoice.DocBal;
                    if (invoice.FinPeriodID == invoice.TranPeriodID)
                    {
                        hist.TranPtdClaimed += invoice.DocBal;
                        hist.TranYtdClaimed += invoice.DocBal;
                    }
                    else
                    {
                        EPHistory tranhist = new EPHistory();
                        tranhist.EmployeeID      = invoice.VendorID;
                        tranhist.FinPeriodID     = invoice.TranPeriodID;
                        tranhist                 = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist);
                        tranhist.TranPtdClaimed += invoice.DocBal;
                        tranhist.TranYtdClaimed += invoice.DocBal;
                    }
                    expenseClaimGraph.Views.Caches.Add(typeof(EPHistory));
                    #endregion

                    expenseClaimGraph.Save.Press();

                    doclist.Add(docgraph.Document.Current);
                }

                ts.Complete();
            }

            if ((bool)epsetup.AutomaticReleaseAP == true)
            {
                APDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Ejemplo n.º 23
0
        public virtual void Bill(CustomersList customer, PX.Objects.EP.EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

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

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

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

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

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

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

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

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

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

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

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

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

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

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

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Ejemplo n.º 24
0
        public static PXRedirectRequiredException CreatePOOrders2(
            System.Collections.Generic.List <POFixedDemand> list,
            DateTime?PurchDate,
            bool extSort)
        {
            POOrderEntry docgraph = PXGraph.CreateInstance <POOrderEntry>();

            docgraph.Views.Caches.Add(typeof(POOrderEntry.SOLineSplit3));
            POSetup current = docgraph.POSetup.Current;
            DocumentList <POOrder> documentList1 = new DocumentList <POOrder>((PXGraph)docgraph);
            Dictionary <string, DocumentList <POLine> > dictionary = new Dictionary <string, DocumentList <POLine> >();

            list.Sort((Comparison <POFixedDemand>)((a, b) =>
            {
                string empty1 = string.Empty;
                string empty2 = string.Empty;
                string str;
                if (a.PlanType == "90")
                {
                    PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, a.InventoryID);
                    str = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD);
                }
                else
                {
                    POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)a.PlanID);
                    str = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault());
                }
                string strB;
                if (b.PlanType == "90")
                {
                    PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, b.InventoryID);
                    strB = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD);
                }
                else
                {
                    POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)b.PlanID);
                    strB = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault());
                }
                return(str.CompareTo(strB));
            }));
            POOrder poOrder1 = (POOrder)null;
            bool    flag1    = false;

            foreach (POFixedDemand demand in list)
            {
                if (!(demand.FixedSource != "P"))
                {
                    string OrderType = demand.PlanType == "6D" ? "DP" : (demand.PlanType == "6E" ? "DP" : "RO");
                    string str1      = (string)null;
                    int?   nullable1 = demand.VendorID;
                    int    num1;
                    if (nullable1.HasValue)
                    {
                        nullable1 = demand.VendorLocationID;
                        num1      = !nullable1.HasValue ? 1 : 0;
                    }
                    else
                    {
                        num1 = 1;
                    }
                    if (num1 != 0)
                    {
                        PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), "Vendor and vendor location should be defined.");
                    }
                    else
                    {
                        PXErrorLevel pxErrorLevel = PXErrorLevel.RowInfo;
                        string       empty        = string.Empty;
                        try
                        {
                            PX.Objects.SO.SOOrder soOrder = (PX.Objects.SO.SOOrder) PXSelectBase <PX.Objects.SO.SOOrder, PXSelect <PX.Objects.SO.SOOrder, Where <PX.Objects.SO.SOOrder.noteID, Equal <Required <PX.Objects.SO.SOOrder.noteID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.RefNoteID);

                            POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3) PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.PlanID);

                            string str2 = (string)null;
                            string str3 = (string)null;
                            if (demand.PlanType == "6B" || demand.PlanType == "6E")
                            {
                                str2 = soLineSplit3.POType;
                                str3 = soLineSplit3.PONbr;
                            }
                            System.Collections.Generic.List <FieldLookup> fieldLookupList1 = new System.Collections.Generic.List <FieldLookup>()
                            {
                                (FieldLookup) new FieldLookup <POOrder.orderType>((object)OrderType),
                                (FieldLookup) new FieldLookup <POOrder.vendorID>((object)demand.VendorID),
                                (FieldLookup) new FieldLookup <POOrder.vendorLocationID>((object)demand.VendorLocationID),
                                (FieldLookup) new FieldLookup <POOrder.bLOrderNbr>((object)str3)
                            };
                            if (OrderType == "RO")
                            {
                                bool?projectPerDocument = docgraph.apsetup.Current.RequireSingleProjectPerDocument;
                                bool flag2 = true;
                                if (projectPerDocument.GetValueOrDefault() == flag2 & projectPerDocument.HasValue)
                                {
                                    nullable1 = demand.ProjectID;
                                    int?nullable2 = nullable1.HasValue ? nullable1 : ProjectDefaultAttribute.NonProject();
                                    fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.projectID>((object)nullable2));
                                }
                                int num2;
                                if (poOrder1 != null && poOrder1.ShipDestType == "L")
                                {
                                    nullable1 = poOrder1.SiteID;
                                    num2      = !nullable1.HasValue ? 1 : 0;
                                }
                                else
                                {
                                    num2 = 0;
                                }
                                if (num2 == 0)
                                {
                                    fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID));
                                }
                            }
                            else if (OrderType == "DP")
                            {
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderType>((object)soLineSplit3.OrderType));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderNbr>((object)soLineSplit3.OrderNbr));
                            }
                            else
                            {
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToBAccountID>((object)soOrder.CustomerID));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToLocationID>((object)soOrder.CustomerLocationID));
                                fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID));
                            }
                            poOrder1 = documentList1.Find(fieldLookupList1.ToArray()) ?? new POOrder();
                            if (poOrder1.OrderNbr == null)
                            {
                                docgraph.Clear();
                                poOrder1.OrderType = OrderType;
                                poOrder1           = PXCache <POOrder> .CreateCopy(docgraph.Document.Insert(poOrder1));

                                poOrder1.VendorID         = demand.VendorID;
                                poOrder1.VendorLocationID = demand.VendorLocationID;
                                poOrder1.SiteID           = demand.POSiteID;
                                nullable1 = demand.ProjectID;
                                if (nullable1.HasValue)
                                {
                                    poOrder1.ProjectID = demand.ProjectID;
                                }
                                poOrder1.OrderDate  = PurchDate;
                                poOrder1.BLType     = str2;
                                poOrder1.BLOrderNbr = str3;
                                if (OrderType == "DP" | extSort)
                                {
                                    poOrder1.SOOrderType = soLineSplit3.OrderType;
                                    poOrder1.SOOrderNbr  = soLineSplit3.OrderNbr;
                                }
                                if (!string.IsNullOrEmpty(poOrder1.BLOrderNbr))
                                {
                                    POOrder poOrder2 = (POOrder)PXSelectBase <POOrder, PXSelect <POOrder, Where <POOrder.orderType, Equal <Current <POOrder.bLType> >, And <POOrder.orderNbr, Equal <Current <POOrder.bLOrderNbr> > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                    {
                                        (object)poOrder1
                                    });

                                    if (poOrder2 != null)
                                    {
                                        poOrder1.VendorRefNbr = poOrder2.VendorRefNbr;
                                    }
                                }
                                if (OrderType == "DP")
                                {
                                    poOrder1.ShipDestType     = "C";
                                    poOrder1.ShipToBAccountID = soOrder.CustomerID;
                                    poOrder1.ShipToLocationID = soOrder.CustomerLocationID;
                                }
                                else if (current.ShipDestType == "S")
                                {
                                    poOrder1.ShipDestType = "S";
                                    poOrder1.SiteID       = demand.POSiteID;
                                }
                                if (PXAccess.FeatureInstalled <PX.Objects.CS.FeaturesSet.multicurrency>())
                                {
                                    docgraph.currencyinfo.Current.CuryID = (string)null;
                                }
                                poOrder1 = docgraph.Document.Update(poOrder1);
                                if (OrderType == "DP")
                                {
                                    SOAddress soAddress = (SOAddress)PXSelectBase <SOAddress, PXSelect <SOAddress, Where <SOAddress.addressID, Equal <Required <PX.Objects.SO.SOOrder.shipAddressID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipAddressID);

                                    bool?isDefaultAddress = soAddress.IsDefaultAddress;
                                    bool flag2            = false;
                                    if (isDefaultAddress.GetValueOrDefault() == flag2 & isDefaultAddress.HasValue)
                                    {
                                        SharedRecordAttribute.CopyRecord <POOrder.shipAddressID>(docgraph.Document.Cache, (object)poOrder1, (object)soAddress, true);
                                    }
                                    SOContact soContact = (SOContact)PXSelectBase <SOContact, PXSelect <SOContact, Where <SOContact.contactID, Equal <Required <PX.Objects.SO.SOOrder.shipContactID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipContactID);

                                    bool?isDefaultContact = soContact.IsDefaultContact;
                                    bool flag3            = false;
                                    if (isDefaultContact.GetValueOrDefault() == flag3 & isDefaultContact.HasValue)
                                    {
                                        SharedRecordAttribute.CopyRecord <POOrder.shipContactID>(docgraph.Document.Cache, (object)poOrder1, (object)soContact, true);
                                    }
                                    DateTime?expectedDate = poOrder1.ExpectedDate;
                                    DateTime?requestDate  = soOrder.RequestDate;
                                    if (expectedDate.HasValue & requestDate.HasValue && expectedDate.GetValueOrDefault() < requestDate.GetValueOrDefault())
                                    {
                                        poOrder1 = PXCache <POOrder> .CreateCopy(poOrder1);

                                        poOrder1.ExpectedDate = soOrder.RequestDate;
                                        poOrder1 = docgraph.Document.Update(poOrder1);
                                    }
                                }
                            }
                            else if (!docgraph.Document.Cache.ObjectsEqual((object)docgraph.Document.Current, (object)poOrder1))
                            {
                                docgraph.Document.Current = (POOrder)docgraph.Document.Search <POOrder.orderNbr>((object)poOrder1.OrderNbr, (object)poOrder1.OrderType);
                            }
                            poOrder1.UpdateVendorCost = new bool?(false);
                            POLine poLine1 = (POLine)null;
                            DocumentList <POLine> documentList2;
                            if (!dictionary.TryGetValue(demand.PlanType, out documentList2))
                            {
                                documentList2 = dictionary[demand.PlanType] = new DocumentList <POLine>((PXGraph)docgraph);
                            }
                            if (OrderType == "RO" && demand.PlanType != "6B")
                            {
                                System.Collections.Generic.List <FieldLookup> fieldLookupList2 = new System.Collections.Generic.List <FieldLookup>();
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorID>((object)demand.VendorID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorLocationID>((object)demand.VendorLocationID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.siteID>((object)demand.POSiteID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.inventoryID>((object)demand.InventoryID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.subItemID>((object)demand.SubItemID));
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.requestedDate>((object)(DateTime?)soLineSplit3?.ShipDate));
                                int?nullable2;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable2 = nullable1;
                                }
                                else
                                {
                                    nullable2 = soLineSplit3.ProjectID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.projectID>((object)nullable2));
                                int?nullable3;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable3 = nullable1;
                                }
                                else
                                {
                                    nullable3 = soLineSplit3.TaskID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.taskID>((object)nullable3));
                                int?nullable4;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable4 = nullable1;
                                }
                                else
                                {
                                    nullable4 = soLineSplit3.CostCodeID;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.costCodeID>((object)nullable4));
                                int?nullable5;
                                if (soLineSplit3 == null)
                                {
                                    nullable1 = new int?();
                                    nullable5 = nullable1;
                                }
                                else
                                {
                                    nullable5 = soLineSplit3.LineNbr;
                                }
                                fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.lineNbr>((object)nullable5));
                                System.Collections.Generic.List <FieldLookup> fieldLookupList3 = fieldLookupList2;
                                bool?nullable6 = current.CopyLineDescrSO;
                                bool flag2     = true;
                                if (nullable6.GetValueOrDefault() == flag2 & nullable6.HasValue && soLineSplit3 != null)
                                {
                                    fieldLookupList3.Add((FieldLookup) new FieldLookup <POLine.tranDesc>((object)soLineSplit3.TranDesc));
                                    poLine1 = documentList2.Find(fieldLookupList3.ToArray());
                                    int num2;
                                    if (poLine1 != null)
                                    {
                                        nullable6 = current.CopyLineNoteSO;
                                        bool flag3 = true;
                                        if (nullable6.GetValueOrDefault() == flag3 & nullable6.HasValue)
                                        {
                                            num2 = PXNoteAttribute.GetNote(docgraph.Caches[typeof(POLine)], (object)poLine1) != null ? 1 : (PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3) != null ? 1 : 0);
                                            goto label_67;
                                        }
                                    }
                                    num2 = 0;
label_67:
                                    if (num2 != 0)
                                    {
                                        poLine1 = (POLine)null;
                                    }
                                }
                                else
                                {
                                    poLine1 = documentList2.Find(fieldLookupList3.ToArray());
                                }
                            }
                            POLine dest = poLine1 ?? new POLine();
                            POLine copy1;
                            if (dest.OrderNbr == null)
                            {
                                docgraph.FillPOLineFromDemand(dest, demand, OrderType, soLineSplit3);
                                POLine line           = docgraph.Transactions.Insert(dest);
                                bool?  copyLineNoteSo = current.CopyLineNoteSO;
                                bool   flag2          = true;
                                if (copyLineNoteSo.GetValueOrDefault() == flag2 & copyLineNoteSo.HasValue && soLineSplit3 != null)
                                {
                                    PXNoteAttribute.SetNote(docgraph.Transactions.Cache, (object)line, PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3));
                                }
                                if (docgraph.onCopyPOLineFields != null)
                                {
                                    docgraph.onCopyPOLineFields(demand, line);
                                }
                                copy1 = PXCache <POLine> .CreateCopy(line);

                                documentList2.Add(copy1);
                            }
                            else
                            {
                                copy1 = PXCache <POLine> .CreateCopy((POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POOrder.orderType> >, And <POLine.orderNbr, Equal <Current <POOrder.orderNbr> >, And <POLine.lineNbr, Equal <Current <POLine.lineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                {
                                    (object)dest
                                }));

                                POLine  poLine2   = copy1;
                                Decimal?orderQty1 = poLine2.OrderQty;
                                Decimal?orderQty2 = demand.OrderQty;
                                poLine2.OrderQty = orderQty1.HasValue & orderQty2.HasValue ? new Decimal?(orderQty1.GetValueOrDefault() + orderQty2.GetValueOrDefault()) : new Decimal?();
                            }
                            if (demand.PlanType == "6B" || demand.PlanType == "6E")
                            {
                                str1 = demand.PlanType == "6B" ? "66" : "6D";
                                demand.FixedSource = "P";
                                copy1.POType       = soLineSplit3.POType;
                                copy1.PONbr        = soLineSplit3.PONbr;
                                copy1.POLineNbr    = soLineSplit3.POLineNbr;
                                POLine poLine2 = (POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POLine.pOType> >, And <POLine.orderNbr, Equal <Current <POLine.pONbr> >, And <POLine.lineNbr, Equal <Current <POLine.pOLineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1]
                                {
                                    (object)copy1
                                });

                                if (poLine2 != null)
                                {
                                    Decimal?nullable2   = demand.PlanQty;
                                    Decimal?baseOpenQty = poLine2.BaseOpenQty;
                                    if (nullable2.GetValueOrDefault() > baseOpenQty.GetValueOrDefault() & (nullable2.HasValue & baseOpenQty.HasValue))
                                    {
                                        POLine  poLine3  = copy1;
                                        Decimal?orderQty = poLine3.OrderQty;
                                        nullable2        = demand.OrderQty;
                                        poLine3.OrderQty = orderQty.HasValue & nullable2.HasValue ? new Decimal?(orderQty.GetValueOrDefault() - nullable2.GetValueOrDefault()) : new Decimal?();
                                        if (string.Equals(copy1.UOM, poLine2.UOM))
                                        {
                                            POLine poLine4 = copy1;
                                            nullable2 = poLine4.OrderQty;
                                            Decimal?openQty = poLine2.OpenQty;
                                            poLine4.OrderQty = nullable2.HasValue & openQty.HasValue ? new Decimal?(nullable2.GetValueOrDefault() + openQty.GetValueOrDefault()) : new Decimal?();
                                        }
                                        else
                                        {
                                            PXDBQuantityAttribute.CalcBaseQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1);
                                            POLine  poLine4      = copy1;
                                            Decimal?baseOrderQty = poLine4.BaseOrderQty;
                                            nullable2            = poLine2.BaseOpenQty;
                                            poLine4.BaseOrderQty = baseOrderQty.HasValue & nullable2.HasValue ? new Decimal?(baseOrderQty.GetValueOrDefault() + nullable2.GetValueOrDefault()) : new Decimal?();
                                            PXDBQuantityAttribute.CalcTranQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1);
                                        }
                                        pxErrorLevel = PXErrorLevel.RowWarning;
                                        empty       += PXMessages.LocalizeFormatNoPrefixNLA("Order Quantity reduced to Blanket Order: '{0}' Open Qty. for this item", (object)copy1.PONbr);
                                    }
                                    copy1.CuryUnitCost = poLine2.CuryUnitCost;
                                    copy1.UnitCost     = poLine2.UnitCost;
                                }
                            }
                            copy1.SiteID = POCreate_Extension.GetWasrehouseByBranch((PXGraph)docgraph, copy1.BranchID);
                            short?       vleadTime = docgraph.location.Current.VLeadTime;
                            POLine       poLine5   = copy1;
                            DateTime     dateTime  = soLineSplit3.ShipDate.Value;
                            ref DateTime local     = ref dateTime;
                            short?       nullable7 = vleadTime;
                            nullable1 = nullable7.HasValue ? new int?((int)nullable7.GetValueOrDefault()) : new int?();
                            int      num3      = 0;
                            double   num4      = nullable1.GetValueOrDefault() > num3 & nullable1.HasValue ? (double)-vleadTime.Value : -14.0;
                            DateTime?nullable8 = new DateTime?(local.AddDays(num4));
                            poLine5.RequestedDate = nullable8;
                            POLine  poLine6 = docgraph.Transactions.Update(copy1);
                            PXCache cach    = docgraph.Caches[typeof(INItemPlan)];
                            POCreate_Extension.CreateSplitDemand2(cach, demand);
                            cach.SetStatus((object)demand, PXEntryStatus.Updated);
                            demand.SupplyPlanID = poLine6.PlanID;
                            if (str1 != null)
                            {
                                cach.RaiseRowDeleted((object)demand);
                                demand.PlanType = str1;
                                cach.RaiseRowInserted((object)demand);
                            }
                            if (soLineSplit3 != null)
                            {
                                int num2;
                                if (demand.AlternateID != null)
                                {
                                    nullable1 = demand.InventoryID;
                                    num2      = nullable1.HasValue ? 1 : 0;
                                }
                                else
                                {
                                    num2 = 0;
                                }
                                if (num2 != 0)
                                {
                                    PXSelectBase <INItemXRef> pxSelectBase = (PXSelectBase <INItemXRef>) new PXSelect <INItemXRef, Where <INItemXRef.inventoryID, Equal <Required <INItemXRef.inventoryID> >, And <INItemXRef.alternateID, Equal <Required <INItemXRef.alternateID> > > > >((PXGraph)docgraph);
                                    INItemXRef inItemXref1 = (INItemXRef)pxSelectBase.Select((object)demand.InventoryID, (object)demand.AlternateID);
                                    if (inItemXref1 != null && inItemXref1.AlternateType == "GLBL")
                                    {
                                        int num5;
                                        if (poLine6.AlternateID != null)
                                        {
                                            nullable1 = poLine6.InventoryID;
                                            num5      = nullable1.HasValue ? 1 : 0;
                                        }
                                        else
                                        {
                                            num5 = 0;
                                        }
                                        if (num5 != 0)
                                        {
                                            INItemXRef inItemXref2 = (INItemXRef)pxSelectBase.Select((object)poLine6.InventoryID, (object)poLine6.AlternateID);
                                            if (inItemXref2 != null && inItemXref2.AlternateType == "GLBL")
                                            {
                                                poLine6.AlternateID = demand.AlternateID;
                                            }
                                        }
                                        else
                                        {
                                            poLine6.AlternateID = demand.AlternateID;
                                        }
                                    }
                                }
                                soLineSplit3.POType    = poLine6.OrderType;
                                soLineSplit3.PONbr     = poLine6.OrderNbr;
                                soLineSplit3.POLineNbr = poLine6.LineNbr;
                                soLineSplit3.RefNoteID = docgraph.Document.Current.NoteID;
                                PX.Objects.SO.SOLine soLine = SelectFrom <PX.Objects.SO.SOLine> .Where <PX.Objects.SO.SOLine.orderType.IsEqual <P.AsString>
                                                                                                        .And <PX.Objects.SO.SOLine.orderNbr.IsEqual <P.AsString>
                                                                                                              .And <PX.Objects.SO.SOLine.lineNbr.IsEqual <P.AsInt> > > > .View.ReadOnly.Select((PXGraph)docgraph, (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.LineNbr);

                                POLineExt extension1 = poLine6.GetExtension <POLineExt>();
                                SOLineExt extension2 = soLine.GetExtension <SOLineExt>();
                                extension1.UsrEndCustomerID = extension2.UsrEndCustomerID;
                                extension1.UsrNonStockItem  = extension2.UsrNonStockItem;
                                extension1.UsrProjectNbr    = extension2.UsrProjectNbr;
                                if (!string.IsNullOrEmpty(extension2.UsrProjectNbr))
                                {
                                    FLXProject flxProject = SelectFrom <FLXProject> .Where <FLXProject.projectNbr.IsEqual <P.AsString> > .View.ReadOnly.Select((PXGraph)docgraph, (object)extension2.UsrProjectNbr);

                                    extension1.UsrCust2Factory = flxProject.Cust2Factory;
                                    extension1.UsrFactoryPN    = flxProject.FactoryPN;
                                }
                                docgraph.GetExtension <POOrderEntry_Extension>().UpdateSOLine(soLineSplit3, docgraph.Document.Current.VendorID, true);
                                docgraph.FixedDemand.Cache.SetStatus((object)soLineSplit3, PXEntryStatus.Updated);
                            }
                            if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted)
                            {
                                using (PXTransactionScope transactionScope = new PXTransactionScope())
                                {
                                    docgraph.Save.Press();
                                    if (demand.PlanType == "90")
                                    {
                                        docgraph.Replenihment.Current = (INReplenishmentOrder)docgraph.Replenihment.Search <INReplenishmentOrder.noteID>((object)demand.RefNoteID);
                                        if (docgraph.Replenihment.Current != null)
                                        {
                                            INReplenishmentLine copy2 = PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine()));

                                            copy2.InventoryID      = poLine6.InventoryID;
                                            copy2.SubItemID        = poLine6.SubItemID;
                                            copy2.UOM              = poLine6.UOM;
                                            copy2.VendorID         = poLine6.VendorID;
                                            copy2.VendorLocationID = poLine6.VendorLocationID;
                                            copy2.Qty              = poLine6.OrderQty;
                                            copy2.POType           = poLine6.OrderType;
                                            copy2.PONbr            = docgraph.Document.Current.OrderNbr;
                                            copy2.POLineNbr        = poLine6.LineNbr;
                                            copy2.SiteID           = demand.POSiteID;
                                            copy2.PlanID           = demand.PlanID;
                                            docgraph.ReplenishmentLines.Update(copy2);
                                            docgraph.Caches[typeof(INItemPlan)].Delete((object)demand);
                                            docgraph.Save.Press();
                                        }
                                    }
                                    transactionScope.Complete();
                                }
                                if (pxErrorLevel == PXErrorLevel.RowInfo)
                                {
                                    PXProcessing <POFixedDemand> .SetInfo(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty);
                                }
                                else
                                {
                                    PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty);
                                }
                                if (documentList1.Find((object)docgraph.Document.Current) == null)
                                {
                                    documentList1.Add(docgraph.Document.Current);
                                }
                            }
                        }
        private static void X_RowSelected <DAC>(
            PXCache cache,
            object eRow,
            EventType eventType,
            FSServiceOrder fsServiceOrderRow,
            FSSrvOrdType fsSrvOrdTypeRow,
            bool disableSODetReferenceFields,
            bool docAllowsActualFieldEdition)
            where DAC : class, IBqlTable, IFSSODetBase, new()
        {
            if (eRow == null)
            {
                return;
            }

            var row = (DAC)eRow;

            Type                 dacType              = typeof(DAC);
            FSSODet              fsSODetRow           = null;
            bool                 calledFromSO         = false;
            bool                 calledFromAPP        = false;
            FSAppointmentDet     fsAppointmentDetRow  = null;
            FSAppointmentDetPart fsAppointmentDetPart = null;

            if (dacType == typeof(FSAppointmentDet) ||
                dacType == typeof(FSAppointmentDetService) ||
                dacType == typeof(FSAppointmentDetPart) ||
                dacType == typeof(FSAppointmentInventoryItem))
            {
                fsAppointmentDetRow = (FSAppointmentDet)eRow;
                if (dacType == typeof(FSAppointmentDetPart))
                {
                    fsAppointmentDetPart = (FSAppointmentDetPart)eRow;
                }
                calledFromAPP = true;
            }
            else
            {
                fsSODetRow   = (FSSODet)eRow;
                calledFromSO = true;
            }


            bool isEnabled;
            PXPersistingCheck persistingCheck;
            bool isInventoryLine = IsInventoryLine(row.LineType);
            bool isStockItem;

            if (isInventoryLine == false)
            {
                isStockItem = false;
            }
            else
            {
                if (row.LineType != ID.LineType_All.SERVICE &&
                    row.LineType != ID.LineType_All.NONSTOCKITEM)
                {
                    isStockItem = true;
                }
                else
                {
                    isStockItem = false;
                }
            }


            // Enable/Disable SODetID
            SetEnabledAndPersistingCheck <FSSODet.sODetID>(cache, eRow, eventType,
                                                           isEnabled: !disableSODetReferenceFields, persistingCheck: null);


            // Enable/Disable LineType
            SetEnabledAndPersistingCheck <FSSODet.lineType>(cache, eRow, eventType,
                                                            isEnabled: !disableSODetReferenceFields, persistingCheck: null);


            // Set InventoryID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = true;
            persistingCheck = PXPersistingCheck.NullOrBlank;
            if (isInventoryLine == false)
            {
                isEnabled       = false;
                persistingCheck = PXPersistingCheck.Nothing;
            }
            else if (row.IsPrepaid == true ||
                     disableSODetReferenceFields == true ||
                     (calledFromSO == true && fsServiceOrderRow.AllowInvoice == true))
            {
                isEnabled = false;
            }

            SetEnabledAndPersistingCheck <FSSODet.inventoryID>(cache, eRow, eventType,
                                                               isEnabled, persistingCheck);


            if (PXAccess.FeatureInstalled <FeaturesSet.subItem>())
            {
                // Set SubItemID properties BASED ON InventoryID and LineType
                SetEnabledAndPersistingCheck <FSSODet.subItemID>(cache, eRow, eventType,
                                                                 isEnabled: isEnabled && isStockItem,
                                                                 persistingCheck: isStockItem == true ? persistingCheck : PXPersistingCheck.Nothing);
            }


            // Set UOM properties SAME AS InventoryID
            SetEnabledAndPersistingCheck <FSSODet.uOM>(cache, eRow, eventType,
                                                       isEnabled, persistingCheck);


            // Enable/Disable billingRule
            isEnabled = false;
            if ((row.LineType == ID.LineType_All.SERVICE || row.LineType == ID.LineType_All.NONSTOCKITEM) &&
                row.IsPrepaid == false &&
                (fsSODetRow == null || fsSODetRow.Mem_LastReferencedBy == null) &&
                (calledFromAPP == true || (calledFromSO == true && fsServiceOrderRow?.AllowInvoice == false)))
            {
                isEnabled = true;
            }

            SetEnabledAndPersistingCheck <FSSODet.billingRule>(cache, eRow, eventType,
                                                               isEnabled, persistingCheck: null);


            // Enable/Disable ManualPrice
            isEnabled = true;
            if (row.IsPrepaid == true ||
                isInventoryLine == false ||
                row.InventoryID == null ||
                (calledFromSO && fsServiceOrderRow?.AllowInvoice == true))
            {
                isEnabled = false;
            }

            SetEnabledAndPersistingCheck <FSSODet.manualPrice>(cache, eRow, eventType,
                                                               isEnabled, persistingCheck: null);


            // Enable/Disable IsBillable Same as ManualPrice

            SetEnabledAndPersistingCheck <FSSODet.isBillable>(cache, eRow, eventType,
                                                              isEnabled, persistingCheck: null);


            // Enable/Disable CuryUnitPrice
            isEnabled = false;
            if (row.BillingRule != ID.BillingRule.NONE &&
                row.IsPrepaid == false &&
                row.InventoryID != null &&
                (calledFromAPP == true || (calledFromSO == true && fsServiceOrderRow?.AllowInvoice == false)))
            {
                isEnabled = true;
            }

            SetEnabledAndPersistingCheck <FSSODet.curyUnitPrice>(cache, eRow, eventType,
                                                                 isEnabled, persistingCheck: null);



            // Enable/Disable EstimatedDuration and ActualDuration
            isEnabled = false;
            if (row.LineType == ID.LineType_All.SERVICE &&
                row.InventoryID != null &&
                (calledFromAPP == true || (calledFromSO == true && fsServiceOrderRow?.AllowInvoice == false)))
            {
                isEnabled = true;
            }

            SetEnabledAndPersistingCheck <FSSODet.estimatedDuration>(cache, eRow, eventType,
                                                                     isEnabled, persistingCheck: null);
            if (fsAppointmentDetRow != null)
            {
                //Enable when there is only 1 or 0 staff related to the service
                bool enableByStaffRelated = fsAppointmentDetRow.StaffRelatedCount < 2;
                SetEnabledAndPersistingCheck <FSAppointmentDet.actualDuration>(cache, eRow, eventType,
                                                                               isEnabled: isEnabled && docAllowsActualFieldEdition && enableByStaffRelated, persistingCheck: null);
            }


            // Enable/Disable EstimatedQty and ActualQty
            isEnabled = false;
            if (isInventoryLine == true &&
                row.BillingRule != ID.BillingRule.TIME &&
                row.IsPrepaid == false &&
                row.InventoryID != null &&
                (fsAppointmentDetPart == null || (string.IsNullOrEmpty(fsAppointmentDetPart.LotSerialNbr) == true ||
                                                  (string.IsNullOrEmpty(fsAppointmentDetPart.LotSerialNbr) == false &&
                                                   fsAppointmentDetPart.LotSerTrack != INLotSerTrack.SerialNumbered))) &&
                (calledFromAPP == true || (calledFromSO == true && fsServiceOrderRow?.AllowInvoice == false)))
            {
                isEnabled = true;
            }

            SetEnabledAndPersistingCheck <FSSODet.estimatedQty>(cache, eRow, eventType,
                                                                isEnabled, persistingCheck: null);
            if (fsAppointmentDetRow != null)
            {
                SetEnabledAndPersistingCheck <FSAppointmentDet.qty>(cache, eRow, eventType,
                                                                    isEnabled: isEnabled && docAllowsActualFieldEdition, persistingCheck: null);
            }


            // Set SiteID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = false;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == true && row.InventoryID != null)
            {
                if (row.IsPrepaid == false)
                {
                    if (fsAppointmentDetPart != null)
                    {
                        isEnabled = fsAppointmentDetPart.SODetID == null;
                    }
                    else
                    {
                        isEnabled = true;
                    }
                }

                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.siteID>(cache, eRow, eventType,
                                                          isEnabled, persistingCheck);


            // Set SiteLocationID properties SAME AS SiteID
            SetEnabledAndPersistingCheck <FSSODet.siteLocationID>(cache, eRow, eventType,
                                                                  isEnabled, persistingCheck);


            // Set ProjectID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = false;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == true && row.InventoryID != null)
            {
                isEnabled       = true;
                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.projectID>(cache, eRow, eventType,
                                                             isEnabled, persistingCheck);


            // Set ProjectTaskID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = true;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == false || row.InventoryID == null)
            {
                isEnabled = false;
            }
            else if (ProjectDefaultAttribute.IsProject(cache.Graph, row.ProjectID) == true)
            {
                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.projectTaskID>(cache, eRow, eventType,
                                                                 isEnabled, persistingCheck);


            // Set CostCodeID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = true;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == false || row.InventoryID == null)
            {
                isEnabled = false;
            }
            else if (ProjectDefaultAttribute.IsProject(cache.Graph, row.ProjectID) == true)
            {
                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.costCodeID>(cache, eRow, eventType,
                                                              isEnabled, persistingCheck);


            // Set AcctID properties (SetEnabled and SetPersistingCheck)
            isEnabled       = false;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == true &&
                row.InventoryID != null &&
                fsServiceOrderRow?.Quote == false &&
                fsSrvOrdTypeRow?.Behavior != ID.Behavior_SrvOrderType.INTERNAL_APPOINTMENT)
            {
                isEnabled       = true;
                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.acctID>(cache, eRow, eventType,
                                                          isEnabled, persistingCheck);


            // Set SubID properties SAME AS AcctID
            SetEnabledAndPersistingCheck <FSSODet.subID>(cache, eRow, eventType,
                                                         isEnabled, persistingCheck);


            // Set PickupDeliveryServiceID properties (SetEnabled and SetPersistingCheck)
            if (fsAppointmentDetRow != null && dacType == typeof(FSAppointmentInventoryItem))
            {
                isEnabled       = false;
                persistingCheck = PXPersistingCheck.Nothing;
                if (row.LineType == ID.LineType_All.PICKUP_DELIVERY)
                {
                    isEnabled       = true;
                    persistingCheck = PXPersistingCheck.NullOrBlank;
                }

                SetEnabledAndPersistingCheck <FSAppointmentInventoryItem.pickupDeliveryServiceID>(cache, eRow, eventType,
                                                                                                  isEnabled, persistingCheck);
            }


            // Set IsBillable properties (SetEnabled and SetPersistingCheck)

            isEnabled = true;
            if (row.ContractRelated == true || row.IsPrepaid == true)
            {
                isEnabled = false;
            }

            SetEnabledAndPersistingCheck <FSSODet.isBillable>(cache, eRow, eventType,
                                                              isEnabled, persistingCheck: null);

            // Set TranDesc properties (SetEnabled and SetPersistingCheck)
            isEnabled       = true;
            persistingCheck = PXPersistingCheck.Nothing;
            if (isInventoryLine == false)
            {
                persistingCheck = PXPersistingCheck.NullOrBlank;
            }

            SetEnabledAndPersistingCheck <FSSODet.tranDesc>(cache, eRow, eventType,
                                                            isEnabled, persistingCheck);

            isEnabled       = false;
            persistingCheck = PXPersistingCheck.Nothing;
            if (fsSODetRow != null && fsSODetRow.EnablePO == true)
            {
                persistingCheck = PXPersistingCheck.NullOrBlank;
                isEnabled       = true;
            }

            SetEnabledAndPersistingCheck <FSSODet.curyUnitCost>(cache, eRow, eventType,
                                                                isEnabled, persistingCheck);


            SharedFunctions.UpdateEquipmentAction(cache, eRow);
            // Additional Enable/Disable for Equipment fields
            if ((calledFromSO == true && fsServiceOrderRow?.AllowInvoice == true))
            {
                isEnabled = false;
                SetEnabledAndPersistingCheck <FSSODet.SMequipmentID>(cache, eRow, eventType,
                                                                     isEnabled, persistingCheck: null);
            }
        }
        public virtual APInvoice ReleaseRetainageProc(APInvoice doc, RetainageOptions retainageOpts, bool isAutoRelease = false)
        {
            Base.Clear(PXClearOption.PreserveTimeStamp);

            if (retainageOpts.CuryRetainageAmt <= 0 || retainageOpts.CuryRetainageAmt > doc.CuryRetainageUnreleasedAmt)
            {
                throw new PXException(Messages.IncorrectRetainageAmount);
            }

            // Magic. We need to prevent rewriting of CurrencyInfo.IsReadOnly
            // by true in CurrencyInfoView
            //
            Base.CurrentDocument.Cache.AllowUpdate = true;

            PXResult <APInvoice, CurrencyInfo, Terms, Vendor> resultDoc =
                APInvoice_CurrencyInfo_Terms_Vendor
                .SelectSingleBound(Base, null, doc.DocType, doc.RefNbr, doc.VendorID)
                .Cast <PXResult <APInvoice, CurrencyInfo, Terms, Vendor> >()
                .First();

            CurrencyInfo info        = resultDoc;
            APInvoice    origInvoice = resultDoc;
            Vendor       vendor      = resultDoc;

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

            new_info.CuryInfoID = null;
            new_info.IsReadOnly = false;
            new_info            = PXCache <CurrencyInfo> .CreateCopy(Base.currencyinfo.Insert(new_info));

            APInvoice invoice = PXCache <APInvoice> .CreateCopy(origInvoice);

            invoice.CuryInfoID = new_info.CuryInfoID;
            invoice.DocType    = APDocType.Invoice;
            invoice.RefNbr     = null;
            invoice.LineCntr   = null;
            invoice.InvoiceNbr = retainageOpts.InvoiceNbr;

            // Must be set for _RowSelected event handler
            //
            invoice.OpenDoc  = true;
            invoice.Released = false;

            Base.Document.Cache.SetDefaultExt <APInvoice.isMigratedRecord>(invoice);
            invoice.BatchNbr        = null;
            invoice.PrebookBatchNbr = null;
            invoice.Prebooked       = false;
            invoice.ScheduleID      = null;
            invoice.Scheduled       = false;
            invoice.NoteID          = null;

            invoice.DueDate         = null;
            invoice.DiscDate        = null;
            invoice.CuryOrigDiscAmt = 0m;
            invoice.OrigDocType     = origInvoice.DocType;
            invoice.OrigRefNbr      = origInvoice.RefNbr;
            invoice.OrigDocDate     = origInvoice.DocDate;

            invoice.PaySel              = false;
            invoice.CuryLineTotal       = 0m;
            invoice.IsTaxPosted         = false;
            invoice.IsTaxValid          = false;
            invoice.CuryVatTaxableTotal = 0m;
            invoice.CuryVatExemptTotal  = 0m;

            invoice.CuryDocBal     = 0m;
            invoice.CuryOrigDocAmt = retainageOpts.CuryRetainageAmt;
            invoice.Hold           = !isAutoRelease && Base.apsetup.Current.HoldEntry == true || Base.IsApprovalRequired(invoice, Base.Document.Cache);

            invoice.DocDate     = retainageOpts.DocDate;
            invoice.FinPeriodID = retainageOpts.FinPeriodID;

            Base.ClearRetainageSummary(invoice);
            invoice.RetainageApply      = false;
            invoice.IsRetainageDocument = true;

            invoice = Base.Document.Insert(invoice);

            if (new_info != null)
            {
                CurrencyInfo b_info = (CurrencyInfo)PXSelect <CurrencyInfo,
                                                              Where <CurrencyInfo.curyInfoID, Equal <Current <APInvoice.curyInfoID> > > > .Select(Base);

                b_info.CuryID         = new_info.CuryID;
                b_info.CuryEffDate    = new_info.CuryEffDate;
                b_info.CuryRateTypeID = new_info.CuryRateTypeID;
                b_info.CuryRate       = new_info.CuryRate;
                b_info.RecipRate      = new_info.RecipRate;
                b_info.CuryMultDiv    = new_info.CuryMultDiv;
                Base.currencyinfo.Update(b_info);
            }

            decimal retainagePercent = (decimal)(retainageOpts.CuryRetainageAmt / doc.CuryRetainageTotal);

            PXResultset <APTran> details = PXSelectGroupBy <APTran,
                                                            Where <APTran.tranType, Equal <Required <APTran.tranType> >,
                                                                   And <APTran.refNbr, Equal <Required <APTran.refNbr> >,
                                                                        And <APTran.curyRetainageAmt, NotEqual <decimal0> > > >,
                                                            Aggregate <
                                                                GroupBy <APTran.taxCategoryID,
                                                                         Sum <APTran.curyRetainageAmt> > > >
                                           .Select(Base, doc.DocType, doc.RefNbr);

            APTran  tranNew       = null;
            decimal prevCuryTotal = 0m;

            TaxCalc oldTaxCalc = TaxBaseAttribute.GetTaxCalc <APTran.taxCategoryID>(Base.Transactions.Cache, null);

            TaxBaseAttribute.SetTaxCalc <APTran.taxCategoryID>(Base.Transactions.Cache, null, TaxCalc.ManualCalc);

            foreach (APTran detail in details)
            {
                // Create APTran record for chosen retainage amount,
                // clear all required fields to prevent tax calculation,
                // discount calculation and retainage calculation.
                // CuryUnitCost = 0m and CuryLineAmt = 0m here to prevent their
                // FieldDefaulting events, because in our case default value
                // should be equal to zero.
                //
                tranNew = Base.Transactions.Insert(new APTran
                {
                    CuryUnitCost = 0m,
                    CuryLineAmt  = 0m
                });

                tranNew.BranchID      = origInvoice.BranchID;
                tranNew.TaxCategoryID = detail.TaxCategoryID;
                tranNew.AccountID     = origInvoice.RetainageAcctID;
                tranNew.SubID         = origInvoice.RetainageSubID;
                tranNew.ProjectID     = ProjectDefaultAttribute.NonProject();

                tranNew.Qty                  = 0m;
                tranNew.CuryUnitCost         = 0m;
                tranNew.ManualDisc           = true;
                tranNew.DiscPct              = 0m;
                tranNew.CuryDiscAmt          = 0m;
                tranNew.RetainagePct         = 0m;
                tranNew.CuryRetainageAmt     = 0m;
                tranNew.CuryTaxableAmt       = 0m;
                tranNew.CuryTaxAmt           = 0;
                tranNew.CuryExpenseAmt       = 0m;
                tranNew.GroupDiscountRate    = 1m;
                tranNew.DocumentDiscountRate = 1m;

                using (new PXLocaleScope(vendor.LocaleName))
                {
                    tranNew.TranDesc = PXMessages.LocalizeFormatNoPrefix(
                        Messages.RetainageForTransactionDescription,
                        APDocTypeDict[origInvoice.DocType],
                        origInvoice.RefNbr);
                }

                prevCuryTotal       = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);
                tranNew.CuryLineAmt = PXCurrencyAttribute.RoundCury(Base.Transactions.Cache, tranNew, (detail.CuryRetainageAmt ?? 0m) * retainagePercent);
                tranNew             = Base.Transactions.Update(tranNew);
            }

            ClearCurrentDocumentDiscountDetails();

            // We should copy all taxes from the original document
            // because it is possible to add or delete them.
            //
            foreach (APTaxTran aptaxtran in PXSelect <APTaxTran,
                                                      Where <APTaxTran.module, Equal <BatchModule.moduleAP>,
                                                             And <APTaxTran.tranType, Equal <Required <APTaxTran.tranType> >,
                                                                  And <APTaxTran.refNbr, Equal <Required <APTaxTran.refNbr> > > > > >
                     .Select(Base, origInvoice.DocType, origInvoice.RefNbr)
                     .RowCast <APTaxTran>()
                     .Where(row => row.CuryRetainedTaxAmt != 0m))
            {
                APTaxTran new_aptaxtran = Base.Taxes.Insert(new APTaxTran
                {
                    TaxID = aptaxtran.TaxID
                });

                if (new_aptaxtran != null)
                {
                    new_aptaxtran = PXCache <APTaxTran> .CreateCopy(new_aptaxtran);

                    new_aptaxtran.TaxRate = aptaxtran.TaxRate;
                    new_aptaxtran         = Base.Taxes.Update(new_aptaxtran);
                }
            }

            TaxBaseAttribute.SetTaxCalc <APTran.taxCategoryID>(Base.Transactions.Cache, null, oldTaxCalc);
            decimal diff = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m);

            if (tranNew != null && diff != 0m)
            {
                HashSet <string> taxList = PXSelectJoin <APTax,
                                                         InnerJoin <Tax, On <Tax.taxID, Equal <APTax.taxID> > >,
                                                         Where <APTax.tranType, Equal <Required <APTax.tranType> >,
                                                                And <APTax.refNbr, Equal <Required <APTax.refNbr> >,
                                                                     And <APTax.lineNbr, Equal <Required <APTax.lineNbr> >,
                                                                          And <Tax.taxType, NotEqual <CSTaxType.use> > > > > >
                                           .Select(Base, tranNew.TranType, tranNew.RefNbr, tranNew.LineNbr)
                                           .RowCast <APTax>()
                                           .Select(row => row.TaxID)
                                           .ToHashSet();

                // To guarantee correct document total amount
                // we should calculate last line total,
                // including its taxes.
                //
                TaxAttribute.CalcTaxable calcClass = new TaxAttribute.CalcTaxable(false, TaxAttribute.TaxCalcLevelEnforcing.None);
                decimal curyLineAmt = calcClass.CalcTaxableFromTotalAmount(
                    Base.Transactions.Cache,
                    tranNew,
                    taxList,
                    invoice.DocDate.Value,
                    prevCuryTotal);

                tranNew.CuryLineAmt = curyLineAmt;
                tranNew             = Base.Transactions.Update(tranNew);
            }

            APVendorRefNbrAttribute aPVendorRefNbrAttribute = Base.Document.Cache.GetAttributesReadonly <APInvoice.invoiceNbr>()
                                                              .OfType <APVendorRefNbrAttribute>().FirstOrDefault();

            if (aPVendorRefNbrAttribute != null)
            {
                var args = new PXFieldVerifyingEventArgs(invoice, invoice.InvoiceNbr, true);
                aPVendorRefNbrAttribute.FieldVerifying(Base.Document.Cache, args);
            }

            return(invoice);
        }
        public virtual void Bill(CustomersList customer, EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

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

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

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

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

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


            decimal signOperation = 1m;

            decimal tipQty = 1m;

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

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

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

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

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

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

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

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

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

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

            if (Setup.Current.AutomaticReleaseAR == true)
            {
                ARDocumentRelease.ReleaseDoc(doclist, false);
            }
        }
Ejemplo n.º 28
0
        public virtual void Bill(CustomersList customer, EPCustomerBilling.BillingFilter filter)
        {
            ARInvoiceEntry arGraph = PXGraph.CreateInstance <ARInvoiceEntry>();
            RegisterEntry  pmGraph = PXGraph.CreateInstance <RegisterEntry>();

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

            PMRegister pmDoc = null;
            ARInvoice  arDoc = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    listOfDirectBilledClaims.Add(row);
                }

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

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

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

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

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

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