private static APTran AddTaxes(APInvoiceEntry docgraph, ExpenseClaimEntry expenseClaimGraph, APInvoice invoice, decimal signOperation, EPExpenseClaimDetails claimdetail, APTran tran, bool isTipTran) { var cmdEPTaxTran = new PXSelect <EPTaxTran, Where <EPTaxTran.claimDetailID, Equal <Required <EPTaxTran.claimDetailID> > > >(docgraph); var cmdEPTax = new PXSelect <EPTax, Where <EPTax.claimDetailID, Equal <Required <EPTax.claimDetailID> >, And <EPTax.taxID, Equal <Required <EPTax.taxID> > > > >(docgraph); if (isTipTran) { cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <True> > >(); cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <True> > >(); } else { cmdEPTaxTran.WhereAnd <Where <EPTaxTran.isTipTax, Equal <False> > >(); cmdEPTax.WhereAnd <Where <EPTax.isTipTax, Equal <False> > >(); } CurrencyInfo expenseCuriInfo = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.CuryInfoID); CurrencyInfo currencyinfo = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaimDetails.curyInfoID> > > > .SelectSingleBound(docgraph, null, claimdetail.ClaimCuryInfoID); foreach (EPTaxTran epTaxTran in cmdEPTaxTran.Select(claimdetail.ClaimDetailID)) { #region Add taxes APTaxTran new_aptax = docgraph.Taxes.Search <APTaxTran.taxID>(epTaxTran.TaxID); if (new_aptax == null) { new_aptax = new APTaxTran(); new_aptax.TaxID = epTaxTran.TaxID; TaxAttribute.SetTaxCalc <APTran.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.NoCalc); 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 = epTaxTran.TaxRate; new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + epTaxTran.ClaimCuryTaxableAmt * signOperation; new_aptax.CuryTaxAmt = (new_aptax.CuryTaxAmt ?? 0m) + epTaxTran.ClaimCuryTaxAmt * signOperation; new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + epTaxTran.ClaimCuryExpenseAmt * signOperation; TaxAttribute.SetTaxCalc <APTran.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc); new_aptax = docgraph.Taxes.Update(new_aptax); //On first inserting APTaxTran APTax line will be created automatically. //However, new APTax will not be inserted on APTaxTran line update, even if we already have more lines. //So, we have to do it manually. APTax aptax = docgraph.Tax_Rows.Search <APTax.lineNbr, APTax.taxID>(tran.LineNbr, new_aptax.TaxID); if (aptax == null) { EPTax epTax = cmdEPTax.Select(claimdetail.ClaimDetailID, new_aptax.TaxID); decimal ClaimCuryTaxableAmt = 0m; decimal ClaimCuryTaxAmt = 0m; decimal ClaimCuryExpenseAmt = 0m; if (EPClaimReceiptController.IsSameCury(claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID, expenseCuriInfo, currencyinfo)) { ClaimCuryTaxableAmt = epTax.CuryTaxableAmt ?? 0m; ClaimCuryTaxAmt = epTax.CuryTaxAmt ?? 0m; ClaimCuryExpenseAmt = epTax.CuryExpenseAmt ?? 0m; } else if (currencyinfo?.CuryRate != null) { PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxableAmt ?? 0m, out ClaimCuryTaxableAmt); PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.TaxAmt ?? 0m, out ClaimCuryTaxAmt); PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, epTax.ExpenseAmt ?? 0m, out ClaimCuryExpenseAmt); } aptax = docgraph.Tax_Rows.Insert(new APTax() { LineNbr = tran.LineNbr, TaxID = new_aptax.TaxID, TaxRate = epTax.TaxRate, CuryTaxableAmt = ClaimCuryTaxableAmt * signOperation, CuryTaxAmt = ClaimCuryTaxAmt * signOperation, CuryExpenseAmt = ClaimCuryExpenseAmt * signOperation }); } Tax taxRow = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(docgraph, new_aptax.TaxID); if ((taxRow.TaxCalcLevel == CSTaxCalcLevel.Inclusive || (invoice.TaxCalcMode == TaxCalculationMode.Gross && taxRow.TaxCalcLevel == CSTaxCalcLevel.CalcOnItemAmt)) && (tran.CuryTaxableAmt == null || tran.CuryTaxableAmt == 0m)) { tran.CuryTaxableAmt = epTaxTran.ClaimCuryTaxableAmt * signOperation; tran.CuryTaxAmt = epTaxTran.ClaimCuryTaxAmt * signOperation; tran = docgraph.Transactions.Update(tran); } } #endregion } return(tran); }
public virtual ARInvoice ReleaseRetainageProc(ARInvoice doc, RetainageOptions retainageOpts, bool isAutoRelease = false) { Base.Clear(PXClearOption.PreserveTimeStamp); if (retainageOpts.CuryRetainageAmt <= 0 || retainageOpts.CuryRetainageAmt > doc.CuryRetainageUnreleasedAmt) { throw new PXException(AP.Messages.IncorrectRetainageAmount); } // Magic. We need to prevent rewriting of CurrencyInfo.IsReadOnly // by true in CurrencyInfoView // Base.CurrentDocument.Cache.AllowUpdate = true; PXResult <ARInvoice, CurrencyInfo, Terms, Customer> resultDoc = ARInvoice_CurrencyInfo_Terms_Customer .SelectSingleBound(Base, null, doc.DocType, doc.RefNbr, doc.CustomerID) .Cast <PXResult <ARInvoice, CurrencyInfo, Terms, Customer> >() .First(); CurrencyInfo info = resultDoc; ARInvoice origInvoice = resultDoc; Customer customer = 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)); ARInvoice invoice = PXCache <ARInvoice> .CreateCopy(origInvoice); invoice.CuryInfoID = new_info.CuryInfoID; invoice.DocType = ARDocType.Invoice; invoice.RefNbr = null; invoice.LineCntr = null; invoice.InvoiceNbr = origInvoice.InvoiceNbr; // Must be set for _RowSelected event handler // invoice.OpenDoc = true; invoice.Released = false; Base.Document.Cache.SetDefaultExt <ARInvoice.isMigratedRecord>(invoice); Base.Document.Cache.SetDefaultExt <ARInvoice.hold>(invoice); invoice.BatchNbr = null; 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.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.ARSetup.Current.HoldEntry == true; 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 <ARInvoice.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 <ARTran> details = PXSelectGroupBy <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> >, And <ARTran.curyRetainageAmt, NotEqual <decimal0> > > >, Aggregate < GroupBy <ARTran.taxCategoryID, Sum <ARTran.curyRetainageAmt> > > > .Select(Base, doc.DocType, doc.RefNbr); ARTran tranNew = null; decimal prevCuryTotal = 0m; TaxCalc oldTaxCalc = TaxBaseAttribute.GetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null); TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null, TaxCalc.ManualCalc); foreach (ARTran detail in details) { // Create ARTran record for chosen retainage amount, // clear all required fields to prevent tax calculation, // discount calculation and retainage calculation. // CuryUnitPrice = 0m and CuryExtPrice = 0m here to prevent their // FieldDefaulting events, because in our case default value // should be equal to zero. // tranNew = Base.Transactions.Insert(new ARTran { CuryUnitPrice = 0m, CuryExtPrice = 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.ManualDisc = true; tranNew.DiscPct = 0m; tranNew.CuryDiscAmt = 0m; tranNew.RetainagePct = 0m; tranNew.CuryRetainageAmt = 0m; tranNew.CuryTaxableAmt = 0m; tranNew.CuryTaxAmt = 0; tranNew.GroupDiscountRate = 1m; tranNew.DocumentDiscountRate = 1m; using (new PXLocaleScope(customer.LocaleName)) { tranNew.TranDesc = PXMessages.LocalizeFormatNoPrefix( AP.Messages.RetainageForTransactionDescription, ARDocTypeDict[origInvoice.DocType], origInvoice.RefNbr); } prevCuryTotal = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m); tranNew.CuryExtPrice = 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 (ARTaxTran artaxtran in PXSelect <ARTaxTran, Where <ARTaxTran.module, Equal <BatchModule.moduleAR>, And <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >, And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > > .Select(Base, origInvoice.DocType, origInvoice.RefNbr) .RowCast <ARTaxTran>() .Where(row => row.CuryRetainedTaxAmt != 0m)) { ARTaxTran new_artaxtran = Base.Taxes.Insert(new ARTaxTran { TaxID = artaxtran.TaxID }); if (new_artaxtran != null) { new_artaxtran = PXCache <ARTaxTran> .CreateCopy(new_artaxtran); new_artaxtran.TaxRate = artaxtran.TaxRate; new_artaxtran = Base.Taxes.Update(new_artaxtran); } } TaxBaseAttribute.SetTaxCalc <ARTran.taxCategoryID>(Base.Transactions.Cache, null, oldTaxCalc); decimal diff = (retainageOpts.CuryRetainageAmt ?? 0m) - (invoice.CuryDocBal ?? 0m); if (tranNew != null && diff != 0m) { HashSet <string> taxList = PXSelectJoin <ARTax, InnerJoin <Tax, On <Tax.taxID, Equal <ARTax.taxID> > >, Where <ARTax.tranType, Equal <Required <ARTax.tranType> >, And <ARTax.refNbr, Equal <Required <ARTax.refNbr> >, And <ARTax.lineNbr, Equal <Required <ARTax.lineNbr> >, And <Tax.taxType, NotEqual <CSTaxType.use> > > > > > .Select(Base, tranNew.TranType, tranNew.RefNbr, tranNew.LineNbr) .RowCast <ARTax>() .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 curyExtPrice = calcClass.CalcTaxableFromTotalAmount( Base.Transactions.Cache, tranNew, taxList, invoice.DocDate.Value, prevCuryTotal); tranNew.CuryExtPrice = curyExtPrice; tranNew = Base.Transactions.Update(tranNew); } return(invoice); }
private static void CreateMemo(ARInvoiceEntry graph, ARRegister doc, RUTROT rutrot, string docType, bool OnRelease = false) { DuplicateFilter filter = PXCache <DuplicateFilter> .CreateCopy(graph.duplicatefilter.Current); foreach (PXResult <ARInvoice, CurrencyInfo, Terms, Customer> res in ARInvoice_CurrencyInfo_Terms_Customer.Select(graph, (object)doc.DocType, doc.RefNbr, doc.CustomerID)) { CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy((CurrencyInfo)res); info.CuryInfoID = null; info.IsReadOnly = false; info = PXCache <CurrencyInfo> .CreateCopy(graph.currencyinfo.Insert(info)); ARInvoice invoice = (ARInvoice)graph.Document.Cache.CreateInstance(); if (docType == ARDocType.CreditMemo) { invoice.DueDate = null; invoice.DiscDate = null; invoice.CustomerID = doc.CustomerID; invoice.ARAccountID = doc.ARAccountID; invoice.ARSubID = doc.ARSubID; } if (docType == ARInvoiceType.DebitMemo) { invoice.DueDate = ((ARInvoice)res).DueDate; invoice.DiscDate = ((ARInvoice)res).DiscDate; BranchRUTROT branchRUTROT = GetBranchRUTROT(graph); invoice.CustomerID = branchRUTROT.TaxAgencyAccountID; invoice.ARAccountID = null; invoice.ARSubID = null; } ARInvoiceRUTROT invoiceRUTROT = RUTROTHelper.GetExtensionNullable <ARInvoice, ARInvoiceRUTROT>(invoice); invoiceRUTROT.IsRUTROTDeductible = false; invoice.CuryInfoID = info.CuryInfoID; invoice.DocType = docType; invoice.OrigModule = GL.BatchModule.AR; invoice.RefNbr = null; invoice.OrigModule = GL.BatchModule.AR; invoice.DocDesc = PXLocalizer.LocalizeFormat(RUTROTMessages.MemoDescription, doc.RefNbr); invoice.OpenDoc = true; invoice.Released = false; invoice.Hold = false; invoice.Printed = false; invoice.Emailed = false; invoice.BatchNbr = null; invoice.ScheduleID = null; invoice.Scheduled = false; invoice.NoteID = null; invoice.RefNoteID = null; invoice.TermsID = null; invoice.InstallmentCntr = null; invoice.InstallmentNbr = null; invoice.CuryOrigDiscAmt = 0m; invoice.FinPeriodID = doc.FinPeriodID; invoice.OrigDocDate = invoice.DocDate; invoice.CuryLineTotal = 0m; invoice.IsTaxPosted = false; invoice.IsTaxValid = false; invoice.CuryVatTaxableTotal = 0m; invoice.CuryVatExemptTotal = 0m; invoice.StatementDate = null; invoice.PendingPPD = false; invoice.CustomerLocationID = null; if (!string.IsNullOrEmpty(invoice.PaymentMethodID)) { CA.PaymentMethod pm = null; if (invoice.CashAccountID.HasValue) { CA.PaymentMethodAccount pmAccount = null; PXResult <CA.PaymentMethod, CA.PaymentMethodAccount> pmResult = (PXResult <CA.PaymentMethod, CA.PaymentMethodAccount>) PXSelectJoin <CA.PaymentMethod, LeftJoin < CA.PaymentMethodAccount, On <CA.PaymentMethod.paymentMethodID, Equal <CA.PaymentMethodAccount.paymentMethodID> > >, Where < CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> >, And <CA.PaymentMethodAccount.cashAccountID, Equal <Required <CA.PaymentMethodAccount.cashAccountID> > > > > . Select(graph, invoice.PaymentMethodID, invoice.CashAccountID); pm = pmResult; pmAccount = pmResult; if (pm == null || pm.UseForAR == false || pm.IsActive == false) { invoice.PaymentMethodID = null; invoice.CashAccountID = null; } else if (pmAccount == null || pmAccount.CashAccountID == null || pmAccount.UseForAR != true) { invoice.CashAccountID = null; } } else { pm = PXSelect <CA.PaymentMethod, Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > > .Select(graph, invoice.PaymentMethodID); if (pm == null || pm.UseForAR == false || pm.IsActive == false) { invoice.PaymentMethodID = null; invoice.CashAccountID = null; invoice.PMInstanceID = null; } } if (invoice.PMInstanceID.HasValue) { CustomerPaymentMethod cpm = PXSelect <CustomerPaymentMethod, Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > . Select(graph, invoice.PMInstanceID); if (string.IsNullOrEmpty(invoice.PaymentMethodID) || cpm == null || cpm.IsActive == false || cpm.PaymentMethodID != invoice.PaymentMethodID) { invoice.PMInstanceID = null; } } } else { invoice.CashAccountID = null; invoice.PMInstanceID = null; } SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARInvoice.salesPersonID>(graph.Document.Cache, invoice); if (sp == null || sp.IsActive == false) { invoice.SalesPersonID = null; } invoice = graph.Document.Insert(invoice); } TX.TaxAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(graph.Transactions.Cache, null, TX.TaxCalc.ManualCalc); graph.FieldDefaulting.AddHandler <ARTran.salesPersonID>((sender, e) => { e.NewValue = null; e.Cancel = true; }); decimal roundedTotalDistributedLinesAmt = 0m; foreach (ARTran srcTran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr)) { ARTran origTran = PXCache <ARTran> .CreateCopy(srcTran); ARTranRUTROT tranRR = RUTROTHelper.GetExtensionNullable <ARTran, ARTranRUTROT>(origTran); if (tranRR.IsRUTROTDeductible != true) { continue; } ARTran tran = (ARTran)graph.Transactions.Cache.CreateInstance(); tran.TranType = graph.Document.Current.DocType; tran.RefNbr = graph.Document.Current.RefNbr; string origDrCr = origTran.DrCr; tran.DrCr = null; tran.Released = null; tran.CuryInfoID = null; tran.SOOrderNbr = null; tran.SOShipmentNbr = null; tran.OrigInvoiceDate = origTran.TranDate; tran.NoteID = null; tran.ManualPrice = true; tran.AccountID = origTran.AccountID; tran.SubID = origTran.SubID; tran.CuryTranAmt = Math.Floor(tranRR.CuryRUTROTAvailableAmt ?? 0m); roundedTotalDistributedLinesAmt += tran.CuryTranAmt ?? 0m; if (!string.IsNullOrEmpty(origTran.DeferredCode)) { DRSchedule schedule = PXSelect <DRSchedule, Where <DRSchedule.module, Equal <BQLConstants.moduleAR>, And <DRSchedule.docType, Equal <Required <DRSchedule.docType> >, And <DRSchedule.refNbr, Equal <Required <DRSchedule.refNbr> >, And <DRSchedule.lineNbr, Equal <Required <DRSchedule.lineNbr> > > > > > > . Select(graph, doc.DocType, doc.RefNbr, origTran.LineNbr); if (schedule != null) { tran.DefScheduleID = schedule.ScheduleID; } } SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARTran.salesPersonID>(graph.Transactions.Cache, origTran); if (sp == null || sp.IsActive == false) { tran.SalesPersonID = null; } ARTran insertedTran = graph.Transactions.Insert(tran); PXNoteAttribute.CopyNoteAndFiles(graph.Transactions.Cache, srcTran, graph.Transactions.Cache, insertedTran); insertedTran.ManualDisc = true; insertedTran.TaxCategoryID = null; graph.Transactions.Update(insertedTran); } decimal distributedFee = (rutrot.CuryDistributedAmt ?? 0m) - roundedTotalDistributedLinesAmt; if (distributedFee != 0m) { foreach (ARTran artran in graph.Transactions.Cache.Inserted) { if (Math.Round(distributedFee) == 0m) { break; } if (artran.CuryTranAmt != 0m) { artran.CuryTranAmt += Math.Sign(distributedFee); distributedFee -= Math.Sign(distributedFee); } graph.Transactions.Update(artran); } } graph.Document.Current.CuryOrigDocAmt = graph.Document.Current.CuryDocBal; graph.Document.Cache.Update(graph.Document.Current); graph.RowInserting.AddHandler <ARSalesPerTran>((sender, e) => { e.Cancel = true; }); foreach (ARSalesPerTran salespertran in PXSelect <ARSalesPerTran, Where <ARSalesPerTran.docType, Equal <Required <ARSalesPerTran.docType> >, And <ARSalesPerTran.refNbr, Equal <Required <ARSalesPerTran.refNbr> > > > > .Select(graph, doc.DocType, doc.RefNbr)) { ARSalesPerTran newtran = PXCache <ARSalesPerTran> .CreateCopy(salespertran); newtran.DocType = graph.Document.Current.DocType; newtran.RefNbr = graph.Document.Current.RefNbr; newtran.Released = false; newtran.CuryInfoID = null; newtran.CuryCommnblAmt *= -1m; newtran.CuryCommnAmt *= -1m; SalesPerson sp = (SalesPerson)PXSelectorAttribute.Select <ARSalesPerTran.salespersonID>(graph.salesPerTrans.Cache, newtran); if (!(sp == null || sp.IsActive == false)) { graph.salesPerTrans.Update(newtran); } } var discountDetailsSet = PXSelect <ARInvoiceDiscountDetail, Where <ARInvoiceDiscountDetail.docType, Equal <Required <ARInvoice.docType> >, And <ARInvoiceDiscountDetail.refNbr, Equal <Required <ARInvoice.refNbr> > > >, OrderBy <Asc <ARInvoiceDiscountDetail.docType, Asc <ARInvoiceDiscountDetail.refNbr> > > > .Select(graph, doc.DocType, doc.RefNbr); foreach (ARInvoiceDiscountDetail discountDetail in discountDetailsSet) { ARInvoiceDiscountDetail newDiscountDetail = PXCache <ARInvoiceDiscountDetail> .CreateCopy(discountDetail); newDiscountDetail.DocType = graph.Document.Current.DocType; newDiscountDetail.RefNbr = graph.Document.Current.RefNbr; newDiscountDetail.IsManual = true; DiscountEngine <ARTran> .UpdateDiscountDetail(graph.ARDiscountDetails.Cache, graph.ARDiscountDetails, newDiscountDetail); } graph.Save.Press(); if (docType == ARDocType.CreditMemo && !OnRelease) { CreateAdjustment(graph, doc, graph.Document.Current); } }
protected void ReceiptDetails_Insert(PXGraph graph, EntityImpl entity, EntityImpl targetEntity) { var lineNbr = targetEntity.Fields.SingleOrDefault(f => f.Name == "OrigLineNbr") as EntityValueField; var receiptQty = targetEntity.Fields.SingleOrDefault(f => f.Name == "Quantity") as EntityValueField; var location = targetEntity.Fields.SingleOrDefault(f => f.Name == "Location") as EntityValueField; var allocations = (targetEntity.Fields.SingleOrDefault(f => string.Equals(f.Name, "Allocations")) as EntityListField).Value ?? new EntityImpl[0]; var hasAllocations = allocations.Any(a => a.Fields != null && a.Fields.Length > 0); var receiptEntry = (INReceiptEntry)graph; string transferNbr = receiptEntry.receipt.Current.TransferNbr; var detailsCache = receiptEntry.transactions.Cache; if (lineNbr == null || transferNbr == null) { detailsCache.Current = detailsCache.Insert(); return; } INTran newtran = null; decimal newtranqty = Decimal.Parse(receiptQty.Value); decimal newtrancost = 0m; receiptEntry.ParseSubItemSegKeys(); using (new PXReadBranchRestrictedScope()) { foreach (PXResult <INTransitLine, INLocationStatus2, INTransitLineLotSerialStatus, INSite, InventoryItem, INTran> res in PXSelectJoin <INTransitLine, InnerJoin <INLocationStatus2, On <INLocationStatus2.locationID, Equal <INTransitLine.costSiteID> >, LeftJoin <INTransitLineLotSerialStatus, On <INTransitLine.transferNbr, Equal <INTransitLineLotSerialStatus.transferNbr>, And <INTransitLine.transferLineNbr, Equal <INTransitLineLotSerialStatus.transferLineNbr> > >, InnerJoin <INSite, On <INSite.siteID, Equal <INTransitLine.toSiteID> >, InnerJoin <InventoryItem, On <InventoryItem.inventoryID, Equal <INLocationStatus2.inventoryID> >, InnerJoin <INTran, On <INTran.docType, Equal <INDocType.transfer>, And <INTran.refNbr, Equal <INTransitLine.transferNbr>, And <INTran.lineNbr, Equal <INTransitLine.transferLineNbr>, And <INTran.invtMult, Equal <shortMinus1> > > > > > > > > >, Where <INTransitLine.transferNbr, Equal <Required <INTransitLine.transferNbr> >, And <INTransitLine.transferLineNbr, Equal <Required <INTransitLine.transferLineNbr> > > >, OrderBy <Asc <INTransitLine.transferNbr, Asc <INTransitLine.transferLineNbr> > > > .Select(receiptEntry, transferNbr, lineNbr.Value)) { INTransitLine transitline = res; INLocationStatus2 stat = res; INTransitLineLotSerialStatus lotstat = res; INSite site = res; InventoryItem item = res; INTran tran = res; if (stat.QtyOnHand == 0m || (lotstat != null && lotstat.QtyOnHand == 0m)) { continue; } if (newtran == null) { if (!object.Equals(receiptEntry.receipt.Current.BranchID, site.BranchID)) { INRegister copy = PXCache <INRegister> .CreateCopy(receiptEntry.receipt.Current); copy.BranchID = site.BranchID; receiptEntry.receipt.Update(copy); } newtran = PXCache <INTran> .CreateCopy(tran); newtran.OrigBranchID = newtran.BranchID; newtran.OrigTranType = newtran.TranType; newtran.OrigRefNbr = transitline.TransferNbr; newtran.OrigLineNbr = transitline.TransferLineNbr; newtran.BranchID = site.BranchID; newtran.DocType = receiptEntry.receipt.Current.DocType; newtran.RefNbr = receiptEntry.receipt.Current.RefNbr; newtran.LineNbr = (int)PXLineNbrAttribute.NewLineNbr <INTran.lineNbr>(receiptEntry.transactions.Cache, receiptEntry.receipt.Current); newtran.InvtMult = (short)1; newtran.SiteID = transitline.ToSiteID; newtran.LocationID = transitline.ToLocationID; newtran.ToSiteID = null; newtran.ToLocationID = null; newtran.BaseQty = 0m; newtran.Qty = 0m; newtran.UnitCost = 0m; newtran.Released = false; newtran.InvtAcctID = null; newtran.InvtSubID = null; newtran.ReasonCode = null; newtran.ARDocType = null; newtran.ARRefNbr = null; newtran.ARLineNbr = null; newtran.ProjectID = null; newtran.TaskID = null; newtran.CostCodeID = null; newtran.TranCost = 0m; receiptEntry.splits.Current = null; newtran = receiptEntry.transactions.Insert(newtran); receiptEntry.transactions.Current = newtran; if (receiptEntry.splits.Current != null) { receiptEntry.splits.Delete(receiptEntry.splits.Current); } } if (hasAllocations) { newtranqty = 0m; foreach (var allocation in allocations) { var newsplitqty = allocation.Fields.SingleOrDefault(f => f.Name == "Quantity") as EntityValueField; var newsplitlocation = allocation.Fields.SingleOrDefault(f => f.Name == "Location") as EntityValueField; INTranSplit newsplit = this.addReceiptSplitLine(receiptEntry, stat, lotstat, transitline, newtran, item, Decimal.Parse(newsplitqty.Value), newsplitlocation.Value); newtrancost += newsplit.BaseQty.Value * newsplit.UnitCost.Value; newtranqty += newsplit.BaseQty.Value; } break; } else { INTranSplit newsplit = this.addReceiptSplitLine(receiptEntry, stat, lotstat, transitline, tran, item, newtranqty, null); newtrancost += newsplit.BaseQty.Value * newsplit.UnitCost.Value; newtranqty += newsplit.BaseQty.Value; } } receiptEntry.UpdateTranCostQty(newtran, newtranqty, newtrancost); } }
public virtual void GenerateProc(Schedule s, short Times, DateTime runDate) { List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate); ARInvoiceEntry docgraph = CreateGraph(); foreach (ScheduleDet sdet in sd) { foreach (PXResult <ARInvoice, Customer, CurrencyInfo> res in PXSelectJoin <ARInvoice, InnerJoin <Customer, On <Customer.bAccountID, Equal <ARInvoice.customerID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <ARInvoice.curyInfoID> > > >, Where <ARInvoice.scheduleID, Equal <Required <ARInvoice.scheduleID> >, And <ARInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID)) { docgraph.Clear(); docgraph.customer.Current = (Customer)res; ARInvoice apdoc = (ARInvoice)res; CurrencyInfo info = (CurrencyInfo)res; CurrencyInfo new_info = PXCache <CurrencyInfo> .CreateCopy(info); new_info.CuryInfoID = null; new_info = docgraph.currencyinfo.Insert(new_info); ARInvoice new_ardoc = PXCache <ARInvoice> .CreateCopy(apdoc); new_ardoc.CuryInfoID = new_info.CuryInfoID; new_ardoc.DocDate = sdet.ScheduledDate; new_ardoc.FinPeriodID = sdet.ScheduledPeriod; new_ardoc.TranPeriodID = null; new_ardoc.DueDate = null; new_ardoc.DiscDate = null; new_ardoc.CuryOrigDiscAmt = null; new_ardoc.OrigDiscAmt = null; new_ardoc.RefNbr = null; new_ardoc.Scheduled = false; new_ardoc.CuryLineTotal = 0m; new_ardoc.CuryVatTaxableTotal = 0m; new_ardoc.CuryVatExemptTotal = 0m; new_ardoc.NoteID = null; bool forceClear = false; bool clearPM = false; if (new_ardoc.PMInstanceID.HasValue) { PXResult <CustomerPaymentMethod, CA.PaymentMethod> pmiResult = (PXResult <CustomerPaymentMethod, CA.PaymentMethod>) PXSelectJoin <CustomerPaymentMethod, InnerJoin <CA.PaymentMethod, On <CA.PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >, Where <CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(docgraph, new_ardoc.PMInstanceID); if (pmiResult != null) { CustomerPaymentMethod pmInstance = pmiResult; CA.PaymentMethod paymentMethod = pmiResult; if (pmInstance == null || pmInstance.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true) { clearPM = true; forceClear = true; } } else { clearPM = true; forceClear = true; } } else { if (string.IsNullOrEmpty(new_ardoc.PaymentMethodID) == false) { CA.PaymentMethod pm = PXSelect <CA.PaymentMethod, Where <CA.PaymentMethod.paymentMethodID, Equal <Required <CA.PaymentMethod.paymentMethodID> > > > .Select(docgraph, new_ardoc.PaymentMethodID); if (pm == null || pm.IsActive != true || pm.UseForAR != true) { clearPM = true; forceClear = true; } } } if (clearPM) { new_ardoc.PMInstanceID = null; new_ardoc.PaymentMethodID = null; new_ardoc.CashAccountID = null; } new_ardoc = docgraph.Document.Insert(new_ardoc); //force creditrule back docgraph.customer.Current = (Customer)res; if (forceClear == true) { ARInvoice copy = PXCache <ARInvoice> .CreateCopy(new_ardoc); copy.PMInstanceID = null; copy.PaymentMethodID = null; copy.CashAccountID = null; new_ardoc = docgraph.Document.Update(copy); } AddressAttribute.CopyRecord <ARInvoice.billAddressID>(docgraph.Document.Cache, new_ardoc, apdoc, false); ContactAttribute.CopyRecord <ARInvoice.billContactID>(docgraph.Document.Cache, new_ardoc, apdoc, false); TaxAttribute.SetTaxCalc <ARTran.taxCategoryID, ARTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc); PXNoteAttribute.SetNote(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetNote(Caches[typeof(ARInvoice)], apdoc)); PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_ardoc, PXNoteAttribute.GetFileNotes(Caches[typeof(ARInvoice)], apdoc)); foreach (ARTran aptran in PXSelect <ARTran, Where <ARTran.tranType, Equal <Required <ARTran.tranType> >, And <ARTran.refNbr, Equal <Required <ARTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr)) { ARTran new_aptran = PXCache <ARTran> .CreateCopy(aptran); new_aptran.RefNbr = null; new_aptran.CuryInfoID = null; docgraph.Transactions.Insert(new_aptran); } foreach (ARTaxTran tax in PXSelect <ARTaxTran, Where <ARTaxTran.tranType, Equal <Required <ARTaxTran.tranType> >, And <ARTaxTran.refNbr, Equal <Required <ARTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr)) { ARTaxTran new_artax = new ARTaxTran(); new_artax.TaxID = tax.TaxID; new_artax = docgraph.Taxes.Insert(new_artax); if (new_artax != null) { new_artax = PXCache <ARTaxTran> .CreateCopy(new_artax); new_artax.TaxRate = tax.TaxRate; new_artax.CuryTaxableAmt = tax.CuryTaxableAmt; new_artax.CuryTaxAmt = tax.CuryTaxAmt; new_artax = docgraph.Taxes.Update(new_artax); } } docgraph.Save.Press(); } s.LastRunDate = sdet.ScheduledDate; Running_Schedule.Cache.Update(s); } using (PXTransactionScope ts = new PXTransactionScope()) { Running_Schedule.Cache.Persist(PXDBOperation.Update); ts.Complete(this); } Running_Schedule.Cache.Persisted(false); }
public IEnumerable requestValidation(PXAdapter adapter) { foreach (FeaturesSet feature in adapter.Get()) { if (feature.Status == 3) { bool? customerDiscountsOld = PXAccess.FeatureInstalled <FeaturesSet.customerDiscounts>(); PXCache cache = new PXCache <FeaturesSet>(this); FeaturesSet update = PXCache <FeaturesSet> .CreateCopy(feature); update.Status = 0; update = this.Features.Update(update); this.Features.Delete(feature); if (update.Status != 1) { this.Features.Delete(new FeaturesSet() { Status = 1 }); } this.Persist(); var tasks = PXSelect <WZTask> .Select(this); WZTaskEntry taskGraph = CreateInstance <WZTaskEntry>(); foreach (WZTask task in tasks) { bool disableTask = false; bool enableTask = false; foreach ( WZTaskFeature taskFeature in PXSelectReadonly <WZTaskFeature, Where <WZTaskFeature.taskID, Equal <Required <WZTask.taskID> > > > .Select( this, task.TaskID)) { bool featureInstalled = (bool?)cache.GetValue(update, taskFeature.Feature) == true; if (!featureInstalled) { disableTask = true; enableTask = false; break; } enableTask = true; } if (disableTask) { task.Status = WizardTaskStatusesAttribute._DISABLED; taskGraph.TaskInfo.Update(task); taskGraph.Save.Press(); } if (enableTask && task.Status == WizardTaskStatusesAttribute._DISABLED) { bool needToBeOpen = false; WZScenario scenario = PXSelect <WZScenario, Where <WZScenario.scenarioID, Equal <Required <WZTask.scenarioID> > > > .Select(this, task.ScenarioID); if (scenario != null && scenario.Status == WizardScenarioStatusesAttribute._ACTIVE) { WZTask parentTask = PXSelect <WZTask, Where <WZTask.taskID, Equal <Required <WZTask.parentTaskID> > > > .Select( this, task.ParentTaskID); if (parentTask != null && (parentTask.Status == WizardTaskStatusesAttribute._OPEN || parentTask.Status == WizardTaskStatusesAttribute._ACTIVE)) { needToBeOpen = true; } foreach ( PXResult <WZTaskPredecessorRelation, WZTask> predecessorResult in PXSelectJoin <WZTaskPredecessorRelation, InnerJoin <WZTask, On <WZTask.taskID, Equal <WZTaskPredecessorRelation.predecessorID> > >, Where <WZTaskPredecessorRelation.taskID, Equal <Required <WZTask.taskID> > > > . Select(this, task.TaskID)) { WZTask predecessorTask = (WZTask)predecessorResult; if (predecessorTask != null) { if (predecessorTask.Status == WizardTaskStatusesAttribute._COMPLETED) { needToBeOpen = true; } else { needToBeOpen = false; break; } } } } task.Status = needToBeOpen ? WizardTaskStatusesAttribute._OPEN : WizardTaskStatusesAttribute._PENDING; taskGraph.TaskInfo.Update(task); taskGraph.Save.Press(); } } if (customerDiscountsOld == true && update.CustomerDiscounts != true) { PXUpdate <Set <ARSetup.applyLineDiscountsIfCustomerPriceDefined, True>, ARSetup> .Update(this); PXUpdate <Set <ARSetup.applyLineDiscountsIfCustomerClassPriceDefined, True>, ARSetup> .Update(this); PXUpdate <Set <SOOrderType.recalculateDiscOnPartialShipment, False, Set <SOOrderType.postLineDiscSeparately, False> >, SOOrderType> .Update(this); } yield return(update); } else { yield return(feature); } } bool needRefresh = !(ActivationBehaviour.Current != null && ActivationBehaviour.Current.Refresh == false); PXDatabase.ResetSlots(); PXPageCacheUtils.InvalidateCachedPages(); this.Clear(); if (needRefresh) { throw new PXRefreshException(); } }
protected override bool Process(Package package) { var account = package.Account; if (account.IncomingProcessing != true || account.CreateCase != true) { return(false); } var message = package.Message; if (!string.IsNullOrEmpty(message.Exception) || message.IsIncome != true || message.RefNoteID != null || message.ClassID == CRActivityClass.EmailRouting) { return(false); } var graph = PXGraph.CreateInstance <CRCaseMaint>(); SetCRSetup(graph); SetAccessInfo(graph); var copy = package.Graph.Caches[typeof(CRSMEmail)].CreateCopy(message); try { var caseCache = graph.Caches[typeof(CRCase)]; var @case = (CRCase)caseCache.Insert(); @case = graph.Case.Search <CRCase.caseCD>(@case.CaseCD); @case = PXCache <CRCase> .CreateCopy(@case); //@case.EMail = package.Address; @case.Subject = message.Subject; if (@case.Subject == null || @case.Subject.Trim().Length == 0) { @case.Subject = GetFromString(package.Address, package.Description); } @case.Description = message.Body; if (account.CreateCaseClassID != null) { @case.CaseClassID = account.CreateCaseClassID; } @case = PXCache <CRCase> .CreateCopy((CRCase)caseCache.Update(@case)); var contact = FindContact(graph, package.Address); if (contact != null) { @case.ContactID = contact.ContactID; message.ContactID = contact.ContactID; } else { CRCaseClass caseClass = PXSelect <CRCaseClass, Where <CRCaseClass.caseClassID, Equal <Required <CRCaseClass.caseClassID> > > > .SelectSingleBound(graph, null, @case.CaseClassID); if (caseClass == null || caseClass.RequireContact == true) { return(false); } } BAccount baccount = FindAccount(graph, contact); if (baccount != null) { PXCache cache = graph.Caches[typeof(BAccount)]; graph.EnsureCachePersistence(cache.GetItemType()); message.BAccountID = baccount.BAccountID; @case.CustomerID = baccount.BAccountID; } message.RefNoteID = PXNoteAttribute.GetNoteID <CRCase.noteID>(graph.Caches[typeof(CRCase)], @case); caseCache.Update(@case); graph.Activities.Cache.Current = message; graph.Save.PressImpl(false); } catch (Exception e) { package.Graph.Caches[typeof(CRSMEmail)].RestoreCopy(message, copy); throw new PXException(Messages.CreateCaseException, e is PXOuterException ? ("\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages)) : e.Message); } return(true); }
protected virtual void PrintPayments(List <APPayment> list, PrintChecksFilter filter, PaymentMethod paymentMethod) { if (list.Count == 0) { return; } if (paymentMethod.UseForAP == true) { if (paymentMethod.APPrintChecks == true && string.IsNullOrEmpty(paymentMethod.APCheckReportID)) { throw new PXException(Messages.FieldNotSetInPaymentMethod, PXUIFieldAttribute.GetDisplayName <PaymentMethod.aPCheckReportID>(paymenttype.Cache), paymentMethod.PaymentMethodID); } if (paymentMethod.APPrintChecks == true && paymentMethod.APPrintRemittance == true && string.IsNullOrEmpty(paymentMethod.APRemittanceReportID)) { throw new PXException(Messages.FieldNotSetInPaymentMethod, PXUIFieldAttribute.GetDisplayName <PaymentMethod.aPRemittanceReportID>(paymenttype.Cache), paymentMethod.PaymentMethodID); } } bool printAdditionRemit = false; if (paymentMethod.APCreateBatchPayment == true) { CABatchEntry be = CreateInstance <CABatchEntry>(); CABatch result = be.Document.Insert(new CABatch()); be.Document.Current = result; CABatch copy = (CABatch)be.Document.Cache.CreateCopy(result); copy.CashAccountID = filter.PayAccountID; copy.PaymentMethodID = filter.PayTypeID; result = be.Document.Update(copy); CABatch batch = be.Document.Current; if (batch != null) { bool failed = false; APPaymentEntry pe = CreateInstance <APPaymentEntry>(); string NextCheckNbr = filter.NextCheckNbr; foreach (APPayment pmt in list) { APPayment payment = pmt; if (pmt.CashAccountID != result.CashAccountID || pmt.PaymentMethodID != result.PaymentMethodID) { throw new PXException(Messages.APPaymentDoesNotMatchCABatchByAccountOrPaymentType); } if (string.IsNullOrEmpty(pmt.ExtRefNbr) && string.IsNullOrEmpty(filter.NextCheckNbr)) { throw new PXException(Messages.NextCheckNumberIsRequiredForProcessing); } PXProcessing <APPayment> .SetCurrentItem(payment); try { payment = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType); if (payment.PrintCheck != true) { throw new PXException(Messages.CantPrintNonprintableCheck); } if (payment.DocType.IsIn(APDocType.Check, APDocType.QuickCheck, APDocType.Prepayment) && payment.Status != APDocStatus.PendingPrint) { throw new PXException(Messages.ChecksMayBePrintedInPendingPrintStatus); } AssignNumbers(pe, payment, ref NextCheckNbr, true); if (payment.Passed == true) { pe.TimeStamp = payment.tstamp; } pe.Save.Press(); payment.tstamp = pe.TimeStamp; pe.Clear(); be.AddPayment(payment, true); } catch (PXException e) { PXProcessing <APPayment> .SetError(e); failed = true; } } bool batchHasPayments = be.BatchPayments.Select().Count > 0; if (failed && batchHasPayments) { be.Save.Press(); batch = be.Document.Current; throw new PXOperationCompletedWithErrorException(Messages.APPaymentsAreAddedToTheBatchFailedPaymentsExcluded, batch.BatchNbr); } if (failed && !batchHasPayments) { throw new PXOperationCompletedWithErrorException(); } be.Save.Press(); batch = be.Document.Current; RedirectToResultWithCreateBatch(batch); } } else { APReleaseChecks pp = CreateInstance <APReleaseChecks>(); ReleaseChecksFilter filter_copy = PXCache <ReleaseChecksFilter> .CreateCopy(pp.Filter.Current); filter_copy.PayAccountID = filter.PayAccountID; filter_copy.PayTypeID = filter.PayTypeID; filter_copy.CuryID = filter.CuryID; pp.Filter.Cache.Update(filter_copy); APPaymentEntry pe = CreateInstance <APPaymentEntry>(); bool failed = false; Dictionary <string, string> d = new Dictionary <string, string>(); string nextCheckNbr = filter.NextCheckNbr; string prevCheckNbr = nextCheckNbr; int idxReportFilter = 0; foreach (APPayment pmt in list) { APPayment payment = pmt; PXProcessing <APPayment> .SetCurrentItem(payment); try { prevCheckNbr = nextCheckNbr; if (filter.IsNextNumberDuplicated(this, nextCheckNbr)) { string duplicate = nextCheckNbr; nextCheckNbr = AutoNumberAttribute.NextNumber(nextCheckNbr); throw new PXException(Messages.ConflictWithExistingCheckNumber, duplicate); } payment = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType); if (payment.PrintCheck != true) { throw new PXException(Messages.CantPrintNonprintableCheck); } if (payment.DocType.IsIn(APDocType.Check, APDocType.QuickCheck, APDocType.Prepayment) && payment.Status != APDocStatus.PendingPrint) { throw new PXException(Messages.ChecksMayBePrintedInPendingPrintStatus); } AssignNumbers(pe, payment, ref nextCheckNbr); if (payment.Passed == true) { pe.TimeStamp = payment.tstamp; } pe.Save.Press(); payment.tstamp = pe.TimeStamp; pe.Clear(); APPayment seldoc = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType); seldoc.Selected = true; seldoc.Passed = true; seldoc.tstamp = payment.tstamp; pp.APPaymentList.Cache.Update(seldoc); pp.APPaymentList.Cache.SetStatus(seldoc, PXEntryStatus.Updated); printAdditionRemit |= seldoc.BillCntr > paymentMethod.APStubLines; StringBuilder sbDocType = new StringBuilder($"{nameof(APPayment)}.{nameof(APPayment.DocType)}"); sbDocType.Append(Convert.ToString(idxReportFilter)); StringBuilder sbRefNbr = new StringBuilder($"{nameof(APPayment)}.{nameof(APPayment.RefNbr)}"); sbRefNbr.Append(Convert.ToString(idxReportFilter)); idxReportFilter++; d[sbDocType.ToString()] = payment.DocType.IsIn(APDocType.Prepayment, APDocType.QuickCheck) ? payment.DocType : APDocType.Check; d[sbRefNbr.ToString()] = payment.RefNbr; PXProcessing <APPayment> .SetProcessed(); } catch (PXException e) { PXProcessing <APPayment> .SetError(e); failed = true; nextCheckNbr = prevCheckNbr; } } if (failed) { PXReportRequiredException report = null; if (d.Count > 0) { d[ReportMessages.CheckReportFlag] = ReportMessages.CheckReportFlagValue; report = new PXReportRequiredException(d, paymentMethod.APCheckReportID, PXBaseRedirectException.WindowMode.New, "Check"); } throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased, report); } else { if (d.Count > 0) { RedirectToResultNoBatch(pp, d, paymentMethod, printAdditionRemit, nextCheckNbr); } } } }
protected virtual void Location_IsAPPaymentInfoSameAsMain_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e) { CR.Location record = (CR.Location)e.Row; if (record.IsAPPaymentInfoSameAsMain == false) { LocationAPPaymentInfo mainloc = APPaymentInfoLocation.Select(); record.VCashAccountID = mainloc.VCashAccountID; record.VPaymentMethodID = mainloc.VPaymentMethodID; record.VPaymentLeadTime = mainloc.VPaymentLeadTime; record.VPaymentByType = mainloc.VPaymentByType; record.VSeparateCheck = mainloc.VSeparateCheck; record.IsRemitAddressSameAsMain = mainloc.IsRemitAddressSameAsMain; record.VRemitAddressID = mainloc.VRemitAddressID; record.IsRemitContactSameAsMain = mainloc.IsRemitContactSameAsMain; record.VRemitContactID = mainloc.VRemitContactID; record.VPaymentInfoLocationID = record.LocationID; LocationAPPaymentInfo copyloc = new LocationAPPaymentInfo(); copyloc.BAccountID = record.BAccountID; copyloc.LocationID = record.LocationID; copyloc.VCashAccountID = record.VCashAccountID; copyloc.VPaymentMethodID = record.VPaymentMethodID; copyloc.VPaymentLeadTime = record.VPaymentLeadTime; copyloc.VPaymentByType = record.VPaymentByType; copyloc.VSeparateCheck = record.VSeparateCheck; copyloc.IsRemitAddressSameAsMain = record.IsRemitAddressSameAsMain; copyloc.VDefAddressID = record.VDefAddressID; copyloc.VRemitAddressID = record.VRemitAddressID; copyloc.IsRemitContactSameAsMain = record.IsRemitContactSameAsMain; copyloc.VRemitContactID = record.VRemitContactID; copyloc.VDefContactID = record.VDefContactID; if (copyloc.VDefAddressID != copyloc.VRemitAddressID) { Address copyaddr = FindAddress(copyloc.VRemitAddressID); copyaddr = PXCache <Address> .CreateCopy(copyaddr); copyaddr.AddressID = null; copyaddr = RemitAddress.Insert(copyaddr); copyloc.VRemitAddressID = copyaddr.AddressID; } if (copyloc.VDefContactID != copyloc.VRemitContactID) { Contact copycont = FindContact(copyloc.VRemitContactID); copycont = PXCache <Contact> .CreateCopy(copycont); copycont.ContactID = null; copycont = RemitContact.Insert(copycont); copyloc.VRemitContactID = copycont.ContactID; } foreach (VendorPaymentMethodDetail maindet in this.PaymentDetails.Select(mainloc.BAccountID, mainloc.LocationID, mainloc.VPaymentMethodID)) { VendorPaymentMethodDetail copydet = PXCache <VendorPaymentMethodDetail> .CreateCopy(maindet); copydet.LocationID = copyloc.LocationID; this.PaymentDetails.Insert(copydet); } BusinessAccount.Cache.Current = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount)); APPaymentInfoLocation.Insert(copyloc); } if (record.IsAPPaymentInfoSameAsMain == true) { foreach (VendorPaymentMethodDetail copydet in this.PaymentDetails.Select(record.BAccountID, record.LocationID, record.VPaymentMethodID)) { this.PaymentDetails.Delete(copydet); } BAccount baccount = (BAccount)PXParentAttribute.SelectParent(sender, e.Row, typeof(BAccount)); if (baccount != null) { record.VPaymentInfoLocationID = baccount.DefLocationID; Location mainloc = PXSelect <CR.Location, Where <CR.Location.bAccountID, Equal <Required <CR.Location.bAccountID> >, And <CR.Location.locationID, Equal <Required <CR.Location.locationID> > > > > .Select(sender.Graph, baccount.BAccountID, baccount.DefLocationID); if (mainloc != null) { if (record.DefAddressID != record.VRemitAddressID && mainloc.VRemitAddressID != record.VRemitAddressID) { Address copyaddr = FindAddress(record.VRemitAddressID); RemitAddress.Delete(copyaddr); } if (record.DefContactID != record.VRemitContactID && mainloc.VRemitContactID != record.VRemitContactID) { Contact copycont = FindContact(record.VRemitContactID); RemitContact.Delete(copycont); } } } record.VCashAccountID = null; record.VPaymentMethodID = null; record.VPaymentLeadTime = 0; record.VSeparateCheck = false; record.VRemitAddressID = null; record.VRemitContactID = null; } }
public virtual IEnumerable apaccountlist() { foreach (PXResult <APHistoryByPeriod, RevaluedAPHistory, Vendor, Branch, FinPeriod, APHistoryLastRevaluation> res in PXSelectJoin <APHistoryByPeriod, InnerJoin <RevaluedAPHistory, On <RevaluedAPHistory.vendorID, Equal <APHistoryByPeriod.vendorID>, And <RevaluedAPHistory.branchID, Equal <APHistoryByPeriod.branchID>, And <RevaluedAPHistory.accountID, Equal <APHistoryByPeriod.accountID>, And <RevaluedAPHistory.subID, Equal <APHistoryByPeriod.subID>, And <RevaluedAPHistory.curyID, Equal <APHistoryByPeriod.curyID>, And <RevaluedAPHistory.finPeriodID, Equal <APHistoryByPeriod.lastActivityPeriod> > > > > > >, InnerJoin <Vendor, On <Vendor.bAccountID, Equal <APHistoryByPeriod.vendorID> >, InnerJoin <Branch, On <Branch.branchID, Equal <APHistoryByPeriod.branchID> >, InnerJoin <FinPeriod, On <APHistoryByPeriod.finPeriodID, Equal <FinPeriod.finPeriodID>, And <Branch.organizationID, Equal <FinPeriod.organizationID> > >, LeftJoin <APHistoryLastRevaluation, On <APHistoryByPeriod.vendorID, Equal <APHistoryLastRevaluation.vendorID>, And <APHistoryByPeriod.branchID, Equal <APHistoryLastRevaluation.branchID>, And <APHistoryByPeriod.accountID, Equal <APHistoryLastRevaluation.accountID>, And <APHistoryByPeriod.subID, Equal <APHistoryLastRevaluation.subID>, And <APHistoryByPeriod.curyID, Equal <APHistoryLastRevaluation.curyID> > > > > > > > > > >, Where <APHistoryByPeriod.curyID, Equal <Current <RevalueFilter.curyID> >, And <FinPeriod.masterFinPeriodID, Equal <Current <RevalueFilter.finPeriodID> >, And <Where <RevaluedAPHistory.curyFinYtdBalance, NotEqual <decimal0>, Or <RevaluedAPHistory.finPtdRevalued, NotEqual <decimal0>, Or <RevaluedAPHistory.curyFinYtdDeposits, NotEqual <decimal0> > > > > > > > .Select(this)) { APHistoryByPeriod histbyper = res; APHistoryLastRevaluation lastRevaluationPeriod = res; RevaluedAPHistory hist = PXCache <RevaluedAPHistory> .CreateCopy(res); RevaluedAPHistory existing; Vendor vendor = res; if ((existing = APAccountList.Locate(hist)) != null) { yield return(existing); continue; } else { APAccountList.Cache.SetStatus(hist, PXEntryStatus.Held); } hist.VendorClassID = vendor.VendorClassID; hist.CuryRateTypeID = cmsetup.Current.APRateTypeReval ?? ((Vendor)res).CuryRateTypeID; if (string.IsNullOrEmpty(hist.CuryRateTypeID)) { APAccountList.Cache.RaiseExceptionHandling <RevaluedGLHistory.curyRateTypeID>(hist, null, new PXSetPropertyException(Messages.RateTypeNotFound)); } else { CurrencyRate curyrate = PXSelect <CurrencyRate, Where <CurrencyRate.fromCuryID, Equal <Current <RevalueFilter.curyID> >, And <CurrencyRate.toCuryID, Equal <Current <Company.baseCuryID> >, And <CurrencyRate.curyRateType, Equal <Required <Vendor.curyRateTypeID> >, And <CurrencyRate.curyEffDate, LessEqual <Current <RevalueFilter.curyEffDate> > > > > >, OrderBy <Desc <CurrencyRate.curyEffDate> > > .Select(this, hist.CuryRateTypeID); if (curyrate == null || curyrate.CuryMultDiv == null) { hist.CuryMultDiv = "M"; hist.CuryRate = 1m; hist.RateReciprocal = 1m; hist.CuryEffDate = Filter.Current.CuryEffDate; APAccountList.Cache.RaiseExceptionHandling <RevaluedAPHistory.curyRate>(hist, 1m, new PXSetPropertyException(Messages.RateNotFound, PXErrorLevel.RowWarning)); } else { hist.CuryRate = curyrate.CuryRate; hist.RateReciprocal = curyrate.RateReciprocal; hist.CuryEffDate = curyrate.CuryEffDate; hist.CuryMultDiv = curyrate.CuryMultDiv; } CurrencyInfo info = new CurrencyInfo(); info.BaseCuryID = company.Current.BaseCuryID; info.CuryID = hist.CuryID; info.CuryMultDiv = hist.CuryMultDiv; info.CuryRate = hist.CuryRate; info.RecipRate = hist.RateReciprocal; hist.CuryFinYtdBalance -= hist.CuryFinYtdDeposits; hist.FinYtdBalance -= hist.FinYtdDeposits; decimal baseval; PXCurrencyAttribute.CuryConvBase(currencyinfo.Cache, info, (decimal)hist.CuryFinYtdBalance, out baseval); hist.FinYtdRevalued = baseval; hist.FinPrevRevalued = string.Equals(histbyper.FinPeriodID, histbyper.LastActivityPeriod) ? hist.FinPtdRevalued : 0m; hist.FinPtdRevalued = hist.FinYtdRevalued - hist.FinPrevRevalued - hist.FinYtdBalance; hist.LastRevaluedFinPeriodID = lastRevaluationPeriod?.LastActivityPeriod; } yield return(hist); } }
public override void Persist() { Contact cnt = contact.SelectSingle(); cnt = (Contact)contact.Cache.CreateCopy(cnt); if (UserList.Current != null) { UserList.Current.IsAssigned = cnt != null; foreach (Contact existing in PXSelect <Contact, Where <Contact.userID, Equal <Current <Users.pKID> > > > .Select(this)) { existing.UserID = null; contact.Update(existing); EPEmployee emp = Employee.Select(existing.ContactID); if (emp != null) { emp = PXCache <EPEmployee> .CreateCopy(emp); emp.UserID = null; Employee.Update(emp); } } if (cnt != null) { cnt.UserID = UserList.Current.PKID; contact.Update(cnt); EPEmployee emp = Employee.Select(cnt.ContactID); if (emp != null) { emp = PXCache <EPEmployee> .CreateCopy(emp); emp.UserID = UserList.Current.PKID; Employee.Update(emp); } } } foreach (Users user in UserList.Cache.Deleted) { cnt = (Contact)contact.View.SelectSingleBound(new object[] { user }); if (cnt != null) { cnt.UserID = null; contact.Update(cnt); EPEmployee emp = Employee.Select(cnt.ContactID); if (emp != null) { emp = PXCache <EPEmployee> .CreateCopy(emp); emp.UserID = null; Employee.Update(emp); } } } if (UserList.Current != null && UserList.Current.OverrideADRoles != true && UserList.Current.Source == PXUsersSourceListAttribute.ActiveDirectory) { //notice that this select returns nothing if called on AccessUsers. AccessUsers::roleList() returns empty list; foreach (UsersInRoles userrole in RoleList.Select()) { RoleList.Delete(userrole); } } //if no local roles selected - disable override. if (UserList.Current != null && UserList.Current.OverrideADRoles == true && UserList.Current.Source == PXUsersSourceListAttribute.ActiveDirectory) { if (RolesByUser.SelectSingle() == null) { UserListCurrent.Current.OverrideADRoles = false; } } base.Persist(); }
public virtual List <PXResult <INItemPlan, INPlanType> > ProcessPOReceipt(PXGraph graph, IEnumerable <PXResult <INItemPlan, INPlanType> > list, string POReceiptType, string POReceiptNbr) { var serviceOrder = new PXSelect <FSServiceOrder>(graph); if (!graph.Views.Caches.Contains(typeof(FSServiceOrder))) { graph.Views.Caches.Add(typeof(FSServiceOrder)); } var soDetSplit = new PXSelect <FSSODetSplit>(graph); if (!graph.Views.Caches.Contains(typeof(FSSODetSplit))) { graph.Views.Caches.Add(typeof(FSSODetSplit)); } var initemplan = new PXSelect <INItemPlan>(graph); List <PXResult <INItemPlan, INPlanType> > returnList = new List <PXResult <INItemPlan, INPlanType> >(); Base.FieldVerifying.AddHandler <FSSODetSplit.lotSerialNbr>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); List <FSSODetSplit> splitsToDeletePlanID = new List <FSSODetSplit>(); List <FSSODetSplit> insertedSchedules = new List <FSSODetSplit>(); List <INItemPlan> deletedPlans = new List <INItemPlan>(); foreach (PXResult <INItemPlan, INPlanType> res in list) { bool includeInReturnList = true; INItemPlan plan = PXCache <INItemPlan> .CreateCopy(res); INPlanType plantype = res; //avoid ReadItem() if (initemplan.Cache.GetStatus(plan) != PXEntryStatus.Inserted) { initemplan.Cache.SetStatus(plan, PXEntryStatus.Notchanged); } //Original Schedule Marked for PO / Allocated on Remote Whse //FSSODetSplit schedule = PXSelect<FSSODetSplit, Where<FSSODetSplit.planID, Equal<Required<FSSODetSplit.planID>>, And<FSSODetSplit.completed, Equal<False>>>>.Select(this, plan.DemandPlanID); FSSODetSplit schedule = PXSelect <FSSODetSplit, Where <FSSODetSplit.planID, Equal <Required <FSSODetSplit.planID> > > > .Select(graph, plan.DemandPlanID); if (schedule != null && (schedule.Completed == false || soDetSplit.Cache.GetStatus(schedule) == PXEntryStatus.Updated)) { includeInReturnList = false; schedule = PXCache <FSSODetSplit> .CreateCopy(schedule); schedule.BaseReceivedQty += plan.PlanQty; schedule.ReceivedQty = INUnitAttribute.ConvertFromBase(soDetSplit.Cache, schedule.InventoryID, schedule.UOM, (decimal)schedule.BaseReceivedQty, INPrecision.QUANTITY); soDetSplit.Cache.Update(schedule); INItemPlan origplan = PXSelect <INItemPlan, Where <INItemPlan.planID, Equal <Required <INItemPlan.planID> > > > .Select(graph, plan.DemandPlanID); if (origplan != null) { origplan.PlanQty = schedule.BaseQty - schedule.BaseReceivedQty; initemplan.Cache.Update(origplan); } //select Allocated line if any, exclude allocated on Remote Whse PXSelectBase <INItemPlan> cmd = new PXSelectJoin <INItemPlan, InnerJoin <FSSODetSplit, On <FSSODetSplit.planID, Equal <INItemPlan.planID> > >, Where <INItemPlan.demandPlanID, Equal <Required <INItemPlan.demandPlanID> >, And <FSSODetSplit.isAllocated, Equal <True>, And <FSSODetSplit.siteID, Equal <Required <FSSODetSplit.siteID> > > > > >(graph); if (!string.IsNullOrEmpty(plan.LotSerialNbr)) { cmd.WhereAnd <Where <INItemPlan.lotSerialNbr, Equal <Required <INItemPlan.lotSerialNbr> > > >(); } PXResult <INItemPlan> allocres = cmd.Select(plan.DemandPlanID, plan.SiteID, plan.LotSerialNbr); if (allocres != null) { schedule = PXResult.Unwrap <FSSODetSplit>(allocres); soDetSplit.Cache.SetStatus(schedule, PXEntryStatus.Notchanged); schedule = PXCache <FSSODetSplit> .CreateCopy(schedule); schedule.BaseQty += plan.PlanQty; schedule.Qty = INUnitAttribute.ConvertFromBase(soDetSplit.Cache, schedule.InventoryID, schedule.UOM, (decimal)schedule.BaseQty, INPrecision.QUANTITY); schedule.POReceiptType = POReceiptType; schedule.POReceiptNbr = POReceiptNbr; soDetSplit.Cache.Update(schedule); INItemPlan allocplan = PXCache <INItemPlan> .CreateCopy(res); allocplan.PlanQty += plan.PlanQty; initemplan.Cache.Update(allocplan); plantype = PXCache <INPlanType> .CreateCopy(plantype); plantype.ReplanOnEvent = null; plantype.DeleteOnEvent = true; } else { serviceOrder.Current = (FSServiceOrder)PXParentAttribute.SelectParent(soDetSplit.Cache, schedule, typeof(FSServiceOrder)); schedule = PXCache <FSSODetSplit> .CreateCopy(schedule); long?oldPlanID = schedule.PlanID; ClearScheduleReferences(ref schedule); plantype.ReplanOnEvent = INPlanConstants.PlanF1; schedule.IsAllocated = false; schedule.LotSerialNbr = plan.LotSerialNbr; schedule.POCreate = false; schedule.POSource = null; schedule.POReceiptType = POReceiptType; schedule.POReceiptNbr = POReceiptNbr; schedule.SiteID = plan.SiteID; schedule.VendorID = null; schedule.BaseReceivedQty = 0m; schedule.ReceivedQty = 0m; schedule.BaseQty = plan.PlanQty; schedule.Qty = INUnitAttribute.ConvertFromBase(soDetSplit.Cache, schedule.InventoryID, schedule.UOM, (decimal)schedule.BaseQty, INPrecision.QUANTITY); //update SupplyPlanID in existing item plans (replenishment) foreach (PXResult <INItemPlan> demand_res in PXSelect <INItemPlan, Where <INItemPlan.supplyPlanID, Equal <Required <INItemPlan.supplyPlanID> > > > .Select(graph, oldPlanID)) { INItemPlan demand_plan = PXCache <INItemPlan> .CreateCopy(demand_res); initemplan.Cache.SetStatus(demand_plan, PXEntryStatus.Notchanged); demand_plan.SupplyPlanID = plan.PlanID; initemplan.Cache.Update(demand_plan); } schedule.PlanID = plan.PlanID; schedule = (FSSODetSplit)soDetSplit.Cache.Insert(schedule); insertedSchedules.Add(schedule); } } else if (plan.DemandPlanID == null) { //Original schedule Marked for PO //TODO: verify this is sufficient for Original SO marked for TR. schedule = PXSelect <FSSODetSplit, Where <FSSODetSplit.planID, Equal <Required <FSSODetSplit.planID> >, And <FSSODetSplit.completed, Equal <False> > > > .Select(graph, plan.PlanID); if (schedule != null) { includeInReturnList = false; soDetSplit.Cache.SetStatus(schedule, PXEntryStatus.Notchanged); schedule = PXCache <FSSODetSplit> .CreateCopy(schedule); schedule.Completed = true; schedule.POCompleted = true; splitsToDeletePlanID.Add(schedule); soDetSplit.Cache.Update(schedule); INItemPlan origplan = PXSelect <INItemPlan, Where <INItemPlan.planID, Equal <Required <INItemPlan.planID> > > > .Select(graph, plan.PlanID); deletedPlans.Add(origplan); initemplan.Cache.Delete(origplan); } } if (includeInReturnList == true) { returnList.Add(res); } else { if (plantype.ReplanOnEvent != null) { plan.PlanType = plantype.ReplanOnEvent; plan.SupplyPlanID = null; plan.DemandPlanID = null; initemplan.Cache.Update(plan); } else if (plantype.DeleteOnEvent == true) { initemplan.Delete(plan); } } } //Create new schedules for partially received schedules marked for PO. FSSODetSplit prevSplit = null; foreach (FSSODetSplit newsplit in insertedSchedules) { if (prevSplit != null && prevSplit.SrvOrdType == newsplit.SrvOrdType && prevSplit.RefNbr == newsplit.RefNbr && prevSplit.LineNbr == newsplit.LineNbr && prevSplit.InventoryID == newsplit.InventoryID && prevSplit.SubItemID == newsplit.SubItemID && prevSplit.ParentSplitLineNbr == newsplit.ParentSplitLineNbr && prevSplit.LotSerialNbr != null && newsplit.LotSerialNbr != null) { continue; } FSSODetSplit parentschedule = PXSelect <FSSODetSplit, Where < FSSODetSplit.srvOrdType, Equal <Required <FSSODetSplit.srvOrdType> >, And <FSSODetSplit.refNbr, Equal <Required <FSSODetSplit.refNbr> >, And <FSSODetSplit.lineNbr, Equal <Required <FSSODetSplit.lineNbr> >, And <FSSODetSplit.splitLineNbr, Equal <Required <FSSODetSplit.parentSplitLineNbr> > > > > > > .Select(graph, newsplit.SrvOrdType, newsplit.RefNbr, newsplit.LineNbr, newsplit.ParentSplitLineNbr); if (parentschedule != null && parentschedule.Completed == true && parentschedule.POCompleted == true && parentschedule.BaseQty > parentschedule.BaseReceivedQty && deletedPlans.Exists(x => x.PlanID == parentschedule.PlanID)) { serviceOrder.Current = (FSServiceOrder)PXParentAttribute.SelectParent(soDetSplit.Cache, parentschedule, typeof(FSServiceOrder)); parentschedule = PXCache <FSSODetSplit> .CreateCopy(parentschedule); INItemPlan demand = PXCache <INItemPlan> .CreateCopy(deletedPlans.First(x => x.PlanID == parentschedule.PlanID)); UpdateSchedulesFromCompletedPO(graph, soDetSplit, initemplan, parentschedule, serviceOrder, demand); } prevSplit = newsplit; } //Added because of MySql AutoIncrement counters behavior foreach (FSSODetSplit split in splitsToDeletePlanID) { FSSODetSplit schedule = (FSSODetSplit)soDetSplit.Cache.Locate(split); if (schedule != null) { schedule.PlanID = null; soDetSplit.Cache.Update(schedule); } } return(returnList); }
public virtual void GenerateProc(Schedule s, short Times, DateTime runDate) { List <ScheduleDet> sd = GL.ScheduleProcess.MakeSchedule(this, s, Times, runDate); APInvoiceEntry docgraph = CreateGraph(); foreach (ScheduleDet sdet in sd) { foreach (PXResult <APInvoice, Vendor, CurrencyInfo> res in PXSelectJoin <APInvoice, InnerJoin <Vendor, On <Vendor.bAccountID, Equal <APInvoice.vendorID> >, InnerJoin <CurrencyInfo, On <CurrencyInfo.curyInfoID, Equal <APInvoice.curyInfoID> > > >, Where <APInvoice.scheduleID, Equal <Required <APInvoice.scheduleID> >, And <APInvoice.scheduled, Equal <boolTrue> > > > .Select(this, s.ScheduleID)) { docgraph.Clear(); docgraph.vendor.Current = (Vendor)res; APInvoice apdoc = (APInvoice)res; CurrencyInfo info = (CurrencyInfo)res; CurrencyInfo new_info = PXCache <CurrencyInfo> .CreateCopy(info); new_info.CuryInfoID = null; new_info = docgraph.currencyinfo.Insert(new_info); APInvoice new_apdoc = PXCache <APInvoice> .CreateCopy(apdoc); new_apdoc.CuryInfoID = new_info.CuryInfoID; new_apdoc.DocDate = sdet.ScheduledDate; new_apdoc.FinPeriodID = sdet.ScheduledPeriod; new_apdoc.TranPeriodID = null; new_apdoc.DueDate = null; new_apdoc.DiscDate = null; new_apdoc.PayDate = null; new_apdoc.CuryOrigDiscAmt = null; new_apdoc.OrigDiscAmt = null; new_apdoc.RefNbr = null; new_apdoc.Scheduled = false; new_apdoc.CuryLineTotal = 0m; new_apdoc.CuryVatTaxableTotal = 0m; new_apdoc.CuryVatExemptTotal = 0m; new_apdoc.NoteID = null; new_apdoc = docgraph.Document.Insert(new_apdoc); TaxAttribute.SetTaxCalc <APTran.taxCategoryID, APTaxAttribute>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc); PXNoteAttribute.SetNote(docgraph.Document.Cache, new_apdoc, PXNoteAttribute.GetNote(Caches[typeof(APInvoice)], apdoc)); PXNoteAttribute.SetFileNotes(docgraph.Document.Cache, new_apdoc, PXNoteAttribute.GetFileNotes(Caches[typeof(APInvoice)], apdoc)); foreach (APTran aptran in PXSelect <APTran, Where <APTran.tranType, Equal <Required <APTran.tranType> >, And <APTran.refNbr, Equal <Required <APTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr)) { APTran new_aptran = PXCache <APTran> .CreateCopy(aptran); new_aptran.RefNbr = null; new_aptran.CuryInfoID = null; docgraph.Transactions.Insert(new_aptran); } foreach (APTaxTran tax in PXSelect <APTaxTran, Where <APTaxTran.tranType, Equal <Required <APTaxTran.tranType> >, And <APTaxTran.refNbr, Equal <Required <APTaxTran.refNbr> > > > > .Select(docgraph, apdoc.DocType, apdoc.RefNbr)) { APTaxTran 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.TaxRate = tax.TaxRate; new_aptax.CuryTaxableAmt = tax.CuryTaxableAmt; new_aptax.CuryTaxAmt = tax.CuryTaxAmt; new_aptax = docgraph.Taxes.Update(new_aptax); } } docgraph.Save.Press(); } s.LastRunDate = sdet.ScheduledDate; Running_Schedule.Cache.Update(s); } using (PXTransactionScope ts = new PXTransactionScope()) { Running_Schedule.Cache.Persist(PXDBOperation.Update); ts.Complete(this); } Running_Schedule.Cache.Persisted(false); }
public virtual void RowPersisting(PXCache sender, PXRowPersistingEventArgs e) { if (IsMigrationModeEnabled == true) { return; } object key = sender.GetValue(e.Row, _FieldOrdinal); PXCache cache = sender.Graph.Caches[typeof(CATran)]; CATran info = null; if (key != null) { //do not read cached record in release processes if ((info = PXSelectReadonly <CATran, Where <CATran.tranID, Equal <Required <CATran.tranID> > > > .Select(sender.Graph, key)) != null) { CATran cached = (CATran)cache.Locate(info); if (cached != null) { if ((cached.OrigModule != null && info.OrigModule != null && cached.OrigModule != info.OrigModule) || (cached.OrigRefNbr != null && info.OrigRefNbr != null && cached.OrigRefNbr != info.OrigRefNbr) || (cached.OrigTranType != null && info.OrigTranType != null && cached.OrigTranType != info.OrigTranType)) { // TO Be removed after solving CATran issue (check JIRA item AC-57875 for details) throw new PXException(Messages.CouldNotInsertCATran); } if (cache.GetStatus(cached) == PXEntryStatus.Notchanged) { PXCache <CATran> .RestoreCopy(cached, info); } info = cached; } else { cache.SetStatus(info, PXEntryStatus.Notchanged); } } if ((long)key < 0L && info == null) { info = new CATran(); info.TranID = (long)key; info = (CATran)cache.Locate(info); } if (info == null) { key = null; sender.SetValue(e.Row, _FieldOrdinal, null); } } if ((e.Operation & PXDBOperation.Command) == PXDBOperation.Delete) { if (info != null) { cache.Delete(info); cache.PersistDeleted(info); } } else if (info == null) { if (!this.NeedPreventCashTransactionCreation(sender, e.Row)) { info = DefaultValues(sender, new CATran(), e.Row); if (info != null) { info = (CATran)cache.Insert(info); if (!(info.TranID < 0L)) { throw new PXException(Messages.CouldNotInsertCATran); } // TO Be removed after solving CATran issue (check JIRA item AC-57875 for details) sender.SetValue(e.Row, _FieldOrdinal, info.TranID); _KeyToAbort = info.TranID; cache.PersistInserted(info); long id = info.TranID ?? 0; if (id == 0 || id < 0) { throw new PXException(Messages.CATranNotSaved, sender.GetItemType().Name); } sender.SetValue(e.Row, _FieldOrdinal, id); info.TranID = id; cache.Normalize(); } } } else if (info.TranID < 0L) { info = DefaultValues(sender, PXCache <CATran> .CreateCopy(info), e.Row); if (info != null) { info = (CATran)cache.Update(info); sender.SetValue(e.Row, _FieldOrdinal, info.TranID); _KeyToAbort = info.TranID; cache.PersistInserted(info); long id = info.TranID ?? 0; if (id == 0 || id < 0) { throw new PXException(Messages.CATranNotSaved, sender.GetItemType().Name); } sender.SetValue(e.Row, _FieldOrdinal, id); info.TranID = id; cache.Normalize(); } } else { CATran copy = PXCache <CATran> .CreateCopy(info); copy = DefaultValues(sender, copy, e.Row); if (copy != null) { if ((copy.OrigModule != null && info.OrigModule != null && copy.OrigModule != info.OrigModule) || (copy.OrigRefNbr != null && info.OrigRefNbr != null && copy.OrigRefNbr != info.OrigRefNbr) || (copy.OrigTranType != null && info.OrigTranType != null && copy.OrigTranType != info.OrigTranType)) { // TO Be removed after solving CATran issue (check JIRA item AC-57875 for details) throw new PXException(Messages.CouldNotInsertCATran); } info = (CATran)cache.Update(copy); //to avoid another process updated DefaultValues will return null for Released docs, except for GLTran cache.PersistUpdated(info); } //JournalEntry is usually persisted prior to ReleaseGraph to obtain BatchNbr reference, read info should contain set Released flag else if (info.Released == false) { key = null; sender.SetValue(e.Row, _FieldOrdinal, null); cache.Delete(info); } } foreach (CATran toDelete in cache.Deleted) { cache.PersistDeleted(toDelete); } }
private static ARInvoice InsertFeeInvoice(ARDunningLetter doc, decimal dunningFee) { ARInvoiceEntry invGraph = PXGraph.CreateInstance <ARInvoiceEntry>(); int? organizationID = PXAccess.GetParentOrganizationID(doc.BranchID); string finPeriodID = invGraph.FinPeriodRepository.GetPeriodIDFromDate(doc.DunningLetterDate, organizationID); invGraph.FinPeriodUtils.ValidateFinPeriod(doc.SingleToArray(), m => finPeriodID, m => m.BranchID.SingleToArray()); ARSetup setup = PXSelect <ARSetup> .Select(invGraph); Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <ARDunningLetter.bAccountID> > > > .Select(invGraph, doc.BAccountID); CS.Numbering numbering = PXSelect <CS.Numbering, Where <CS.Numbering.numberingID, Equal <Required <ARSetup.dunningFeeNumberingID> > > > .Select(invGraph, setup.DunningFeeNumberingID); if (setup.DunningFeeInventoryID == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } IN.InventoryItem item = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <ARSetup.dunningFeeInventoryID> > > > .Select(invGraph, setup.DunningFeeInventoryID); if (item == null) { throw new PXException(Messages.DunningLetterEmptyInventory); } if (item.SalesAcctID == null) { throw new PXException(Messages.DunningProcessFeeEmptySalesAccount); } ARInvoice feeInvoice = new ARInvoice { DocType = ARDocType.Invoice }; if (numbering != null) { CS.AutoNumberAttribute.SetNumberingId <ARInvoice.refNbr>(invGraph.Document.Cache, feeInvoice.DocType, numbering.NumberingID); } feeInvoice = (ARInvoice)invGraph.Document.Cache.CreateCopy(invGraph.Document.Insert(feeInvoice)); feeInvoice.Released = false; feeInvoice.Voided = false; feeInvoice.BranchID = doc.BranchID; feeInvoice.DocDate = doc.DunningLetterDate; feeInvoice.CustomerID = customer.BAccountID; feeInvoice.DocDesc = Messages.DunningLetterFee; feeInvoice.CustomerLocationID = customer.DefLocationID; feeInvoice.CuryID = customer.AllowOverrideCury == false && customer.CuryID != null ? customer.CuryID : ((GL.Company)PXSelect <GL.Company> .Select(invGraph)).BaseCuryID; if (setup.DunningFeeTermID != null) { feeInvoice.TermsID = setup.DunningFeeTermID; } invGraph.Document.Update(feeInvoice); decimal curyVal; CurrencyInfo curyInfo = invGraph.currencyinfo.Select(); PXCurrencyAttribute.PXCurrencyHelper.CuryConvCury(invGraph.Caches[typeof(CurrencyInfo)], curyInfo, dunningFee, out curyVal); ARTran detail = new ARTran { BranchID = doc.BranchID, Qty = 1, CuryUnitPrice = curyVal, InventoryID = setup.DunningFeeInventoryID, AccountID = item.SalesAcctID, SubID = item.SalesSubID }; invGraph.Transactions.Insert(detail); feeInvoice = PXCache <ARInvoice> .CreateCopy(invGraph.Document.Current); feeInvoice.OrigDocAmt = feeInvoice.DocBal; feeInvoice.CuryOrigDocAmt = feeInvoice.CuryDocBal; feeInvoice.Hold = false; invGraph.Document.Update(feeInvoice); invGraph.Save.Press(); if (setup.AutoReleaseDunningFee == true) { invGraph.release.Press(); } return(invGraph.Document.Current); }
private static void GenerateRequisition(RQRequestSelection filter, List <RQRequestLineOwned> lines) { RQRequisitionEntry graph = PXGraph.CreateInstance <RQRequisitionEntry>(); RQRequisition requisition = (RQRequisition)graph.Document.Cache.CreateInstance(); graph.Document.Insert(requisition); requisition.ShipDestType = null; bool isCustomerSet = true; bool isVendorSet = true; bool isShipToSet = true; int? shipContactID = null; int? shipAddressID = null; var vendors = new HashSet <VendorRef>(); foreach (RQRequestLine line in lines) { PXResult <RQRequest, RQRequestClass> e = (PXResult <RQRequest, RQRequestClass>) PXSelectJoin <RQRequest, InnerJoin <RQRequestClass, On <RQRequestClass.reqClassID, Equal <RQRequest.reqClassID> > >, Where <RQRequest.orderNbr, Equal <Required <RQRequest.orderNbr> > > > .Select(graph, line.OrderNbr); RQRequest req = e; RQRequestClass reqclass = e; requisition = PXCache <RQRequisition> .CreateCopy(graph.Document.Current); if (reqclass.CustomerRequest == true && isCustomerSet) { if (requisition.CustomerID == null) { requisition.CustomerID = req.EmployeeID; requisition.CustomerLocationID = req.LocationID; } else if (requisition.CustomerID != req.EmployeeID || requisition.CustomerLocationID != req.LocationID) { isCustomerSet = false; } } else { isCustomerSet = false; } if (isShipToSet) { if (shipContactID == null && shipAddressID == null) { requisition.ShipDestType = req.ShipDestType; requisition.ShipToBAccountID = req.ShipToBAccountID; requisition.ShipToLocationID = req.ShipToLocationID; shipContactID = req.ShipContactID; shipAddressID = req.ShipAddressID; } else if (requisition.ShipDestType != req.ShipDestType || requisition.ShipToBAccountID != req.ShipToBAccountID || requisition.ShipToLocationID != req.ShipToLocationID) { isShipToSet = false; } } if (line.VendorID != null && line.VendorLocationID != null) { VendorRef vendor = new VendorRef() { VendorID = line.VendorID.Value, LocationID = line.VendorLocationID.Value }; vendors.Add(vendor); if (isVendorSet) { if (requisition.VendorID == null) { requisition.VendorID = line.VendorID; requisition.VendorLocationID = line.VendorLocationID; } else if (requisition.VendorID != line.VendorID || requisition.VendorLocationID != line.VendorLocationID) { isVendorSet = false; } } } else { isVendorSet = false; } if (!isCustomerSet) { requisition.CustomerID = null; requisition.CustomerLocationID = null; } if (!isVendorSet) { requisition.VendorID = null; requisition.VendorLocationID = null; requisition.RemitAddressID = null; requisition.RemitContactID = null; } else if (requisition.VendorID == req.VendorID && requisition.VendorLocationID == req.VendorLocationID) { requisition.RemitAddressID = req.RemitAddressID; requisition.RemitContactID = req.RemitContactID; } if (!isShipToSet) { requisition.ShipDestType = PX.Objects.PO.POShippingDestination.CompanyLocation; graph.Document.Cache.SetDefaultExt <RQRequisition.shipToBAccountID>(requisition); } graph.Document.Update(requisition); if (line.OpenQty > 0) { if (!graph.Lines.Cache.IsDirty && req.CuryID != requisition.CuryID) { requisition = PXCache <RQRequisition> .CreateCopy(graph.Document.Current); requisition.CuryID = req.CuryID; graph.Document.Update(requisition); } graph.InsertRequestLine(line, line.OpenQty.GetValueOrDefault(), filter.AddExists == true); } } if (isShipToSet) { foreach (PXResult <POAddress, POContact> res in PXSelectJoin <POAddress, CrossJoin <POContact>, Where <POAddress.addressID, Equal <Required <RQRequisition.shipAddressID> >, And <POContact.contactID, Equal <Required <RQRequisition.shipContactID> > > > > .Select(graph, shipAddressID, shipContactID)) { AddressAttribute.CopyRecord <RQRequisition.shipAddressID>(graph.Document.Cache, graph.Document.Current, (POAddress)res, true); AddressAttribute.CopyRecord <RQRequisition.shipContactID>(graph.Document.Cache, graph.Document.Current, (POContact)res, true); } } if (requisition.VendorID == null && vendors.Count > 0) { foreach (var vendor in vendors) { RQBiddingVendor bid = PXCache <RQBiddingVendor> .CreateCopy(graph.Vendors.Insert()); bid.VendorID = vendor.VendorID; bid.VendorLocationID = vendor.LocationID; graph.Vendors.Update(bid); } } if (graph.Lines.Cache.IsDirty) { graph.Save.Press(); throw new PXRedirectRequiredException(graph, Messages.RequisitionCreated); } for (int i = 0; i < lines.Count; i++) { PXProcessing <RQRequestLine> .SetInfo(i, PXMessages.LocalizeFormatNoPrefixNLA(Messages.RequisitionCreated, graph.Document.Current.ReqNbr)); } }
protected virtual void PrintPayments(List <APPayment> list, PrintChecksFilter filter, PaymentMethod paymenttype) { if (list.Count == 0) { return; } bool printAdditionRemit = false; if (paymenttype.APCreateBatchPayment == true) { CABatch batch = CreateBatchPayment(list, filter); if (batch != null) { bool failed = false; APPaymentEntry pe = PXGraph.CreateInstance <APPaymentEntry>(); string NextCheckNbr = filter.NextCheckNbr; for (int i = 0; i < list.Count; i++) { try { AssignNumbers(pe, list[i], ref NextCheckNbr, true); if (list[i].Passed == true) { pe.TimeStamp = list[i].tstamp; } pe.Save.Press(); list[i].tstamp = pe.TimeStamp; pe.Clear(); APPayment seldoc = (APPayment)pe.Document.Search <APPayment.refNbr>(list[i].RefNbr, list[i].DocType); printAdditionRemit = seldoc.BillCntr > paymenttype.APStubLines; } catch (Exception e) { PXProcessing <APPayment> .SetError(i, e); failed = true; } } if (failed) { throw new PXOperationCompletedException(Messages.APPaymentsAreAddedToTheBatchButWasNotUpdatedCorrectly, batch.BatchNbr); } else { RedirectToResultWithCreateBatch(batch); } } } else { APReleaseChecks pp = PXGraph.CreateInstance <APReleaseChecks>(); ReleaseChecksFilter filter_copy = PXCache <ReleaseChecksFilter> .CreateCopy(pp.Filter.Current); filter_copy.PayAccountID = filter.PayAccountID; filter_copy.PayTypeID = filter.PayTypeID; filter_copy.CuryID = filter.CuryID; pp.Filter.Cache.Update(filter_copy); APPaymentEntry pe = PXGraph.CreateInstance <APPaymentEntry>(); bool failed = false; List <APPayment> paylist = new List <APPayment>(list.Count); Dictionary <string, string> d = new Dictionary <string, string>(); string NextCheckNbr = null; if (filter != null) { NextCheckNbr = filter.NextCheckNbr; } int idxReportFilter = 0; for (int i = 0; i < list.Count; i++) { try { AssignNumbers(pe, list[i], ref NextCheckNbr); if (list[i].Passed == true) { pe.TimeStamp = list[i].tstamp; } pe.Save.Press(); list[i].tstamp = pe.TimeStamp; pe.Clear(); APPayment seldoc = (APPayment)pe.Document.Search <APPayment.refNbr>(list[i].RefNbr, list[i].DocType); seldoc.Selected = true; seldoc.Passed = true; seldoc.tstamp = list[i].tstamp; pp.APPaymentList.Cache.Update(seldoc); pp.APPaymentList.Cache.SetStatus(seldoc, PXEntryStatus.Updated); printAdditionRemit = seldoc.BillCntr > paymenttype.APStubLines; StringBuilder sbDocType = new StringBuilder("APPayment.DocType"); sbDocType.Append(Convert.ToString(idxReportFilter)); StringBuilder sbRefNbr = new StringBuilder("APPayment.RefNbr"); sbRefNbr.Append(Convert.ToString(idxReportFilter)); idxReportFilter++; d[sbDocType.ToString()] = list[i].DocType == APDocType.QuickCheck ? APDocType.QuickCheck : APDocType.Check; d[sbRefNbr.ToString()] = list[i].RefNbr; } catch (Exception e) { PXProcessing <APPayment> .SetError(i, e); failed = true; } } if (failed) { if (d.Count > 0) { d[ReportMessages.CheckReportFlag] = ReportMessages.CheckReportFlagValue; var requiredException = new PXReportRequiredException(d, paymenttype.APCheckReportID, PXBaseRedirectException.WindowMode.New, "Check"); throw new PXException(GL.Messages.DocumentsNotReleased, requiredException); } throw new PXOperationCompletedException(GL.Messages.DocumentsNotReleased); } else { if (d.Count > 0) { RedirectToResultNoBatch(pp, d, paymenttype, printAdditionRemit, NextCheckNbr); } } } }
public virtual decimal AllocateOverRCTLine( PXGraph graph, List <POReceiptLineAdjustment> result, AllocationItem allocationItem, decimal toDistribute, Int32?branchID) { // the artificial object is used for allocating the landed cost amount between splits (by quantity) var nAllocationItem = new AllocationItem() { LandedCostCode = new LandedCostCode() { AllocationMethod = LandedCostAllocationMethod.ByQuantity }, ReceiptLine = allocationItem.ReceiptLine, }; InventoryItem ii = InventoryItem.PK.Find(graph, allocationItem.ReceiptLine.InventoryID.Value); bool requireLotSerial = (ii.ValMethod == INValMethod.Specific); List <Type> bql = new List <Type>(16) { typeof(Select4 <, ,>), typeof(POReceiptLineSplit), typeof(Where <POReceiptLineSplit.receiptType, Equal <Required <POReceiptLine.receiptType> >, And <POReceiptLineSplit.receiptNbr, Equal <Required <POReceiptLine.receiptNbr> >, And <POReceiptLineSplit.lineNbr, Equal <Required <POReceiptLine.lineNbr> > > > >), typeof(Aggregate <>), typeof(GroupBy <,>), typeof(POReceiptLineSplit.locationID), typeof(GroupBy <,>), typeof(POReceiptLineSplit.subItemID), typeof(Sum <>), typeof(POReceiptLineSplit.baseQty), }; if (requireLotSerial) { bql.Insert(bql.Count - 2, typeof(GroupBy <,>)); bql.Insert(bql.Count - 2, typeof(POReceiptLineSplit.lotSerialNbr)); } PXView splitsView = new PXView(graph, false, BqlCommand.CreateInstance(bql.ToArray())); var splits = splitsView.SelectMulti(allocationItem.ReceiptLine.ReceiptType, allocationItem.ReceiptLine.ReceiptNbr, allocationItem.ReceiptLine.LineNbr); bool hasSplits = false; decimal baseTotal = GetBaseValue(nAllocationItem); decimal allocatedBase = 0m; decimal allocatingBase = 0m; decimal allocatedAmt = 0m; POReceiptLineSplit maxSplit = null; foreach (POReceiptLineSplit split in splits) { hasSplits = true; allocatingBase += split.BaseQty ?? 0m; decimal handledSplitsAmt = (baseTotal == 0m) ? 0m : (allocatedBase + allocatingBase) * toDistribute / baseTotal; handledSplitsAmt = PXDBCurrencyAttribute.BaseRound(graph, handledSplitsAmt); decimal shareAmt = handledSplitsAmt - allocatedAmt; if (maxSplit == null || maxSplit.BaseQty < split.BaseQty) { maxSplit = split; } if (shareAmt != 0m) { POReceiptLine newPOReceiptLine = PXCache <POReceiptLine> .CreateCopy(allocationItem.ReceiptLine); newPOReceiptLine.LocationID = maxSplit.LocationID; newPOReceiptLine.SiteID = maxSplit.SiteID; newPOReceiptLine.SubItemID = maxSplit.SubItemID; newPOReceiptLine.LotSerialNbr = requireLotSerial ? maxSplit.LotSerialNbr : null; var adj = CreateReceiptLineAdjustment(allocationItem, newPOReceiptLine, shareAmt, branchID); result.Add(adj); allocatedAmt += shareAmt; allocatedBase += allocatingBase; allocatingBase = 0m; maxSplit = null; } } if (!hasSplits) { decimal shareAmt = toDistribute; shareAmt = PXDBCurrencyAttribute.BaseRound(graph, shareAmt); if (shareAmt != 0m) { var adj = CreateReceiptLineAdjustment(allocationItem, null, shareAmt, branchID); result.Add(adj); } allocatedAmt = shareAmt; } return(allocatedAmt); }
protected virtual IEnumerable items() { ContractItem ci = SelectedContractItem.Select(); PXSelectBase <ContractDetail> select = new PXSelectJoin <ContractDetail, InnerJoin <Contract, On <Contract.contractID, Equal <ContractDetail.contractID> > >, Where <ContractDetail.contractItemID, Equal <Current <ContractFilter.contractItemID> > > >(this); List <PXResult <ContractDetail, Contract> > result = new List <PXResult <ContractDetail, Contract> >(); foreach (PXResult <ContractDetail, Contract> res in select.Select()) { ContractDetail item = res; bool isOutdated = false; ContractDetail copy = PXCache <ContractDetail> .CreateCopy(item); copy.ContractDetailID = -1; //Just to be safe that formulas on the following fields do not modify the original record. Items.Cache.SetDefaultExt <ContractDetail.basePriceOption>(copy); Items.Cache.SetDefaultExt <ContractDetail.basePrice>(copy); Items.Cache.SetDefaultExt <ContractDetail.renewalPriceOption>(copy); Items.Cache.SetDefaultExt <ContractDetail.renewalPrice>(copy); Items.Cache.SetDefaultExt <ContractDetail.fixedRecurringPriceOption>(copy); Items.Cache.SetDefaultExt <ContractDetail.fixedRecurringPrice>(copy); Items.Cache.SetDefaultExt <ContractDetail.usagePriceOption>(copy); Items.Cache.SetDefaultExt <ContractDetail.usagePrice>(copy); if (ci.BaseItemID != null) { if (ci.BasePriceOption != item.BasePriceOption || ci.BasePrice != item.BasePrice || copy.BasePriceVal != item.BasePriceVal) { isOutdated = true; } } if (ci.RenewalItemID != null) { if (ci.RenewalPriceOption != item.RenewalPriceOption || ci.RenewalPrice != item.RenewalPrice || copy.RenewalPriceVal != item.RenewalPriceVal) { isOutdated = true; } } if (ci.RecurringItemID != null) { if (ci.FixedRecurringPriceOption != item.FixedRecurringPriceOption || ci.FixedRecurringPrice != item.FixedRecurringPrice || copy.FixedRecurringPriceVal != item.FixedRecurringPriceVal) { isOutdated = true; } if (ci.UsagePriceOption != item.UsagePriceOption || ci.UsagePrice != item.UsagePrice || copy.UsagePriceVal != item.UsagePriceVal) { isOutdated = true; } } if (isOutdated) { result.Add(res); } } return(result); }
protected virtual ARInvoice InsertDocument( ARInvoiceEntry invoiceEntry, ScheduleDet occurrence, Customer customer, ARInvoice scheduledInvoice, CurrencyInfo scheduledInvoiceCurrencyInfo) { if (scheduledInvoice.Released == true) { throw new PXException(Messages.ScheduledDocumentAlreadyReleased); } // Cloning currency info is required because we want to preserve // (and not default) the currency rate type of the template document. // - CurrencyInfo newCurrencyInfo = PXCache <CurrencyInfo> .CreateCopy(scheduledInvoiceCurrencyInfo); newCurrencyInfo.CuryInfoID = null; newCurrencyInfo.CuryRate = null; newCurrencyInfo.CuryEffDate = occurrence.ScheduledDate; newCurrencyInfo = invoiceEntry.currencyinfo.Insert(newCurrencyInfo); ARInvoice newInvoice = PXCache <ARInvoice> .CreateCopy(scheduledInvoice); newInvoice.CuryInfoID = newCurrencyInfo.CuryInfoID; newInvoice.DocDate = occurrence.ScheduledDate; newInvoice.FinPeriodID = occurrence.ScheduledPeriod; newInvoice.TranPeriodID = null; newInvoice.DueDate = null; newInvoice.DiscDate = null; newInvoice.CuryOrigDiscAmt = null; newInvoice.OrigDiscAmt = null; newInvoice.RefNbr = null; newInvoice.Scheduled = false; newInvoice.CuryLineTotal = 0m; newInvoice.CuryVatTaxableTotal = 0m; newInvoice.CuryVatExemptTotal = 0m; newInvoice.NoteID = null; newInvoice.IsTaxValid = false; newInvoice.IsTaxPosted = false; newInvoice.IsTaxSaved = false; newInvoice.OrigDocType = scheduledInvoice.DocType; newInvoice.OrigRefNbr = scheduledInvoice.RefNbr; invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.printed>(newInvoice); invoiceEntry.Document.Cache.SetDefaultExt <ARInvoice.emailed>(newInvoice); bool forceClear = false; bool clearPaymentMethod = false; if (newInvoice.PMInstanceID.HasValue) { PXResult <CustomerPaymentMethod, PaymentMethod> paymentMethodResult = (PXResult <CustomerPaymentMethod, PaymentMethod>) PXSelectJoin < CustomerPaymentMethod, InnerJoin <PaymentMethod, On <PaymentMethod.paymentMethodID, Equal <CustomerPaymentMethod.paymentMethodID> > >, Where < CustomerPaymentMethod.pMInstanceID, Equal <Required <CustomerPaymentMethod.pMInstanceID> > > > .Select(invoiceEntry, newInvoice.PMInstanceID); if (paymentMethodResult != null) { CustomerPaymentMethod customerPaymentMethod = paymentMethodResult; PaymentMethod paymentMethod = paymentMethodResult; if (customerPaymentMethod == null || customerPaymentMethod.IsActive != true || paymentMethod.IsActive != true || paymentMethod.UseForAR != true) { clearPaymentMethod = true; forceClear = true; } } else { clearPaymentMethod = true; forceClear = true; } } else { if (!string.IsNullOrEmpty(newInvoice.PaymentMethodID)) { PaymentMethod paymentMethod = PXSelect < PaymentMethod, Where <PaymentMethod.paymentMethodID, Equal <Required <PaymentMethod.paymentMethodID> > > > .Select(invoiceEntry, newInvoice.PaymentMethodID); if (paymentMethod == null || paymentMethod.IsActive != true || paymentMethod.UseForAR != true) { clearPaymentMethod = true; forceClear = true; } } } if (clearPaymentMethod) { newInvoice.PMInstanceID = null; newInvoice.PaymentMethodID = null; newInvoice.CashAccountID = null; } newInvoice = invoiceEntry.Document.Insert(newInvoice); // Force credit rule back // - invoiceEntry.customer.Current = customer; if (forceClear == true) { ARInvoice copy = PXCache <ARInvoice> .CreateCopy(newInvoice); copy.PMInstanceID = null; copy.PaymentMethodID = null; copy.CashAccountID = null; newInvoice = invoiceEntry.Document.Update(copy); } AddressAttribute.CopyRecord <ARInvoice.billAddressID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false); ContactAttribute.CopyRecord <ARInvoice.billContactID>(invoiceEntry.Document.Cache, newInvoice, scheduledInvoice, false); CurrencyInfoAttribute.SetEffectiveDate <ARInvoice.docDate>( invoiceEntry.Document.Cache, new PXFieldUpdatedEventArgs(newInvoice, null, false)); PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(ARInvoice)], scheduledInvoice, invoiceEntry.Document.Cache, newInvoice); return(newInvoice); }
//TODO:refactor public static void SOCreateProc(List <SOFixedDemand> list, DateTime?PurchDate) { SOOrderEntry docgraph = PXGraph.CreateInstance <SOOrderEntry>(); SOSetup sosetup = docgraph.sosetup.Current; DocumentList <SOOrder> created = new DocumentList <SOOrder>(docgraph); docgraph.ExceptionHandling.AddHandler <SOLineSplit.qty>((cache, e) => { e.Cancel = true; }); docgraph.ExceptionHandling.AddHandler <SOLineSplit.isAllocated>((cache, e) => { ((SOLineSplit)e.Row).IsAllocated = true; e.Cancel = true; }); foreach (SOFixedDemand demand in list) { string OrderType = sosetup.TransferOrderType ?? SOOrderTypeConstants.TransferOrder; string demandPlanType = demand.PlanType; try { if (demand.SourceSiteID == null) { PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.MissingSourceSite); continue; } SOOrder order; SOLineSplit2 sosplit = PXSelect <SOLineSplit2, Where <SOLineSplit2.planID, Equal <Required <SOLineSplit2.planID> > > > .Select(docgraph, demand.PlanID); if (sosplit != null) { order = created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID>(OrderType, sosplit.ToSiteID, sosplit.SiteID); } else { if (demand.SourceSiteID == demand.SiteID) { PXProcessing <SOFixedDemand> .SetWarning(list.IndexOf(demand), Messages.EqualSourceDestinationSite); continue; } order = created.Find <SOOrder.orderType, SOOrder.destinationSiteID, SOOrder.defaultSiteID>(OrderType, demand.SiteID, demand.SourceSiteID); } if (order == null) { order = new SOOrder(); } if (order.OrderNbr == null) { docgraph.Clear(); if (sosplit != null) { INSite sourceSite = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(docgraph, sosplit.SiteID); order.BranchID = sourceSite.BranchID; order.OrderType = OrderType; order = PXCache <SOOrder> .CreateCopy(docgraph.Document.Insert(order)); order.DefaultSiteID = sosplit.SiteID; order.DestinationSiteID = sosplit.ToSiteID; order.OrderDate = PurchDate; docgraph.Document.Update(order); } else { INSite sourceSite = PXSelect <INSite, Where <INSite.siteID, Equal <Required <INSite.siteID> > > > .Select(docgraph, demand.SourceSiteID); order.BranchID = sourceSite.BranchID; order.OrderType = OrderType; order = PXCache <SOOrder> .CreateCopy(docgraph.Document.Insert(order)); order.DefaultSiteID = demand.SourceSiteID; order.DestinationSiteID = demand.SiteID; order.OrderDate = PurchDate; docgraph.Document.Update(order); } } else if (docgraph.Document.Cache.ObjectsEqual(docgraph.Document.Current, order) == false) { docgraph.Document.Current = docgraph.Document.Search <SOOrder.orderNbr>(order.OrderNbr, order.OrderType); } SOLine newline; SOLineSplit newsplit; PXCache cache = docgraph.Caches[typeof(INItemPlan)]; INItemPlan rp; if (sosplit != null) { docgraph.Transactions.Current = newline = docgraph.Transactions.Search <SOLine.inventoryID, SOLine.subItemID, SOLine.siteID, SOLine.pOCreate>(demand.InventoryID, demand.SubItemID, demand.SiteID, false); if (newline == null) { newline = PXCache <SOLine> .CreateCopy(docgraph.Transactions.Insert()); newline.InventoryID = demand.InventoryID; newline.SubItemID = demand.SubItemID; newline.SiteID = demand.SiteID; newline.UOM = demand.UOM; newline.OrderQty = 0m; newline = docgraph.Transactions.Update(newline); } newsplit = new SOLineSplit(); newsplit.LotSerialNbr = sosplit.LotSerialNbr; newsplit.IsAllocated = true; newsplit.IsMergeable = false; newsplit.SiteID = demand.SiteID; //SiteID should be explicitly set because of PXFormula newsplit.Qty = demand.OrderQty; newsplit.RefNoteID = demand.RefNoteID; //we have to delete previous allocation and reinsert it after the newsplit for transfer-order allocation to work properly rp = PXCache <INItemPlan> .CreateCopy(demand); cache.RaiseRowDeleted(demand); newsplit = docgraph.splits.Insert(newsplit); sosplit.SOOrderType = newsplit.OrderType; sosplit.SOOrderNbr = newsplit.OrderNbr; sosplit.SOLineNbr = newsplit.LineNbr; sosplit.SOSplitLineNbr = newsplit.SplitLineNbr; docgraph.sodemand.Update(sosplit); rp.SiteID = sosplit.ToSiteID; rp.PlanType = INPlanConstants.Plan93; rp.FixedSource = null; rp.SupplyPlanID = newsplit.PlanID; cache.RaiseRowInserted(rp); cache.SetStatus(rp, PXEntryStatus.Updated); } else { docgraph.Transactions.Current = newline = docgraph.Transactions.Search <SOLine.inventoryID, SOLine.subItemID, SOLine.siteID, SOLine.pOCreate>(demand.InventoryID, demand.SubItemID, demand.SourceSiteID, demand.VendorID != null); if (newline == null) { newline = PXCache <SOLine> .CreateCopy(docgraph.Transactions.Insert()); newline.InventoryID = demand.InventoryID; newline.SubItemID = demand.SubItemID; newline.SiteID = demand.SourceSiteID; newline.UOM = demand.UOM; newline.OrderQty = 0m; //newline.POCreate = (demand.VendorID != null); newline.POCreate = (demand.FixedSource == INReplenishmentSource.TransferToPurchase); newline.VendorID = demand.VendorID; //newline.VendorLocationID = demand.VendorLocationID; newline = docgraph.Transactions.Update(newline); } newsplit = new SOLineSplit(); newsplit.IsAllocated = false; newsplit.Qty = demand.OrderQty; //newsplit.POCreate = (demand.VendorID != null); newsplit.POCreate = (demand.FixedSource == INReplenishmentSource.TransferToPurchase); newsplit.VendorID = demand.VendorID; //newsplit.VendorLocationID = demand.VendorLocationID; newsplit = docgraph.splits.Insert(newsplit) ?? docgraph.splits.Current; rp = PXCache <INItemPlan> .CreateCopy(demand); cache.RaiseRowDeleted(demand); rp.SiteID = demand.SiteID; rp.PlanType = INPlanConstants.Plan94; rp.FixedSource = null; rp.SupplyPlanID = newsplit.PlanID; cache.RaiseRowInserted(rp); cache.SetStatus(rp, PXEntryStatus.Updated); } if (newsplit.PlanID == null) { throw new PXRowPersistedException(typeof(SOLine).Name, newline, RQ.Messages.UnableToCreateSOOrders); } if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted) { using (PXTransactionScope scope = new PXTransactionScope()) { docgraph.Save.Press(); if (demandPlanType == INPlanConstants.Plan90) { docgraph.Replenihment.Current = docgraph.Replenihment.Search <INReplenishmentOrder.noteID>(demand.RefNoteID); if (docgraph.Replenihment.Current != null) { INReplenishmentLine rLine = PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine())); rLine.InventoryID = newsplit.InventoryID; rLine.SubItemID = newsplit.SubItemID; rLine.UOM = newsplit.UOM; rLine.Qty = newsplit.Qty; rLine.SOType = newsplit.OrderType; rLine.SONbr = docgraph.Document.Current.OrderNbr; rLine.SOLineNbr = newsplit.LineNbr; rLine.SOSplitLineNbr = newsplit.SplitLineNbr; rLine.SiteID = demand.SourceSiteID; rLine.DestinationSiteID = demand.SiteID; rLine.PlanID = demand.PlanID; docgraph.ReplenishmentLines.Update(rLine); INItemPlan plan = PXSelect <INItemPlan, Where <INItemPlan.planID, Equal <Required <INItemPlan.planID> > > > .SelectWindowed(docgraph, 0, 1, demand.SupplyPlanID); if (plan != null) { //plan.SupplyPlanID = rp.PlanID; rp.SupplyPlanID = plan.PlanID; cache.SetStatus(rp, PXEntryStatus.Updated); } docgraph.Save.Press(); } } scope.Complete(); } PXProcessing <SOFixedDemand> .SetInfo(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA(Messages.TransferOrderCreated, docgraph.Document.Current.OrderNbr)); if (created.Find(docgraph.Document.Current) == null) { created.Add(docgraph.Document.Current); } } } catch (Exception e) { PXProcessing <SOFixedDemand> .SetError(list.IndexOf(demand), e); } } if (created.Count == 1) { using (new PXTimeStampScope(null)) { docgraph.Clear(); docgraph.Document.Current = docgraph.Document.Search <POOrder.orderNbr>(created[0].OrderNbr, created[0].OrderType); throw new PXRedirectRequiredException(docgraph, Messages.SOOrder); } } }
//This method executed after customization was published and website was restarted. public override void UpdateDatabase() { #region T200Data RSSVRepairServiceMaint repairServiceGraph = PXGraph.CreateInstance <RSSVRepairServiceMaint>(); #region RSSVRepairService RSSVRepairService repairService = SelectFrom <RSSVRepairService> .View.ReadOnly.Select(repairServiceGraph); if (repairService == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVRepairService.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVRepairService service = new RSSVRepairService { ServiceCD = dic["ServiceCD"], Description = dic["Description"], Active = Convert.ToBoolean(Convert.ToInt32(dic["Active"])), WalkInService = Convert.ToBoolean(Convert.ToInt32(dic["WalkInService"])), Prepayment = Convert.ToBoolean(Convert.ToInt32(dic["Prepayment"])), PreliminaryCheck = Convert.ToBoolean(Convert.ToInt32(dic["PreliminaryCheck"])) }; repairServiceGraph.RepairService.Insert(service); repairServiceGraph.Actions.PressSave(); repairServiceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVRepairService updated"); } } #endregion RSSVDeviceMaint deviceGraph = PXGraph.CreateInstance <RSSVDeviceMaint>(); #region RSSVDevice RSSVDevice servDevice = SelectFrom <RSSVDevice> .View.ReadOnly.Select(deviceGraph); if (servDevice == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVDevice.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVDevice device = new RSSVDevice { DeviceCD = dic["DeviceCD"], Description = dic["Description"], Active = Convert.ToBoolean(Convert.ToInt32(dic["Active"])), AvgComplexityOfRepair = dic["AvgComplexityOfRepair"] }; deviceGraph.ServDevices.Insert(device); deviceGraph.Actions.PressSave(); deviceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVDevice updated"); } } #endregion #endregion #region T210Data var iiEntry = PXGraph.CreateInstance <InventoryItemMaint>(); #region InventoryItem //Add data to InventoryItem //InventoryItem invItem = SelectFrom<InventoryItem>.Where<InventoryItemExt.usrRepairItem.IsEqual<True>>.View.ReadOnly.Select(iiEntry); //if (invItem == null) //{ using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\InventoryItem.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); InventoryItem invItem = SelectFrom <InventoryItem> .Where <InventoryItem.inventoryID.IsEqual <@P.AsInt> > .View.ReadOnly.Select(iiEntry, Convert.ToInt32(dic["InventoryID"])); if (invItem == null) { var iItem = new InventoryItem { InventoryCD = dic["InventoryCD"], ItemClassID = Convert.ToInt32(dic["ItemClassID"]) }; iItem = PXCache <InventoryItem> .CreateCopy(iiEntry.Item.Insert(iItem)); iItem.Descr = dic["Descr"]; iItem.BasePrice = Convert.ToDecimal(dic["BasePrice"]); iItem = PXCache <InventoryItem> .CreateCopy(iiEntry.Item.Update(iItem)); iItem.DfltSiteID = Convert.ToInt32(dic["DfltSiteID"]); iItem = PXCache <InventoryItem> .CreateCopy(iiEntry.Item.Update(iItem)); //var extItem = PXCache<InventoryItem>.GetExtension<InventoryItemExt>(iItem); //extItem.UsrRepairItem = true; //extItem.UsrRepairItemType = dic["UsrRepairItemType"]; //iItem = PXCache<InventoryItem>.CreateCopy(iiEntry.Item.Update(iItem)); iiEntry.Actions.PressSave(); iiEntry.Clear(); } } else { break; } } } this.WriteLog("InventoryItem updated"); } //} #endregion var repairPriceGraph = PXGraph.CreateInstance <RSSVRepairPriceMaint>(); #region RSSVRepairPrice //Add data to RSSVRepairPrice RSSVRepairPrice repairPrice = SelectFrom <RSSVRepairPrice> .View.ReadOnly.Select(repairPriceGraph); if (repairPrice == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVRepairPrice.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVRepairPrice price = new RSSVRepairPrice { DeviceID = Convert.ToInt32(dic["DeviceID"]), ServiceID = Convert.ToInt32(dic["ServiceID"]), Price = Convert.ToDecimal(dic["Price"]), RepairItemLineCntr = Convert.ToInt32(dic["RepairItemLineCntr"]) }; repairPriceGraph.RepairPrices.Insert(price); repairPriceGraph.Actions.PressSave(); repairPriceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVRepairPrice updated"); } } #endregion #region RSSVRepairItem //Add data to RSSVRepairItem RSSVRepairItem repairItem = SelectFrom <RSSVRepairItem> .View.ReadOnly.Select(repairPriceGraph); if (repairItem == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVRepairItem.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVRepairItem item = new RSSVRepairItem { ServiceID = Convert.ToInt32(dic["ServiceID"]), DeviceID = Convert.ToInt32(dic["DeviceID"]), LineNbr = Convert.ToInt32(dic["LineNbr"]), RepairItemType = Convert.ToString(dic["RepairItemType"]), InventoryID = Convert.ToInt32(dic["InventoryID"]), Required = Convert.ToBoolean(Convert.ToInt32(dic["Required"])), IsDefault = Convert.ToBoolean(Convert.ToInt32(dic["IsDefault"])), BasePrice = Convert.ToDecimal(dic["BasePrice"]) }; repairPriceGraph.RepairItems.Insert(item); repairPriceGraph.Actions.PressSave(); repairPriceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVRepairItem updated"); } } #endregion #region RSSVLabor //Add data to RSSVLabor RSSVLabor labor = SelectFrom <RSSVLabor> .View.ReadOnly.Select(repairPriceGraph); if (labor == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVLabor.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVLabor priceLabor = new RSSVLabor { InventoryID = Convert.ToInt32(dic["InventoryID"]), DeviceID = Convert.ToInt32(dic["DeviceID"]), ServiceID = Convert.ToInt32(dic["ServiceID"]), DefaultPrice = Convert.ToDecimal(dic["DefaultPrice"]), Quantity = Convert.ToDecimal(dic["Quantity"]), ExtPrice = Convert.ToDecimal(dic["ExtPrice"]) }; repairPriceGraph.Labor.Insert(priceLabor); repairPriceGraph.Actions.PressSave(); repairPriceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVLabor updated"); } } #endregion #region RSSVWarranty //Add data to RSSVWarranty RSSVWarranty warranty = SelectFrom <RSSVWarranty> .View.ReadOnly.Select(repairPriceGraph); if (warranty == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVWarranty.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVWarranty priceWarranty = new RSSVWarranty { ContractID = Convert.ToInt32(dic["ContractID"]), DeviceID = Convert.ToInt32(dic["DeviceID"]), ServiceID = Convert.ToInt32(dic["ServiceID"]), DefaultWarranty = Convert.ToBoolean(Convert.ToInt32(dic["DefaultWarranty"])) }; repairPriceGraph.Warranty.Insert(priceWarranty); repairPriceGraph.Actions.PressSave(); repairPriceGraph.Clear(); } else { break; } } } this.WriteLog("RSSVWarranty updated"); } } #endregion #endregion #region T220Data & T240Data var setupGraph = PXGraph.CreateInstance <RSSVSetupMaint>(); #region RSSVSetup //Add data to RSSVSetup RSSVSetup setup = SelectFrom <RSSVSetup> .View.ReadOnly.Select(setupGraph); if (setup == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVSetup.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVSetup settings = new RSSVSetup { NumberingID = dic["NumberingID"], WalkInCustomerID = Convert.ToInt32(dic["WalkInCustomerID"]), DefaultEmployee = Guid.Parse(dic["DefaultEmployee"]), PrepaymentPercent = Convert.ToDecimal(dic["PrepaymentPercent"]) }; setupGraph.Setup.Insert(settings); setupGraph.Actions.PressSave(); setupGraph.Clear(); } else { break; } } } this.WriteLog("RSSVSetup updated"); } } #endregion var workOrderGraph = PXGraph.CreateInstance <RSSVWorkOrderEntry>(); #region RSSVWorkOrder //Add data to RSSVWorkOrder RSSVWorkOrder workOrder = SelectFrom <RSSVWorkOrder> .View.ReadOnly.Select(workOrderGraph); if (workOrder == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVWorkOrder.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVWorkOrder order = new RSSVWorkOrder { OrderNbr = dic["OrderNbr"], CustomerID = Convert.ToInt32(dic["CustomerID"]), DateCreated = Convert.ToDateTime(dic["DateCreated"]), Status = dic["Status"], Hold = Convert.ToBoolean(Convert.ToInt32(dic["Hold"])), Description = dic["Description"], DeviceID = Convert.ToInt32(dic["DeviceID"]), ServiceID = Convert.ToInt32(dic["ServiceID"]), //OrderTotal = Convert.ToDecimal(dic["OrderTotal"]), RepairItemLineCntr = Convert.ToInt32(dic["RepairItemLineCntr"]), Priority = dic["Priority"] }; if (dic["DateCompleted"] != "NULL") { order.DateCompleted = Convert.ToDateTime(dic["DateCompleted"]); } //if (dic["InvoiceNbr"] != "NULL") order.InvoiceNbr = dic["InvoiceNbr"]; if (dic["Assignee"] != "NULL") { order.Assignee = Guid.Parse(dic["Assignee"]); } workOrderGraph.WorkOrders.Insert(order); workOrderGraph.Actions.PressSave(); workOrderGraph.Clear(); } else { break; } } } this.WriteLog("RSSVWorkOrder updated"); } } #endregion #region RSSVWorkOrderItem //Add data to RSSVWorkOrderItem RSSVWorkOrderItem workOrderItem = SelectFrom <RSSVWorkOrderItem> .View.ReadOnly.Select(workOrderGraph); if (workOrderItem == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVWorkOrderItem.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); //workOrderGraph.WorkOrders.Current = workOrderGraph.WorkOrders.Search<RSSVWorkOrder.orderNbr>(dic["OrderNbr"]); RSSVWorkOrderItem orderItem = new RSSVWorkOrderItem { OrderNbr = dic["OrderNbr"], LineNbr = Convert.ToInt32(dic["LineNbr"]), RepairItemType = dic["RepairItemType"], InventoryID = Convert.ToInt32(dic["InventoryID"]), BasePrice = Convert.ToDecimal(dic["BasePrice"]) }; workOrderGraph.RepairItems.Insert(orderItem); workOrderGraph.Actions.PressSave(); workOrderGraph.Clear(); } else { break; } } } this.WriteLog("RSSVWorkOrderItem updated"); } } #endregion #region RSSVWorkOrderLabor //Add data to RSSVWorkOrderLabor RSSVWorkOrderLabor workOrderLabor = SelectFrom <RSSVWorkOrderLabor> .View.ReadOnly.Select(workOrderGraph); if (workOrderLabor == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVWorkOrderLabor.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); RSSVWorkOrderLabor laborItem = new RSSVWorkOrderLabor { OrderNbr = dic["OrderNbr"], InventoryID = Convert.ToInt32(dic["InventoryID"]), DefaultPrice = Convert.ToDecimal(dic["DefaultPrice"]), Quantity = Convert.ToDecimal(dic["Quantity"]), ExtPrice = Convert.ToDecimal(dic["ExtPrice"]) }; workOrderGraph.Labor.Insert(laborItem); workOrderGraph.Actions.PressSave(); workOrderGraph.Clear(); } else { break; } } } this.WriteLog("RSSVWorkOrderLabor updated"); } } #endregion #endregion #region T240Data #region RSSVEmployeeWorkOrderQty //Add data to RSSVEmployeeWorkOrderQty RSSVEmployeeWorkOrderQty qty = SelectFrom <RSSVEmployeeWorkOrderQty> .View.ReadOnly.Select(workOrderGraph); if (qty == null) { using (StreamReader file = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "InputData\\RSSVEmployeeWorkOrderQty.csv")) { string header = file.ReadLine(); if (header != null) { string[] headerParts = header.Split(';'); while (true) { string line = file.ReadLine(); if (line != null) { string[] lineParts = line.Split(';'); IDictionary <string, string> dic = headerParts.Select((k, i) => new { k, v = lineParts[i] }).ToDictionary(x => x.k, x => x.v); //we skip graph logic for RSSVEmployeeWorkOrderQty because there is a PXAccumulator attribute for its field PXDatabase.Insert <RSSVEmployeeWorkOrderQty>( new PXDataFieldAssign <RSSVEmployeeWorkOrderQty.userid>(Guid.Parse(dic["UserID"])), new PXDataFieldAssign <RSSVEmployeeWorkOrderQty.nbrOfAssignedOrders>(Convert.ToInt32(dic["NbrOfAssignedOrders"])), new PXDataFieldAssign <RSSVWorkOrder.lastModifiedDateTime>(workOrderGraph.Accessinfo.BusinessDate) ); } else { break; } } } this.WriteLog("RSSVEmployeeWorkOrderQty updated"); } } #endregion #endregion }
private Batch BuildReclassificationBatch(IReadOnlyCollection <ReclassificationItem> transForReclassItems, List <GLTran> transMovedFromExistingBatch, Batch batchForEditing = null) { DateTime earliestNewTranDate = DateTime.MaxValue; Batch batch; if (batchForEditing == null) { batch = JournalEntryInstance.BatchModule.Insert(new Batch()); } else { batch = batchForEditing; JournalEntryInstance.BatchModule.Current = batch; } //adding or editing of transactions foreach (var reclassItem in transForReclassItems) { IEnumerable <GLTranForReclassification> headTranForReclass = IsReclassAttrChanged(reclassItem.HeadTranForReclass) ? reclassItem.HeadTranForReclass.SingleToArray().Union(reclassItem.SplittingTransForReclass) : new GLTranForReclassification[0]; IEnumerable <GLTranForReclassification> tranForReclassToProcess = headTranForReclass.Union(reclassItem.SplittingTransForReclass); foreach (var tranForReclass in tranForReclassToProcess) { GLTran reclassifyingTran = CreateOrEditReclassTranPair(tranForReclass, reclassItem, transMovedFromExistingBatch); if (reclassifyingTran.TranDate < earliestNewTranDate) { earliestNewTranDate = reclassifyingTran.TranDate.Value; } } } //remove deleted trans if (batchForEditing != null) { foreach (var tranForReclassToDel in State.GLTranForReclassToDelete) { var reverseTran = LocateReverseTran(JournalEntryInstance.GLTranModuleBatNbr.Cache, tranForReclassToDel); var reclassifyingTran = LocateReclassifyingTran(JournalEntryInstance.GLTranModuleBatNbr.Cache, tranForReclassToDel); JournalEntryInstance.GLTranModuleBatNbr.Delete(reclassifyingTran); JournalEntryInstance.GLTranModuleBatNbr.Delete(reverseTran); } } var representativeTranForReclass = transForReclassItems.First().HeadTranForReclass; //creating and editing of batch header if (batchForEditing == null) { var batchCuryInfo = PXCache <CurrencyInfo> .CreateCopy(transForReclassItems.First().CuryInfo); batchCuryInfo.CuryInfoID = null; batchCuryInfo = JournalEntryInstance.currencyinfo.Insert(batchCuryInfo); batch.BatchType = BatchTypeCode.Reclassification; batch.BranchID = Accessinfo.BranchID; batch.LedgerID = representativeTranForReclass.LedgerID; batch.Module = BatchModule.GL; batch.CuryInfoID = batchCuryInfo.CuryInfoID; } else { CurrencyInfo firstCuryInfo = null; int? minLineNbr = int.MaxValue; foreach (var item in transForReclassItems) { var reclassTran = item.ReclassifyingTrans.GetItemWithMin(m => m.LineNbr.Value); if (minLineNbr > reclassTran.LineNbr) { minLineNbr = reclassTran.LineNbr; firstCuryInfo = item.CuryInfo; } } var batchCuryInfo = PXCache <CurrencyInfo> .CreateCopy(firstCuryInfo); batchCuryInfo.CuryInfoID = JournalEntryInstance.currencyInfo.CuryInfoID; batchCuryInfo.tstamp = JournalEntryInstance.currencyInfo.tstamp; JournalEntryInstance.currencyinfo.Update(batchCuryInfo); } batch.DateEntered = earliestNewTranDate; batch.FinPeriodID = representativeTranForReclass.FinPeriodID; batch.CuryID = representativeTranForReclass.CuryID; if (State.ReclassScreenMode == ReclassScreenMode.Reversing) { batch.OrigModule = State.OrigBatchModuleToReverse; batch.OrigBatchNbr = State.OrigBatchNbrToReverse; batch.AutoReverseCopy = true; } batch = JournalEntryInstance.BatchModule.Update(batch); return(batch); }
public virtual List <Balance> Run(PMTask task) { if (task.BillingID == null) { throw new PXException(Messages.BillingIDIsNotDefined); } Dictionary <string, Balance> balances = new Dictionary <string, Balance>(); DateTime? lastDate; List <PMTran> expenseTrans = CreateExpenseTransactions(task, out lastDate); List <long> expenseTranIds = new List <long>(); Debug.Print("Created Expense Transactions:"); Debug.Indent(); foreach (PMTran tran in expenseTrans) { expenseTranIds.Add(tran.TranID.Value); Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date); } Debug.Unindent(); if (expenseTrans.Count == 0) { PXTrace.WriteError(Messages.FailedToEmulateExpenses, task.TaskCD); return(new List <Balance>()); } PMAllocator ae = PXGraph.CreateInstance <PMAllocator>(); ae.SourceTransactions = expenseTrans; foreach (PMTran tran in expenseTrans) { ae.Transactions.Insert(tran); } ae.OverrideAllocationDate = lastDate; ae.Execute(task); Debug.Print("After Allocation:"); Debug.Indent(); foreach (PMTran tran in ae.Transactions.Cache.Inserted) { tran.Released = true; Transactions.Cache.Update(tran); if (expenseTranIds.Contains(tran.TranID.Value)) { continue; } int inventoryID = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID; string key = string.Format("{0}.{1}", tran.AccountGroupID, inventoryID); if (!balances.ContainsKey(key)) { Balance b = new Balance(); b.AccountGroupID = tran.AccountGroupID.Value; b.InventoryID = inventoryID; balances.Add(key, b); } Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date); } Debug.Unindent(); DateTime billingDate = lastDate.Value.AddDays(1); //Get ARTrans for Bill: Debug.Print("Bill using the following Billing date={0}", billingDate); PMBillEngine engine = PXGraph.CreateInstance <PMBillEngine>(); engine.IsEmulation = true; engine.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); engine.FieldVerifying.AddHandler <PMTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); Debug.Print("Transactions passed to BillTask:"); Debug.Indent(); foreach (PMTran tran in Transactions.Cache.Cached) { if (expenseTranIds.Contains(tran.TranID.Value)) { continue; } engine.Transactions.Insert(tran); Debug.Print("TranID:{0} AccountGroup:{1}, InventoryID={2}, Qty={3}, Amt={4}, Allocated={5}, Released={6}, Billed={7}, Date={8}", tran.TranID, AccountGroupFromID(tran.AccountGroupID), InventoryFromID(tran.InventoryID), tran.Qty, tran.Amount, tran.Allocated, tran.Released, tran.Billed, tran.Date); } Debug.Unindent(); PMProject project = PXSelect <PMProject, Where <PMProject.contractID, Equal <Required <PMProject.contractID> > > > .Select(this, task.ProjectID); Customer customer = PXSelect <Customer, Where <Customer.bAccountID, Equal <Required <Customer.bAccountID> > > > .Select(this, project.CustomerID); PXSelectBase <PMBillingRule> billingRuleSelect = new PXSelect <PMBillingRule, Where <PMBillingRule.billingID, Equal <Required <PMBillingRule.billingID> > > >(this); List <PMBillingRule> rulesList = new List <PMBillingRule>(); foreach (PMBillingRule rule in billingRuleSelect.Select(task.BillingID)) { rulesList.Add(rule); } engine.billingRules.Add(task.BillingID, rulesList); List <PMBillEngine.BillingData> arTrans = engine.BillTask(project, customer, task, billingDate); //Create ARInvoice to DEFAULT Accounts and SubAccounts. ARInvoiceEntry invoiceEntry = PXGraph.CreateInstance <ARInvoiceEntry>(); //Project and Task is in Planning State - thus suppress verification: invoiceEntry.FieldVerifying.AddHandler <ARInvoice.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); invoiceEntry.FieldVerifying.AddHandler <ARTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); invoiceEntry.FieldVerifying.AddHandler <ARTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); ARInvoice invoice = new ARInvoice(); invoice.DocType = ARDocType.Invoice; invoice = PXCache <ARInvoice> .CreateCopy(invoiceEntry.Document.Insert(invoice)); invoice.DocDate = billingDate; invoice.CustomerID = task.CustomerID; invoice.CustomerLocationID = task.LocationID; invoice.ProjectID = task.ProjectID; invoice = (ARInvoice)invoiceEntry.Document.Update(invoice); CurrencyInfo curyinfo = (CurrencyInfo)invoiceEntry.Caches[typeof(CurrencyInfo)].Current; foreach (PMBillEngine.BillingData data in arTrans) { decimal curyamount; PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, (data.Tran.UnitPrice ?? 0), out curyamount); data.Tran.CuryUnitPrice = curyamount; PXDBCurrencyAttribute.CuryConvCury(invoiceEntry.Caches[typeof(CurrencyInfo)], curyinfo, (data.Tran.ExtPrice ?? 0), out curyamount); data.Tran.CuryExtPrice = curyamount; data.Tran.CuryTranAmt = data.Tran.CuryExtPrice; data.Tran.FreezeManualDisc = true; ARTran newTran = (ARTran)invoiceEntry.Caches[typeof(ARTran)].Insert(data.Tran); } ARInvoice oldInvoice = (ARInvoice)invoiceEntry.Caches[typeof(ARInvoice)].CreateCopy(invoice); invoice.CuryOrigDocAmt = invoice.CuryDocBal; invoiceEntry.Caches[typeof(ARInvoice)].RaiseRowUpdated(invoice, oldInvoice); Debug.Print("AR Trans:"); Debug.Indent(); foreach (ARTran tran in invoiceEntry.Transactions.Select()) { if (tran.TaskID == task.TaskID) { Debug.Print("InventoryID={0}, Qty={1}, Amt={2}", InventoryFromID(tran.InventoryID), tran.Qty, tran.TranAmt); Account acct = PXSelect <Account, Where <Account.accountID, Equal <Required <Account.accountID> > > > .Select(invoiceEntry, tran.AccountID); if (acct.AccountGroupID == null) { throw new PXException(Messages.FailedEmulateBilling); } string key = string.Format("{0}.{1}", acct.AccountGroupID, tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID); if (balances.ContainsKey(key)) { balances[key].Amount += tran.TranAmt ?? 0; balances[key].Quantity += tran.Qty ?? 0; } else { Balance b = new Balance(); b.AccountGroupID = acct.AccountGroupID.Value; b.InventoryID = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID; b.Amount = tran.TranAmt ?? 0; b.Quantity = tran.Qty ?? 0; balances.Add(key, b); } } } return(new List <Balance>(balances.Values)); }
public virtual IEnumerable ReleaseRetainage(PXAdapter adapter) { ARInvoice doc = Base.Document.Current; if (doc != null && doc.DocType == ARDocType.Invoice && doc.RetainageApply == true && doc.CuryRetainageUnreleasedAmt > 0m) { ARRetainageInvoice retainageDoc = RetainageDocuments .Select() .RowCast <ARRetainageInvoice>() .FirstOrDefault(row => row.Released != true); if (retainageDoc != null) { throw new PXException( AP.Messages.ReleaseRetainageNotReleasedDocument, PXMessages.LocalizeNoPrefix(ARDocTypeDict[retainageDoc.DocType]), retainageDoc.RefNbr, PXMessages.LocalizeNoPrefix(ARDocTypeDict[doc.DocType])); } ARRegister reversingDoc; if (Base.CheckReversingRetainageDocumentAlreadyExists(Base.Document.Current, out reversingDoc)) { throw new PXException( AP.Messages.ReleaseRetainageReversingDocumentExists, PXMessages.LocalizeNoPrefix(ARDocTypeDict[doc.DocType]), PXMessages.LocalizeNoPrefix(ARDocTypeDict[reversingDoc.DocType]), reversingDoc.RefNbr); } Base.Save.Press(); RetainageOptions retainageOpts = ReleaseRetainageOptions.Current; WebDialogResult wdr = ReleaseRetainageOptions.AskExt( (graph, view) => { retainageOpts.CuryRetainageTotal = doc.CuryRetainageUnreleasedAmt; retainageOpts.RetainagePct = 100m; retainageOpts.CuryRetainageAmt = doc.CuryRetainageUnreleasedAmt; retainageOpts.CuryRetainageUnreleasedAmt = retainageOpts.CuryRetainageTotal - retainageOpts.CuryRetainageAmt; }, true); if (wdr == WebDialogResult.OK) { ARInvoice invoice = PXCache <ARInvoice> .CreateCopy(doc); try { ReleaseRetainageProc(invoice, retainageOpts); return(new List <ARInvoice> { Base.Document.Current }); } catch (PXException) { Base.Clear(PXClearOption.PreserveTimeStamp); Base.Document.Current = doc; throw; } } } return(adapter.Get()); }
public virtual void ApplyTax(ARInvoice invoice, GetTaxResult result) { TaxZone taxZone = null; AP.Vendor vendor = null; if (result.TaxSummary.Length > 0) { taxZone = (TaxZone)Base.taxzone.View.SelectSingleBound(new object[] { invoice }); vendor = PXSelect <AP.Vendor, Where <AP.Vendor.bAccountID, Equal <Required <AP.Vendor.bAccountID> > > > .Select(Base, taxZone.TaxVendorID); if (vendor == null) { throw new PXException(TX.Messages.ExternalTaxVendorNotFound); } if (vendor.SalesTaxAcctID == null) { throw new PXException(TX.Messages.TaxPayableAccountNotSpecified, vendor.AcctCD); } if (vendor.SalesTaxSubID == null) { throw new PXException(TX.Messages.TaxPayableSubNotSpecified, vendor.AcctCD); } } Sign sign = invoice.DocType == ARDocType.CreditMemo ? Sign.Minus : Sign.Plus; //Clear all existing Tax transactions: foreach (PXResult <ARTaxTran, Tax> res in Base.Taxes.View.SelectMultiBound(new object[] { invoice })) { ARTaxTran taxTran = res; Base.Taxes.Delete(taxTran); } Base.Views.Caches.Add(typeof(Tax)); for (int i = 0; i < result.TaxSummary.Length; i++) { string taxID = result.TaxSummary[i].TaxName; if (string.IsNullOrEmpty(taxID)) { taxID = result.TaxSummary[i].JurisCode; } if (string.IsNullOrEmpty(taxID)) { PXTrace.WriteInformation(Messages.EmptyValuesFromExternalTaxProvider); continue; } //Insert Tax if not exists - just for the selectors sake Tax tx = PXSelect <Tax, Where <Tax.taxID, Equal <Required <Tax.taxID> > > > .Select(Base, taxID); if (tx == null) { tx = new Tax { TaxID = taxID, Descr = PXMessages.LocalizeFormatNoPrefixNLA(TX.Messages.ExternalTaxProviderTaxId, taxID), TaxType = CSTaxType.Sales, TaxCalcType = CSTaxCalcType.Doc, TaxCalcLevel = result.TaxSummary[i].TaxCalculationLevel.ToCSTaxCalcLevel(), TaxApplyTermsDisc = CSTaxTermsDiscount.ToTaxableAmount, SalesTaxAcctID = vendor.SalesTaxAcctID, SalesTaxSubID = vendor.SalesTaxSubID, ExpenseAccountID = vendor.TaxExpenseAcctID, ExpenseSubID = vendor.TaxExpenseSubID, TaxVendorID = taxZone.TaxVendorID, IsExternal = true }; Base.Caches[typeof(Tax)].Insert(tx); } var tax = new ARTaxTran { Module = BatchModule.AR, TranType = invoice.DocType, RefNbr = invoice.RefNbr, TaxID = taxID, CuryTaxAmt = sign * result.TaxSummary[i].TaxAmount, CuryTaxableAmt = sign * result.TaxSummary[i].TaxableAmount, TaxRate = Convert.ToDecimal(result.TaxSummary[i].Rate) * 100, JurisType = result.TaxSummary[i].JurisType, JurisName = result.TaxSummary[i].JurisName, TaxType = CSTaxType.Sales, TaxBucketID = 0, AccountID = vendor.SalesTaxAcctID, SubID = vendor.SalesTaxSubID }; Base.Taxes.Insert(tax); } bool requireControlTotal = Base.ARSetup.Current.RequireControlTotal == true; if (invoice.Hold != true) { Base.ARSetup.Current.RequireControlTotal = false; } try { invoice.CuryTaxTotal = sign * result.TotalTaxAmount; Base.Document.Cache.SetValueExt <ARInvoice.isTaxSaved>(invoice, true); } finally { Base.ARSetup.Current.RequireControlTotal = requireControlTotal; } if (invoice.ApplyPaymentWhenTaxAvailable == true) { PXSelectBase <ARAdjust2> select = new PXSelectJoin <ARAdjust2, InnerJoin <ARPayment, On <ARAdjust2.adjgDocType, Equal <ARPayment.docType>, And <ARAdjust2.adjgRefNbr, Equal <ARPayment.refNbr> > > >, Where <ARAdjust2.adjdDocType, Equal <Required <ARInvoice.docType> >, And <ARAdjust2.adjdRefNbr, Equal <Required <ARInvoice.refNbr> > > > >(Base); decimal amountApplied = 0m; foreach (PXResult <ARAdjust2, ARPayment> res in select.Select(invoice.DocType, invoice.RefNbr)) { ARAdjust2 row = (ARAdjust2)res; ARPayment payment = (ARPayment)res; ARAdjust2 copy = PXCache <ARAdjust2> .CreateCopy(row); amountApplied += (copy.CuryAdjdAmt ?? 0m); if (amountApplied > (invoice.CuryDocBal ?? 0m)) { decimal newAdjdAmt = (copy.CuryAdjdAmt ?? 0m) - (amountApplied - (invoice.CuryDocBal ?? 0m)); copy.CuryAdjdAmt = newAdjdAmt > 0m ? newAdjdAmt : 0m; } Base.Adjustments.Update(copy); } } }
private void CreateActivity() { PXCache cache = _graph.Caches[typeof(PX.Objects.CR.EPActivity)]; _message = (EPActivity)cache.CreateCopy(cache.Insert()); _message.ClassID = CRActivityClass.Email; _message.Type = null; _message.IsBillable = false; _message.MailAccountID = _account.EmailAccountID; var mimeMessage = _email.Message; _message.MailFrom = mimeMessage.From.With(_ => _.ToString()) ?? string.Empty; _message.MailReply = mimeMessage.ReplyTo.With(_ => _.ToString()) ?? string.Empty; _message.MailTo = mimeMessage.To.With(_ => _.ToString()) ?? string.Empty; _message.MailCc = mimeMessage.Cc.With(_ => _.ToString()) ?? string.Empty; _message.MailBcc = mimeMessage.Bcc.With(_ => _.ToString()) ?? string.Empty; _message.Subject = mimeMessage.Subject.With(_ => _.ToString()) ?? " "; if (!string.IsNullOrEmpty(_email.UID)) { if (_account.IncomingHostProtocol == IncomingMailProtocolsAttribute._IMAP) { _message.ImapUID = int.Parse(_email.UID); } else { _message.Pop3UID = _email.UID; } } _message.StartDate = _email.Message.Date; _message.IsIncome = true; _message.MessageId = mimeMessage.MessageID; _message.MPStatus = MailStatusListAttribute.PreProcess; //TODO: need move into Automation steps _message.IsBillable = false; var body = mimeMessage.BodyHtmlText; if (body == null) { if (mimeMessage.BodyText != null) { body = PX.Common.Tools.ConvertSimpleTextToHtml(mimeMessage.BodyText); } } else { body = mimeMessage.BodyHtmlText. Replace(Environment.NewLine, " "). Replace("<spanstyle", "<span style"); //NOTE: ms outlook style conflicts with our system style Regex baseTag = new Regex(@"<base(.|\n)*?>"); body = baseTag.Replace(body, String.Empty); } _message.Body = body ?? string.Empty; string clearedSubject; var ticket = DecodeTicket(_message.Subject, out clearedSubject); if (ticket != null) { _message.Ticket = CorrectTicket(ticket); } _message.Subject = clearedSubject; UpdateMessage(); }
public virtual void GenerateProc(Schedule schedule, short times, DateTime runDate) { string lastBatchNbr = "0000000000"; long lastInfoID = -1; IEnumerable <ScheduleDet> occurrences = new Scheduler(this).MakeSchedule(schedule, times, runDate); using (PXTransactionScope ts = new PXTransactionScope()) { foreach (ScheduleDet occurrence in occurrences) { foreach (BatchNew scheduledBatch in PXSelect < BatchNew, Where < BatchNew.scheduleID, Equal <Optional <Schedule.scheduleID> >, And <BatchNew.scheduled, Equal <boolTrue> > > > .Select(this, schedule.ScheduleID)) { BatchNew copy = PXCache <BatchNew> .CreateCopy(scheduledBatch); copy.OrigBatchNbr = copy.BatchNbr; copy.OrigModule = copy.Module; copy.CuryInfoID = null; copy.NumberCode = "GLREC"; copy.NoteID = null; CurrencyInfo info = (CurrencyInfo)PXSelect < CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(this, scheduledBatch.CuryInfoID); if (info != null) { CurrencyInfo infocopy = PXCache <CurrencyInfo> .CreateCopy(info); infocopy.CuryInfoID = lastInfoID; copy.CuryInfoID = lastInfoID; CuryInfo_Created.Cache.Insert(infocopy); } copy.Posted = false; copy.Released = false; copy.Status = BatchStatus.Balanced; copy.Scheduled = false; copy.AutoReverseCopy = false; copy.DateEntered = occurrence.ScheduledDate; copy.FinPeriodID = occurrence.ScheduledPeriod; copy.TranPeriodID = null; copy.BatchNbr = lastBatchNbr; copy.RefBatchNbr = lastBatchNbr; lastBatchNbr = AutoNumberAttribute.NextNumber(lastBatchNbr); lastInfoID--; copy = (BatchNew)Batch_Created.Cache.Insert(copy); CurrencyInfoAttribute.SetEffectiveDate <Batch.dateEntered>(Batch_Created.Cache, new PXFieldUpdatedEventArgs(copy, null, false)); PXNoteAttribute.CopyNoteAndFiles(Caches[typeof(BatchNew)], scheduledBatch, Batch_Created.Cache, copy); foreach (GLTranNew scheduledBatchTransaction in PXSelect < GLTranNew, Where < GLTranNew.module, Equal <Required <GLTranNew.module> >, And <GLTranNew.batchNbr, Equal <Required <GLTranNew.batchNbr> > > > > .Select(this, scheduledBatch.Module, scheduledBatch.BatchNbr)) { GLTranNew transactionCopy = PXCache <GLTranNew> .CreateCopy(scheduledBatchTransaction); transactionCopy.OrigBatchNbr = transactionCopy.BatchNbr; transactionCopy.OrigModule = transactionCopy.Module; transactionCopy.BatchNbr = copy.BatchNbr; transactionCopy.RefBatchNbr = copy.RefBatchNbr; transactionCopy.CuryInfoID = copy.CuryInfoID; transactionCopy.CATranID = null; transactionCopy.TranDate = occurrence.ScheduledDate; transactionCopy.FinPeriodID = occurrence.ScheduledPeriod; transactionCopy.TranPeriodID = occurrence.ScheduledPeriod; Tran_Created.Cache.Insert(transactionCopy); } } schedule.LastRunDate = occurrence.ScheduledDate; Running_Schedule.Cache.Update(schedule); } Running_Schedule.Cache.Persist(PXDBOperation.Update); Batch_Created.Cache.Persist(PXDBOperation.Insert); Batch_Created.Cache.Persist(PXDBOperation.Update); foreach (GLTranNew createdTransaction in Tran_Created.Cache.Inserted) { foreach (BatchNew createdBatch in Batch_Created.Cache.Cached) { if (object.Equals(createdBatch.RefBatchNbr, createdTransaction.RefBatchNbr)) { createdTransaction.BatchNbr = createdBatch.BatchNbr; createdTransaction.CuryInfoID = createdBatch.CuryInfoID; if (!string.IsNullOrEmpty(createdBatch.RefNbr)) { createdTransaction.RefNbr = createdBatch.RefNbr; } break; } } } Tran_Created.Cache.Normalize(); Tran_Created.Cache.Persist(PXDBOperation.Insert); Tran_Created.Cache.Persist(PXDBOperation.Update); Caches[typeof(CA.CADailySummary)].Persist(PXDBOperation.Insert); ts.Complete(this); } Running_Schedule.Cache.Persisted(false); Batch_Created.Cache.Persisted(false); Tran_Created.Cache.Persisted(false); Caches[typeof(CA.CADailySummary)].Persisted(false); }
protected virtual void AdjustMethodLines(FADepreciationMethod meth) { if (meth.UsefulLife == null || meth.AveragingConvention == null || meth.AveragingConvPeriod == null) { return; } int periodFactor; switch (meth.AveragingConvention) { case FAAveragingConvention.HalfYear: case FAAveragingConvention.FullYear: periodFactor = 12; break; case FAAveragingConvention.HalfQuarter: case FAAveragingConvention.FullQuarter: periodFactor = 3; break; default: periodFactor = 1; break; } int offsetPeriods = ((int)meth.AveragingConvPeriod - 1) * periodFactor; int periods = (int)Math.Ceiling((decimal)meth.UsefulLife * 12 + offsetPeriods); if (meth.AveragingConvention == FAAveragingConvention.HalfYear || meth.AveragingConvention == FAAveragingConvention.HalfQuarter || meth.AveragingConvention == FAAveragingConvention.HalfPeriod || meth.AveragingConvention == FAAveragingConvention.ModifiedPeriod || meth.AveragingConvention == FAAveragingConvention.ModifiedPeriod2 || meth.AveragingConvention == FAAveragingConvention.NextPeriod ) { periods++; } int years = (int)Math.Ceiling(periods / 12d); List <FADepreciationMethodLines> lines = PXSelect <FADepreciationMethodLines, Where <FADepreciationMethodLines.methodID, Equal <Current <FADepreciationMethod.methodID> > > > .Select(this) .RowCast <FADepreciationMethodLines>() .ToList(); if (years != lines.Count) { decimal oldTotalRate = 0m; decimal newTotalRate = 0m; int count = 0; FADepreciationMethodLines lastLine = null; lines.Sort((line1, line2) => (line1.Year ?? 0m).CompareTo(line2.Year ?? 0m)); foreach (FADepreciationMethodLines line in lines) { oldTotalRate += line.RatioPerYear ?? 0m; count++; if (count > years) { details.Delete(PXCache <FADepreciationMethodLines> .CreateCopy(line)); } else { lastLine = PXCache <FADepreciationMethodLines> .CreateCopy(line); newTotalRate += line.RatioPerYear ?? 0m; } } if (count > years && lastLine != null) { lastLine.RatioPerYear += oldTotalRate - newTotalRate; lastLine = details.Update(lastLine); details.Cache.SetDefaultExt <FADepreciationMethodLines.displayRatioPerYear>(lastLine); } else { for (int year_num = count + 1; year_num <= years; year_num++) { details.Insert(new FADepreciationMethodLines { Year = year_num, RatioPerYear = 0m }); } } } }
public static void ReleaseDoc(EPExpenseClaim claim) { #region prepare required variables APInvoiceEntry docgraph = PXGraph.CreateInstance <APInvoiceEntry>(); ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>(); EPExpenseClaim checkClaim = PXSelect <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr); if (checkClaim.Released == true) { throw new PXException(Messages.AlreadyReleased); } var receiptsResult = PXSelect <EPExpenseClaimDetails, Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr); IFinPeriodUtils finPeriodUtils = expenseClaimGraph.GetService <IFinPeriodUtils>(); if (claim.FinPeriodID != null) { finPeriodUtils.ValidateFinPeriod <EPExpenseClaimDetails>(receiptsResult.RowCast <EPExpenseClaimDetails>(), m => claim.FinPeriodID, m => m.BranchID.SingleToArray()); } var receipts = receiptsResult.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 if (claim.FinPeriodID != null) { finPeriodUtils.ValidateFinPeriod(claim.SingleToArray()); } 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; if (claim.FinPeriodID == null) { APOpenPeriodAttribute.DefaultFirstOpenPeriod <APInvoice.finPeriodID>(docgraph.Document.Cache); } else { 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>(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 == CT.CTPRType.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, expenseClaimGraph, 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, 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 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; } invoice.Approved = true; 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); } }