public SurveyGenerator() : this(PXGraph.CreateInstance <SurveyMaint>()) { }
public static void ReleaseDoc(CABatch aDocument) { if ((bool)aDocument.Released || (bool)aDocument.Hold) { throw new PXException(CA.Messages.CABatchStatusIsNotValidForProcessing); } ARBatchUpdate batchEntry = PXGraph.CreateInstance <ARBatchUpdate>(); CABatch document = batchEntry.Document.Select(aDocument.BatchNbr); batchEntry.Document.Current = document; if ((bool)document.Released || (bool)document.Hold) { throw new PXException(CA.Messages.CABatchStatusIsNotValidForProcessing); } ARPayment voided = PXSelectReadonly2 <ARPayment, InnerJoin <CABatchDetail, On <CABatchDetail.origDocType, Equal <ARPayment.docType>, And <CABatchDetail.origRefNbr, Equal <ARPayment.refNbr>, And <CABatchDetail.origModule, Equal <GL.BatchModule.moduleAR> > > > >, Where <CABatchDetail.batchNbr, Equal <Required <CABatch.batchNbr> >, And <ARPayment.voided, Equal <True> > > > .Select(batchEntry, document.BatchNbr); if (voided != null && string.IsNullOrEmpty(voided.RefNbr) == false) { throw new PXException(CA.Messages.CABatchContainsVoidedPaymentsAndConnotBeReleased); } List <ARRegister> unreleasedList = new List <ARRegister>(); PXSelectBase <ARPayment> selectUnreleased = new PXSelectReadonly2 <ARPayment, InnerJoin <CABatchDetail, On <CABatchDetail.origDocType, Equal <ARPayment.docType>, And <CABatchDetail.origRefNbr, Equal <ARPayment.refNbr>, And <CABatchDetail.origModule, Equal <GL.BatchModule.moduleAR> > > > >, Where <CABatchDetail.batchNbr, Equal <Optional <CABatch.batchNbr> >, And <ARPayment.released, Equal <boolFalse> > > >(batchEntry); foreach (ARPayment item in selectUnreleased.Select(document.BatchNbr)) { if (item.Released != true) { unreleasedList.Add(item); } } if (unreleasedList.Count > 0) { ARDocumentRelease.ReleaseDoc(unreleasedList, true); } selectUnreleased.View.Clear(); ARPayment payment = selectUnreleased.Select(document.BatchNbr); if (payment != null) { throw new PXException(CA.Messages.CABatchContainsUnreleasedPaymentsAndCannotBeReleased); } document.Released = true; document.DateSeqNbr = CABatchEntry.GetNextDateSeqNbr(batchEntry, aDocument); //Nothing AP specific in this static function batchEntry.RecalcTotals(); document = batchEntry.Document.Update(document); batchEntry.Actions.PressSave(); }
public static void RunRecognition(List <ScheduledTran> trans, DateTime?filterDate) { ScheduleMaint scheduleMaint = PXGraph.CreateInstance <ScheduleMaint>(); scheduleMaint.Clear(); bool failed = false; List <ScheduledTran> items = GetValidatedItems(trans, scheduleMaint); failed = items.Count() < trans.Count(); // Save virtual records: // - foreach (ScheduledTran tr in items) { PXProcessing <ScheduledTran> .SetCurrentItem(tr); if (tr.IsVirtual == true) { try { scheduleMaint.Document.Current = PXSelect <DRScheduleDetail, Where <DRScheduleDetail.scheduleID, Equal <Required <DRScheduleDetail.scheduleID> >, And <DRScheduleDetail.componentID, Equal <Required <DRScheduleDetail.componentID> >, And <DRScheduleDetail.detailLineNbr, Equal <Required <DRScheduleDetail.detailLineNbr> > > > > > .Select(scheduleMaint, tr.ScheduleID, tr.ComponentID ?? DRScheduleDetail.EmptyComponentID, tr.DetailLineNbr); DRScheduleTran tran = new DRScheduleTran(); tran.BranchID = tr.BranchID; tran.AccountID = tr.AccountID; tran.SubID = tr.SubID; tran.AdjgDocType = tr.AdjgDocType; tran.AdjgRefNbr = tr.AdjgRefNbr; tran.AdjNbr = tr.AdjNbr; tran.Amount = tr.Amount; tran.ComponentID = tr.ComponentID ?? DRScheduleDetail.EmptyComponentID; tran.DetailLineNbr = tr.DetailLineNbr; tran.FinPeriodID = tr.FinPeriodID; tran.ScheduleID = tr.ScheduleID; tran.RecDate = tr.RecDate; tran.Status = DRScheduleTranStatus.Open; tran = scheduleMaint.OpenTransactions.Insert(tran); tr.LineNbr = tran.LineNbr; scheduleMaint.RebuildProjections(); scheduleMaint.Save.Press(); byte[] ts = scheduleMaint.TimeStamp; scheduleMaint.Clear(); scheduleMaint.TimeStamp = ts; PXProcessing <ScheduledTran> .SetProcessed(); } catch (Exception ex) { failed = true; PXProcessing <ScheduledTran> .SetError(ex.Message); } } else { PXProcessing <ScheduledTran> .SetProcessed(); } } PXProcessing <ScheduledTran> .SetCurrentItem(null); List <DRBatch> list = SplitByFinPeriod(items); DRProcess process = CreateInstance <DRProcess>(); process.Clear(); process.TimeStamp = scheduleMaint.TimeStamp; List <Batch> batchlist = process.RunRecognition(list, filterDate); PostGraph pg = PXGraph.CreateInstance <PostGraph>(); //Post Batches if AutoPost bool postFailed = false; if (pg.AutoPost) { foreach (Batch batch in batchlist) { try { pg.Clear(); pg.TimeStamp = batch.tstamp; pg.PostBatchProc(batch); } catch (Exception) { postFailed = true; } } if (postFailed) { throw new PXException(Messages.AutoPostFailed); } } if (failed) { throw new PXException(GL.Messages.DocumentsNotReleased); } }
public static void UpdateDiscount(string discountID, string discountSequenceID, DateTime?filterDate) { UpdateDiscountProcess graph = PXGraph.CreateInstance <UpdateDiscountProcess>(); graph.UpdateDiscount(discountID, discountSequenceID, filterDate); }
public virtual List <APRegister> ReleaseClaimDetails <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension> (ExpenseClaimEntry expenseClaimGraph, EPExpenseClaim claim, IEnumerable <EPExpenseClaimDetails> receipts, string receiptGroupPaidWithType) where TGraph : PXGraph, new() where TAPDocument : InvoiceBase, new() where TInvoiceMapping : IBqlMapping where TAPDocumentGraphExtension : PX.Objects.Common.GraphExtensions.Abstract.InvoiceBaseGraphExtension <TGraph, TAPDocument, TInvoiceMapping> { #region prepare required variable var docgraph = PXGraph.CreateInstance <TGraph>(); EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(docgraph); TAPDocumentGraphExtension apDocumentGraphExtension = docgraph.FindImplementation <TAPDocumentGraphExtension>(); List <List <EPExpenseClaimDetails> > receiptsForDocument = new List <List <EPExpenseClaimDetails> >(); if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount) { receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode }) .Select(group => group.ToList()) .ToList(); } else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense) { if (epsetup.PostSummarizedCorpCardExpenseReceipts == true) { receiptsForDocument = receipts.GroupBy(item => new { item.TaxZoneID, item.TaxCalcMode, item.CorpCardID, item.ExpenseDate, item.ExpenseRefNbr }) .Select(group => group.ToList()) .ToList(); } else { receiptsForDocument = receipts.Select(receipt => receipt.SingleToList()).ToList(); } } else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense) { receiptsForDocument = new List <List <EPExpenseClaimDetails> >() { receipts.ToList() }; } else { throw new NotImplementedException(); } if (!receiptsForDocument.Any()) { receiptsForDocument.Add(new List <EPExpenseClaimDetails>()); } APSetup apsetup = PXSelectReadonly <APSetup> .Select(docgraph); EPEmployee employee = PXSelect <EPEmployee, Where <EPEmployee.bAccountID, Equal <Required <EPExpenseClaim.employeeID> > > > .Select(docgraph, claim.EmployeeID); Location emplocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <EPExpenseClaim.employeeID> >, And <Location.locationID, Equal <Required <EPExpenseClaim.locationID> > > > > .Select(docgraph, claim.EmployeeID, claim.LocationID); List <APRegister> doclist = new List <APRegister>(); expenseClaimGraph.SelectTimeStamp(); if (claim.FinPeriodID != null) { FinPeriodUtils.ValidateFinPeriod(claim.SingleToArray()); } #endregion foreach (var receiptGroup in receiptsForDocument) { if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense && receiptGroup.Count > 1) { EPExpenseClaimDetails[] matchedReceipts = receiptGroup.Where(receipt => receipt.BankTranDate != null).Take(11).ToArray(); if (matchedReceipts.Any()) { PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran>[] rows = PXSelectJoin <EPExpenseClaimDetails, InnerJoin <CABankTranMatch, On <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>, And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>, And <CABankTranMatch.docRefNbr, Equal <EPExpenseClaimDetails.claimDetailCD> > > >, InnerJoin <CABankTran, On <CABankTran.tranID, Equal <CABankTranMatch.tranID> > > >, Where <EPExpenseClaimDetails.claimDetailCD, In <Required <EPExpenseClaimDetails.claimDetailCD> > > > .Select(expenseClaimGraph, matchedReceipts.Select(receipt => receipt.ClaimDetailCD).ToArray()) .Cast <PXResult <EPExpenseClaimDetails, CABankTranMatch, CABankTran> >() .ToArray(); throw new PXException(Messages.ExpenseReceiptCannotBeSummarized, rows.Select(row => String.Concat(PXMessages.LocalizeNoPrefix(Messages.Receipt), " ", ((EPExpenseClaimDetails)row).ClaimDetailCD, " - ", ((CABankTran)row).GetFriendlyKeyImage(Caches[typeof(CABankTran)]))) .ToArray() .JoinIntoStringForMessageNoQuotes(maxCount: 10)); } } docgraph.Clear(PXClearOption.ClearAll); docgraph.SelectTimeStamp(); apDocumentGraphExtension.Contragent.Current = apDocumentGraphExtension.Contragent.Cache.GetExtension <Contragent>(employee); apDocumentGraphExtension.Location.Current = emplocation; CurrencyInfo infoOriginal = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <EPExpenseClaim.curyInfoID> > > > .Select(docgraph, claim.CuryInfoID); CurrencyInfo info = PXCache <CurrencyInfo> .CreateCopy(infoOriginal); info.CuryInfoID = null; info = apDocumentGraphExtension.CurrencyInfo.Insert(info); #region CreateInvoiceHeader var invoice = new TAPDocument(); CABankTranMatch bankTranMatch = null; if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount) { invoice.DocType = receiptGroup.Sum(_ => _.ClaimCuryTranAmtWithTaxes) < 0 ? APInvoiceType.DebitAdj : APInvoiceType.Invoice; } else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense) { EPExpenseClaimDetails receipt = receiptGroup.First(); invoice.DocType = APDocType.QuickCheck; CACorpCard card = CACorpCard.PKID.Find(this, receipt.CorpCardID); PaymentMethodAccount paymentMethodAccount = PXSelect <PaymentMethodAccount, Where <PaymentMethodAccount.cashAccountID, Equal <Required <PaymentMethodAccount.cashAccountID> > > > .Select(this, card.CashAccountID); invoice.CashAccountID = card.CashAccountID; invoice.PaymentMethodID = paymentMethodAccount.PaymentMethodID; invoice.ExtRefNbr = receipt.ExpenseRefNbr; if (receiptGroup.Count == 1) { bankTranMatch = PXSelect <CABankTranMatch, Where <CABankTranMatch.docModule, Equal <BatchModule.moduleEP>, And <CABankTranMatch.docType, Equal <EPExpenseClaimDetails.docType>, And <CABankTranMatch.docRefNbr, Equal <Required <CABankTranMatch.docRefNbr> > > > > > .Select(expenseClaimGraph, receipt.ClaimDetailCD); if (bankTranMatch != null) { CABankTran bankTran = CABankTran.PK.Find(expenseClaimGraph, bankTranMatch.TranID); invoice.ClearDate = bankTran.ClearDate; invoice.Cleared = true; } } } else if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense) { invoice.DocType = APDocType.DebitAdj; } else { throw new NotImplementedException(); } invoice.CuryInfoID = info.CuryInfoID; invoice.Hold = true; invoice.Released = false; invoice.Printed = invoice.DocType == APDocType.QuickCheck; invoice.OpenDoc = true; invoice.HeaderDocDate = claim.DocDate; invoice.FinPeriodID = claim.FinPeriodID; invoice.InvoiceNbr = claim.RefNbr; invoice.DocDesc = claim.DocDesc; invoice.ContragentID = claim.EmployeeID; invoice.CuryID = info.CuryID; invoice.ContragentLocationID = claim.LocationID; invoice.ModuleAccountID = emplocation != null ? emplocation.APAccountID : null; invoice.ModuleSubID = emplocation != null ? emplocation.APSubID : null; invoice.TaxCalcMode = receiptGroup.Any() ? receiptGroup.First().TaxCalcMode: claim.TaxCalcMode; invoice.BranchID = claim.BranchID; invoice.OrigModule = BatchModule.EP; if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense && receiptGroup.Count == 1) { invoice.OrigDocType = EPExpenseClaimDetails.DocType; invoice.OrigRefNbr = receiptGroup.Single().ClaimDetailCD; } else { invoice.OrigDocType = EPExpenseClaim.DocType; invoice.OrigRefNbr = claim.RefNbr; } bool reversedDocument = invoice.DocType == APInvoiceType.DebitAdj && receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.PersonalAccount; decimal signOperation = reversedDocument ? -1 : 1; invoice = apDocumentGraphExtension.Documents.Insert(invoice); (apDocumentGraphExtension.Documents.Cache as PXModelExtension <TAPDocument>)?.UpdateExtensionMapping(invoice, MappingSyncDirection.BaseToExtension); invoice.TaxZoneID = receiptGroup.Any() ? receiptGroup.First().TaxZoneID : claim.TaxZoneID; invoice = apDocumentGraphExtension.Documents.Update(invoice); PXCache <CurrencyInfo> .RestoreCopy(info, infoOriginal); info.CuryInfoID = invoice.CuryInfoID; PXCache claimcache = docgraph.Caches[typeof(EPExpenseClaim)]; PXCache claimdetailcache = docgraph.Caches[typeof(EPExpenseClaimDetails)]; PXNoteAttribute.CopyNoteAndFiles(claimcache, claim, apDocumentGraphExtension.Documents.Cache, invoice, epsetup.GetCopyNoteSettings <PXModule.ap>()); #endregion TaxAttribute.SetTaxCalc <InvoiceTran.taxCategoryID>(apDocumentGraphExtension.InvoiceTrans.Cache, null, TaxCalc.ManualCalc); decimal?claimCuryTaxRoundDiff = 0m; decimal?claimTaxRoundDiff = 0m; foreach (EPExpenseClaimDetails claimdetail in receiptGroup) { #region AddDetails decimal tipQty; if (reversedDocument == claimdetail.ClaimCuryTranAmtWithTaxes < 0) { tipQty = 1; } else { tipQty = -1; } Contract contract = PXSelect <Contract, Where <Contract.contractID, Equal <Required <EPExpenseClaimDetails.contractID> > > > .SelectSingleBound(docgraph, null, claimdetail.ContractID); if (claimdetail.TaskID != null) { PMTask task = PXSelect <PMTask, Where <PMTask.taskID, Equal <Required <PMTask.taskID> > > > .Select(expenseClaimGraph, claimdetail.TaskID); if (task != null && !(bool)task.VisibleInAP) { throw new PXException(PM.Messages.TaskInvisibleInModule, task.TaskCD, BatchModule.AP); } } InvoiceTran tran = new InvoiceTran(); tran.InventoryID = claimdetail.InventoryID; tran.TranDesc = claimdetail.TranDesc; decimal unitCost; decimal amount; decimal taxableAmt; decimal taxAmt; if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID)) { unitCost = claimdetail.CuryUnitCost ?? 0m; amount = claimdetail.CuryTaxableAmt ?? 0m; taxableAmt = claimdetail.CuryTaxableAmtFromTax ?? 0m; taxAmt = claimdetail.CuryTaxAmt ?? 0m; } else { if (claimdetail.CuryUnitCost == null || claimdetail.CuryUnitCost == 0m) { unitCost = 0m; } else { PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.UnitCost, out unitCost); } if (claimdetail.CuryTaxableAmt == null || claimdetail.CuryTaxableAmt == 0m) { amount = 0m; } else { PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmt, out amount); } if (claimdetail.CuryTaxableAmtFromTax == null || claimdetail.CuryTaxableAmtFromTax == 0m) { taxableAmt = 0m; } else { PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxableAmtFromTax, out taxableAmt); } if (claimdetail.CuryTaxAmt == null || claimdetail.CuryTaxAmt == 0m) { taxAmt = 0m; } else { PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TaxAmt, out taxAmt); } } tran.ManualPrice = true; tran.CuryUnitCost = unitCost; tran.Qty = claimdetail.Qty * signOperation; tran.UOM = claimdetail.UOM; tran.NonBillable = claimdetail.Billable != true; claimCuryTaxRoundDiff += (claimdetail.ClaimCuryTaxRoundDiff ?? 0m) * signOperation; claimTaxRoundDiff += (claimdetail.ClaimTaxRoundDiff ?? 0m) * signOperation; tran.Date = claimdetail.ExpenseDate; if (contract.BaseType == CT.CTPRType.Project) { tran.ProjectID = claimdetail.ContractID; } else { tran.ProjectID = ProjectDefaultAttribute.NonProject(); } tran.TaskID = claimdetail.TaskID; tran.CostCodeID = claimdetail.CostCodeID; if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardPersonalExpense) { CACorpCard card = CACorpCard.PKID.Find(this, claimdetail.CorpCardID); CashAccount cashAccount = CashAccount.PK.Find(this, card.CashAccountID); tran.AccountID = cashAccount.AccountID; tran.SubID = cashAccount.SubID; } else { tran.AccountID = claimdetail.ExpenseAccountID; tran.SubID = claimdetail.ExpenseSubID; } tran.BranchID = claimdetail.BranchID; tran = InsertInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran, new InvoiceTranContext { EPClaim = claim, EPClaimDetails = claimdetail }); if (claimdetail.PaidWith == EPExpenseClaimDetails.paidWith.CardPersonalExpense) { claimdetail.APLineNbr = tran.LineNbr; } tran.CuryLineAmt = amount * signOperation; tran.CuryTaxAmt = 0; tran.CuryTaxableAmt = taxableAmt * signOperation; tran.CuryTaxAmt = taxAmt * signOperation; tran.TaxCategoryID = claimdetail.TaxCategoryID; tran = UpdateInvoiceTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tran, new InvoiceTranContext { EPClaim = claim, EPClaimDetails = claimdetail }); if ((claimdetail.CuryTipAmt ?? 0) != 0) { InvoiceTran tranTip = new InvoiceTran(); if (epsetup.NonTaxableTipItem == null) { throw new PXException(Messages.TipItemIsNotDefined); } IN.InventoryItem tipItem = PXSelect <IN.InventoryItem, Where <IN.InventoryItem.inventoryID, Equal <Required <IN.InventoryItem.inventoryID> > > > .Select(docgraph, epsetup.NonTaxableTipItem); if (tipItem == null) { string fieldname = PXUIFieldAttribute.GetDisplayName <EPSetup.nonTaxableTipItem>(docgraph.Caches[typeof(EPSetup)]); throw new PXException(ErrorMessages.ValueDoesntExistOrNoRights, fieldname, epsetup.NonTaxableTipItem); } tranTip.InventoryID = epsetup.NonTaxableTipItem; tranTip.TranDesc = tipItem.Descr; if (CurrencyHelper.IsSameCury(expenseClaimGraph, claimdetail.CuryInfoID, claimdetail.ClaimCuryInfoID)) { tranTip.CuryUnitCost = Math.Abs(claimdetail.CuryTipAmt ?? 0m); tranTip.CuryTranAmt = claimdetail.CuryTipAmt * signOperation; } else { decimal tipAmt; PXCurrencyAttribute.CuryConvCury <EPExpenseClaimDetails.claimCuryInfoID>(expenseClaimGraph.ExpenseClaimDetails.Cache, claimdetail, (decimal)claimdetail.TipAmt, out tipAmt); tranTip.CuryUnitCost = Math.Abs(tipAmt); tranTip.CuryTranAmt = tipAmt * signOperation; } tranTip.Qty = tipQty; tranTip.UOM = tipItem.BaseUnit; tranTip.NonBillable = claimdetail.Billable != true; tranTip.Date = claimdetail.ExpenseDate; tranTip.BranchID = claimdetail.BranchID; tranTip = InsertInvoiceTipTransaction(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip, new InvoiceTranContext { EPClaim = claim, EPClaimDetails = claimdetail }); if (epsetup.UseReceiptAccountForTips == true) { tranTip.AccountID = claimdetail.ExpenseAccountID; tranTip.SubID = claimdetail.ExpenseSubID; } else { tranTip.AccountID = tipItem.COGSAcctID; Location companyloc = (Location)PXSelectJoin <Location, InnerJoin <BAccountR, On <Location.bAccountID, Equal <BAccountR.bAccountID>, And <Location.locationID, Equal <BAccountR.defLocationID> > >, InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >, Where <GL.Branch.branchID, Equal <Current <APInvoice.branchID> > > > .Select(docgraph); PMTask task = PXSelect <PMTask, Where <PMTask.projectID, Equal <Required <PMTask.projectID> >, And <PMTask.taskID, Equal <Required <PMTask.taskID> > > > > .Select(docgraph, claimdetail.ContractID, claimdetail.TaskID); Location customerLocation = (Location)PXSelectorAttribute.Select <EPExpenseClaimDetails.customerLocationID>(claimdetailcache, claimdetail); int?employee_SubID = (int?)docgraph.Caches[typeof(EPEmployee)].GetValue <EPEmployee.expenseSubID>(employee); int?item_SubID = (int?)docgraph.Caches[typeof(IN.InventoryItem)].GetValue <IN.InventoryItem.cOGSSubID>(tipItem); int?company_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cMPExpenseSubID>(companyloc); int?project_SubID = (int?)docgraph.Caches[typeof(Contract)].GetValue <Contract.defaultSubID>(contract); int?task_SubID = (int?)docgraph.Caches[typeof(PMTask)].GetValue <PMTask.defaultSubID>(task); int?location_SubID = (int?)docgraph.Caches[typeof(Location)].GetValue <Location.cSalesSubID>(customerLocation); object value = SubAccountMaskAttribute.MakeSub <EPSetup.expenseSubMask>(docgraph, epsetup.ExpenseSubMask, new object[] { employee_SubID, item_SubID, company_SubID, project_SubID, task_SubID, location_SubID }, new Type[] { typeof(EPEmployee.expenseSubID), typeof(IN.InventoryItem.cOGSSubID), typeof(Location.cMPExpenseSubID), typeof(Contract.defaultSubID), typeof(PMTask.defaultSubID), typeof(Location.cSalesSubID) }); docgraph.Caches[typeof(APTran)].RaiseFieldUpdating <APTran.subID>(tranTip, ref value); tranTip.SubID = (int?)value; } tranTip = UpdateInvoiceTipTransactionAccounts(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip, new InvoiceTranContext { EPClaim = claim, EPClaimDetails = claimdetail }); tranTip.TaxCategoryID = tipItem.TaxCategoryID; tranTip.ProjectID = tran.ProjectID; tranTip.TaskID = tran.TaskID; tranTip = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tranTip, true); tranTip = UpdateInvoiceTipTransactionTaxesAndProject(apDocumentGraphExtension.InvoiceTrans.Cache, tranTip, new InvoiceTranContext { EPClaim = claim, EPClaimDetails = claimdetail }); } PXNoteAttribute.CopyNoteAndFiles(claimdetailcache, claimdetail, apDocumentGraphExtension.InvoiceTrans.Cache, tran, epsetup.GetCopyNoteSettings <PXModule.ap>()); claimdetail.Released = true; expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail); #endregion if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense) { tran = AddTaxes <TAPDocument, TInvoiceMapping, TGraph, TAPDocumentGraphExtension>(apDocumentGraphExtension, docgraph, expenseClaimGraph, invoice, signOperation, claimdetail, tran, false); } } #region legacy taxes foreach (EPTaxAggregate tax in PXSelectReadonly <EPTaxAggregate, Where <EPTaxAggregate.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(docgraph, claim.RefNbr)) { #region Add taxes GenericTaxTran new_aptax = apDocumentGraphExtension.TaxTrans.Search <GenericTaxTran.taxID>(tax.TaxID); if (new_aptax == null) { new_aptax = new GenericTaxTran(); new_aptax.TaxID = tax.TaxID; new_aptax = apDocumentGraphExtension.TaxTrans.Insert(new_aptax); if (new_aptax != null) { new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax); new_aptax.CuryTaxableAmt = 0m; new_aptax.CuryTaxAmt = 0m; new_aptax.CuryExpenseAmt = 0m; new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax); } } if (new_aptax != null) { new_aptax = (GenericTaxTran)apDocumentGraphExtension.TaxTrans.Cache.CreateCopy(new_aptax); new_aptax.TaxRate = tax.TaxRate; new_aptax.CuryTaxableAmt = (new_aptax.CuryTaxableAmt ?? 0m) + tax.CuryTaxableAmt * signOperation; new_aptax.CuryTaxAmt = (new_aptax.CuryTaxAmt ?? 0m) + tax.CuryTaxAmt * signOperation; new_aptax.CuryExpenseAmt = (new_aptax.CuryExpenseAmt ?? 0m) + tax.CuryExpenseAmt * signOperation; new_aptax = apDocumentGraphExtension.TaxTrans.Update(new_aptax); } #endregion } #endregion invoice.CuryOrigDocAmt = invoice.CuryDocBal; invoice.CuryTaxAmt = invoice.CuryTaxTotal; invoice.Hold = false; apDocumentGraphExtension.SuppressApproval(); apDocumentGraphExtension.Documents.Update(invoice); if (receiptGroupPaidWithType != EPExpenseClaimDetails.paidWith.CardPersonalExpense) { invoice.CuryTaxRoundDiff = invoice.CuryRoundDiff = invoice.CuryRoundDiff = claimCuryTaxRoundDiff; invoice.TaxRoundDiff = invoice.RoundDiff = claimTaxRoundDiff; bool inclusive = PXSelectJoin <APTaxTran, InnerJoin <Tax, On <APTaxTran.taxID, Equal <Tax.taxID> > >, Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >, And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >, And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.inclusive> > > > > .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0; if ((invoice.TaxCalcMode == TaxCalculationMode.Gross && PXSelectJoin <APTaxTran, InnerJoin <Tax, On <APTaxTran.taxID, Equal <Tax.taxID> > >, Where <APTaxTran.refNbr, Equal <Required <APInvoice.refNbr> >, And <APTaxTran.tranType, Equal <Required <APInvoice.docType> >, And <Tax.taxCalcLevel, Equal <CSTaxCalcLevel.calcOnItemAmt> > > > > .Select(docgraph, invoice.RefNbr, invoice.DocType).Count > 0) || inclusive) { decimal curyAdditionalDiff = -(invoice.CuryTaxRoundDiff ?? 0m) + (invoice.CuryTaxAmt ?? 0m) - (invoice.CuryDocBal ?? 0m); decimal additionalDiff = -(invoice.TaxRoundDiff ?? 0m) + (invoice.TaxAmt ?? 0m) - (invoice.DocBal ?? 0m); foreach (InvoiceTran line in apDocumentGraphExtension.InvoiceTrans.Select()) { curyAdditionalDiff += (line.CuryTaxableAmt ?? 0m) == 0m ? (line.CuryTranAmt ?? 0m) : (line.CuryTaxableAmt ?? 0m); additionalDiff += (line.TaxableAmt ?? 0m) == 0m ? (line.TranAmt ?? 0m) : (line.TaxableAmt ?? 0m); } invoice.CuryTaxRoundDiff += curyAdditionalDiff; invoice.TaxRoundDiff += additionalDiff; } } invoice = apDocumentGraphExtension.Documents.Update(invoice); docgraph.Actions.PressSave(); if (receiptGroupPaidWithType == EPExpenseClaimDetails.paidWith.CardCompanyExpense && receiptGroup.Count == 1 && bankTranMatch != null) { CABankTransactionsMaint.RematchFromExpenseReceipt(this, bankTranMatch, invoice.CATranID, invoice.ContragentID, receiptGroup.Single()); } foreach (EPExpenseClaimDetails claimdetail in receiptGroup) { claimdetail.APDocType = invoice.DocType; claimdetail.APRefNbr = invoice.RefNbr; expenseClaimGraph.ExpenseClaimDetails.Update(claimdetail); } claim.Status = EPExpenseClaimStatus.ReleasedStatus; claim.Released = true; expenseClaimGraph.ExpenseClaim.Update(claim); #region EP History Update EPHistory hist = new EPHistory(); hist.EmployeeID = invoice.ContragentID; hist.FinPeriodID = invoice.FinPeriodID; hist = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(hist); hist.FinPtdClaimed += invoice.DocBal; hist.FinYtdClaimed += invoice.DocBal; if (invoice.FinPeriodID == invoice.HeaderTranPeriodID) { hist.TranPtdClaimed += invoice.DocBal; hist.TranYtdClaimed += invoice.DocBal; } else { EPHistory tranhist = new EPHistory(); tranhist.EmployeeID = invoice.ContragentID; tranhist.FinPeriodID = invoice.HeaderTranPeriodID; tranhist = (EPHistory)expenseClaimGraph.Caches[typeof(EPHistory)].Insert(tranhist); tranhist.TranPtdClaimed += invoice.DocBal; tranhist.TranYtdClaimed += invoice.DocBal; } expenseClaimGraph.Views.Caches.Add(typeof(EPHistory)); #endregion expenseClaimGraph.Save.Press(); Actions.PressSave(); doclist.Add((APRegister)apDocumentGraphExtension.Documents.Current.Base); } return(doclist); }
public static void ProcessReminders(List <AutoRemindCaseInfo> cases) { bool erroroccurred = false; CRCaseMaint graphCase = PXGraph.CreateInstance <CRCaseMaint>(); //Get the Email Templates Notification rowNotification1 = PXSelectJoin <Notification, InnerJoin <CRSetup, On <Notification.notificationID, Equal <CRSetupExt.usrRem1NotificationMapID> > > > .Select(graphCase); if (rowNotification1 == null) { throw new PXException("Notification Template for Reminder 1 is not specified."); } Notification rowNotification2 = PXSelectJoin <Notification, InnerJoin <CRSetup, On <Notification.notificationID, Equal <CRSetupExt.usrRem2NotificationMapID> > > > .Select(graphCase); if (rowNotification2 == null) { throw new PXException("Notification Template for Reminder 2 is not specified."); } Notification rowNotification3 = PXSelectJoin <Notification, InnerJoin <CRSetup, On <Notification.notificationID, Equal <CRSetupExt.usrRem3NotificationMapID> > > > .Select(graphCase); if (rowNotification3 == null) { throw new PXException("Notification Template for Reminder 3 is not specified."); } Notification rowNotificationAutoClose = PXSelectJoin <Notification, InnerJoin <CRSetup, On <Notification.notificationID, Equal <CRSetupExt.usrAutoCloseNotificationMapID> > > > .Select(graphCase); if (rowNotificationAutoClose == null) { throw new PXException("Notification Template for Auto Close is not specified."); } List <AutoRemindCaseInfo> casesToProcess = new List <AutoRemindCaseInfo>(cases); foreach (var rec in casesToProcess) { try { if ((!rec.UsrReminderCount.HasValue || rec.UsrReminderCount == 0) && (rec.LastActivityAge > rec.UsrTimeReactionReminder1)) { //Send First reminder AddEmailActivity(rec, rowNotification1); UpdateReminderCount(graphCase, rec.CaseID, 1); PXProcessing <AutoRemindCaseInfo> .SetInfo(cases.IndexOf(rec), String.Format("First Reminder has been sent for Case # {0}", rec.CaseCD)); } else if ((rec.UsrReminderCount == 1) && (rec.LastActivityAge > rec.UsrTimeReactionReminder2)) { //Send Second reminder AddEmailActivity(rec, rowNotification2); UpdateReminderCount(graphCase, rec.CaseID, 2); PXProcessing <AutoRemindCaseInfo> .SetInfo(cases.IndexOf(rec), String.Format("Second Reminder has been sent for Case # {0}", rec.CaseCD)); } else if ((rec.UsrReminderCount == 2) && (rec.LastActivityAge > rec.UsrTimeReactionReminder3)) { //Send Third reminder AddEmailActivity(rec, rowNotification3); UpdateReminderCount(graphCase, rec.CaseID, 3); PXProcessing <AutoRemindCaseInfo> .SetInfo(cases.IndexOf(rec), String.Format("Third Reminder has been sent for Case # {0}", rec.CaseCD)); } else if ((rec.UsrReminderCount == 3) && (rec.LastActivityAge > rec.UsrTimeReactionAutoClose)) { //Send Case closure notice AddEmailActivity(rec, rowNotificationAutoClose); UpdateReminderCount(graphCase, rec.CaseID, 4, true); PXProcessing <AutoRemindCaseInfo> .SetInfo(cases.IndexOf(rec), String.Format("Case Closure Notice has been sent for Case # {0}", rec.CaseCD)); } } catch (Exception e) { erroroccurred = true; PXProcessing <AutoRemindCaseInfo> .SetError(cases.IndexOf(rec), e); } } if (erroroccurred) { throw new PXException("At least one Case hasn't been processed."); } }
public static void PrepareAndImportRecords(List <SOPrepareAndImport> listOfPrepareAndImport) { SOScheduleProcess graph = PXGraph.CreateInstance <SOScheduleProcess>(); graph.PrepareAndImportAmazonRecords(graph, listOfPrepareAndImport); }
protected virtual PXGraph CreateGraph(string graphName, string screenID) { Type gt = System.Web.Compilation.PXBuildManager.GetType(graphName, false); if (gt == null) { gt = Type.GetType(graphName); } if (gt != null) { gt = System.Web.Compilation.PXBuildManager.GetType(PX.Api.CustomizedTypeManager.GetCustomizedTypeFullName(gt), false) ?? gt; using (new PXPreserveScope()) { try { return(gt == typeof(PXGenericInqGrph) ? PXGenericInqGrph.CreateInstance(screenID) : (PXGraph)PXGraph.CreateInstance(gt)); } catch (System.Reflection.TargetInvocationException ex) { throw PXException.ExtractInner(ex); } } } return(null); }
public static void CreatePPDDebitAdjs(PXCache cache, APPPDDebitAdjParameters filter, APSetup setup, List <PendingPPDDebitAdjApp> docs) { int i = 0; bool failed = false; APInvoiceEntry ie = PXGraph.CreateInstance <APInvoiceEntry>(); ie.APSetup.Current = setup; if (filter.GenerateOnePerVendor == true) { if (filter.DebitAdjDate == null) { throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat, PXUIFieldAttribute.GetDisplayName <APPPDDebitAdjParameters.debitAdjDate>(cache)); } if (filter.FinPeriodID == null) { throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat, PXUIFieldAttribute.GetDisplayName <APPPDDebitAdjParameters.finPeriodID>(cache)); } Dictionary <PPDApplicationKey, List <PendingPPDDebitAdjApp> > dict = new Dictionary <PPDApplicationKey, List <PendingPPDDebitAdjApp> >(); foreach (PendingPPDDebitAdjApp pendingPPDDebitAdjApp in docs) { CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, pendingPPDDebitAdjApp.InvCuryInfoID); PPDApplicationKey key = new PPDApplicationKey(); pendingPPDDebitAdjApp.Index = i++; key.BranchID = pendingPPDDebitAdjApp.AdjdBranchID; key.BAccountID = pendingPPDDebitAdjApp.VendorID; key.LocationID = pendingPPDDebitAdjApp.InvVendorLocationID; key.CuryID = info.CuryID; key.CuryRate = info.CuryRate; key.AccountID = pendingPPDDebitAdjApp.AdjdAPAcct; key.SubID = pendingPPDDebitAdjApp.AdjdAPSub; key.TaxZoneID = pendingPPDDebitAdjApp.InvTaxZoneID; List <PendingPPDDebitAdjApp> list; if (!dict.TryGetValue(key, out list)) { dict[key] = list = new List <PendingPPDDebitAdjApp>(); } list.Add(pendingPPDDebitAdjApp); } foreach (List <PendingPPDDebitAdjApp> list in dict.Values) { APInvoice invoice = CreateAndReleasePPDDebitAdj(ie, filter, list, AutoReleaseDebitAdjustments); if (invoice == null) { failed = true; } } } else { foreach (PendingPPDDebitAdjApp pendingPPDDebitAdjApp in docs) { List <PendingPPDDebitAdjApp> list = new List <PendingPPDDebitAdjApp>(1); pendingPPDDebitAdjApp.Index = i++; list.Add(pendingPPDDebitAdjApp); APInvoice invoice = CreateAndReleasePPDDebitAdj(ie, filter, list, AutoReleaseDebitAdjustments); if (invoice == null) { failed = true; } } } if (failed) { throw new PXException(GL.Messages.DocumentsNotReleased); } }
protected virtual IEnumerable LumGenerate3PLUKFile(PXAdapter adapter, [PXDate] DateTime?shipDate, [PXInt] int?siteID, [SOOperation.List] string operation) { try { // Create SOShipment Graph var graph = PXGraph.CreateInstance <SOShipmentEntry>(); var soOrder = adapter.Get <SOOrder>().FirstOrDefault(); using (PXTransactionScope sc = new PXTransactionScope()) { // FBM wont create Shipment, only upload file to FTP if (soOrder.OrderType == "FM") { // Combine csv data var result = graph.GetExtension <SOShipmentEntryExt>().CombineCSVForFBM(soOrder, "P3PL"); // Upload Graph UploadFileMaintenance upload = PXGraph.CreateInstance <UploadFileMaintenance>(); // Create SM.FileInfo var fileName = $"{soOrder.OrderNbr}.csv"; var data = new UTF8Encoding(true).GetBytes(result.csvText.ToString()); FileInfo fi = new FileInfo(fileName, null, data); // upload file to FTP #region 3PL UK FTP var configYusen = SelectFrom <LUM3PLUKSetup> .View.Select(Base).RowCast <LUM3PLUKSetup>().FirstOrDefault(); FTP_Config config = new FTP_Config() { FtpHost = configYusen.FtpHost, FtpUser = configYusen.FtpUser, FtpPass = configYusen.FtpPass, FtpPort = configYusen.FtpPort, FtpPath = configYusen.FtpPath }; var ftpResult = graph.GetExtension <SOShipmentEntryExt>().UploadFileByFTP(config, fileName, data); //var ftpResult = true; if (!ftpResult) { throw new Exception("Ftp Upload Fail!!"); } #endregion // upload file to Attachment upload.SaveFile(fi); PXNoteAttribute.SetFileNotes(Base.Document.Cache, Base.Document.Current, fi.UID.Value); Base.Save.Press(); PXProcessing.SetProcessed(); } else { // Create Shipment Base.CreateShipmentIssue(adapter, shipDate, siteID); if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel != PXErrorLevel.RowInfo) { return(null); } // Find SOShipment var _soOrderShipment = FbqlSelect <SelectFromBase <SOOrderShipment, TypeArrayOf <IFbqlJoin> .Empty> .Where <BqlChainableConditionBase <TypeArrayOf <IBqlBinary> .FilledWith <And <Compare <SOOrderShipment.orderType, Equal <P.AsString> > > > > .And <BqlOperand <SOOrderShipment.orderNbr, IBqlString> .IsEqual <P.AsString> > >, SOOrderShipment> .View.Select(Base, soOrder.OrderType, soOrder.OrderNbr) .RowCast <SOOrderShipment>().FirstOrDefault(); // Create new Adapter var newAdapter = new PXAdapter(graph.Document) { Searches = new Object[] { _soOrderShipment.ShipmentNbr } }; // Generate UK csv file and upload to FTP graph.GetExtension <SOShipmentEntryExt>().lumGenerate3PLUKFile.PressButton(newAdapter); // Remove Hold graph.releaseFromHold.PressButton(newAdapter); } if (PXProcessing <SOOrder> .GetItemMessage().ErrorLevel == PXErrorLevel.RowInfo) { sc.Complete(); } } } catch (Exception ex) { PXProcessing.SetError <SOOrder>(ex.Message); } return(adapter.Get()); }
protected virtual IEnumerable LumCallDCLShipemnt(PXAdapter adapter, [PXDate] DateTime?shipDate, [PXInt] int?siteID, [SOOperation.List] string operation) { try { var _soOrder = adapter.Get <SOOrder>().ToList()[0]; // Get DCL SO. Data(正式:order_number = SO.OrderNbr) //var dclOrders = JsonConvert.DeserializeObject<OrderResponse>( // DCLHelper.CallDCLToGetSOByOrderNumbers( // this.DCLSetup.Select().RowCast<LUMVendCntrlSetup>().FirstOrDefault(), soOrder.OrderNbr).ContentResult); // Get DCL SO. Data(理論上資料一定存在,因為Process Order已經先篩選了) var dclOrders = JsonConvert.DeserializeObject <OrderResponse>( DCLHelper.CallDCLToGetSOByOrderNumbers( this.DCLSetup.Select().RowCast <LUMVendCntrlSetup>().FirstOrDefault(), _soOrder.CustomerRefNbr).ContentResult); if (dclOrders.orders == null) { throw new Exception("Can not Mapping DCL Data"); } if (!dclOrders.orders.Any(x => x.order_stage == 60)) { throw new Exception("DCL Order stage is not Fully Shipped"); } if (_soOrder.OrderType == "FM") { var setup = this.MiddlewareSetup.Select().RowCast <LUMMiddleWareSetup>().FirstOrDefault(); var shippingCarrier = dclOrders.orders.FirstOrDefault()?.shipping_carrier; var packagesInfo = dclOrders.orders.FirstOrDefault().shipments.SelectMany(x => x.packages); var _merchant = string.IsNullOrEmpty(PXAccess.GetCompanyName()?.Split(' ')[1]) ? "us" : PXAccess.GetCompanyName()?.Split(' ')[1].ToLower() == "uk" ? "gb" : PXAccess.GetCompanyName()?.Split(' ')[1].ToLower(); MiddleWare_Shipment metaData = new MiddleWare_Shipment() { merchant = _merchant, amazon_order_id = dclOrders.orders.FirstOrDefault().po_number, shipment_date = dclOrders.orders.FirstOrDefault()?.shipments?.FirstOrDefault()?.ship_date + " 00:00:00", shipping_method = "Standard", carrier = shippingCarrier, tracking_number = string.Join("|", packagesInfo.Select(x => x.tracking_number)) }; // Update FBM var updateResult = MiddleWareHelper.CallMiddleWareToUpdateFBM(setup, metaData); // Check HttpStatusCode if (updateResult.StatusCode != System.Net.HttpStatusCode.OK) { throw new PXException($"Update MiddleWare FBM fail , Code = {updateResult.StatusCode}"); } // Check Response status var updateModel = JsonConvert.DeserializeObject <MiddleWare_Response>(updateResult.ContentResult); if (!updateModel.Status) { throw new PXException($"Update Middleware FBM fail, Msg = {updateModel.Message}"); } _soOrder.GetExtension <SOOrderExt>().UsrSendToMiddleware = true; Base.Document.Update(_soOrder); Base.Save.Press(); } else { using (PXTransactionScope sc = new PXTransactionScope()) { Base.CreateShipmentIssue(adapter, shipDate, siteID); var processResult = PXProcessing <SOOrder> .GetItemMessage(); if (processResult.ErrorLevel != PXErrorLevel.RowInfo) { return(adapter.Get()); } // Create SOShipment Graph var graph = PXGraph.CreateInstance <SOShipmentEntry>(); // Find SOShipment var _soOrderShipments = FbqlSelect <SelectFromBase <SOOrderShipment, TypeArrayOf <IFbqlJoin> .Empty> .Where <BqlChainableConditionBase <TypeArrayOf <IBqlBinary> .FilledWith <And <Compare <SOOrderShipment.orderType, Equal <P.AsString> > > > > .And <BqlOperand <SOOrderShipment.orderNbr, IBqlString> .IsEqual <P.AsString> > >, SOOrderShipment> .View.Select(Base, _soOrder.OrderType, _soOrder.OrderNbr) .RowCast <SOOrderShipment>(); foreach (var refItem in _soOrderShipments) { // Create new Adapter var newAdapter = new PXAdapter(graph.Document) { Searches = new Object[] { refItem.ShipmentNbr } }; // Select Current Shipment var _soShipment = newAdapter.Get <SOShipment>().ToList()[0]; try { // Get Carrier and TrackingNbr var shippingCarrier = dclOrders.orders.FirstOrDefault().shipping_carrier; var packagesInfo = dclOrders.orders.FirstOrDefault().shipments.SelectMany(x => x.packages); _soShipment.GetExtension <SOShipmentExt>().UsrCarrier = shippingCarrier; _soShipment.GetExtension <SOShipmentExt>().UsrTrackingNbr = string.Join("|", packagesInfo.Select(x => x.tracking_number)); _soShipment.ShipmentDesc = $"Carrier: {shippingCarrier}|" + $"TrackingNbr: {string.Join("|", packagesInfo.Select(x => x.tracking_number))}"; if (_soShipment.ShipmentDesc.Length > 256) { _soShipment.ShipmentDesc = _soShipment.ShipmentDesc.Substring(0, 255); } } catch (Exception e) { _soShipment.ShipmentDesc = e.Message; } // Update Data graph.Document.Update(_soShipment); // Remove Hold graph.releaseFromHold.PressButton(newAdapter); // Confirm Shipment graph.confirmShipmentAction.PressButton(newAdapter); // Prepare Invoice For 3D Orders try { if (_soOrder.OrderType == "3D") { newAdapter.AllowRedirect = true; graph.createInvoice.PressButton(newAdapter); } } catch (PXRedirectRequiredException ex) { SOInvoiceEntry invoiceEntry = ex.Graph as SOInvoiceEntry; var soTax = SelectFrom <SOTaxTran> .Where <SOTaxTran.orderNbr.IsEqual <P.AsString> .And <SOTaxTran.orderType.IsEqual <P.AsString> > > .View.Select(Base, _soOrder.OrderNbr, _soOrder.OrderType) .RowCast <SOTaxTran>().FirstOrDefault(); var balance = invoiceEntry.Document.Current.CuryDocBal; var refNbr = invoiceEntry.Document.Current.RefNbr; var invTax = SelectFrom <ARTaxTran> .Where <ARTaxTran.refNbr.IsEqual <P.AsString> > .View.Select(Base, refNbr).RowCast <ARTaxTran>().FirstOrDefault(); var adjd = SelectFrom <ARAdjust2> .Where <ARAdjust2.adjdRefNbr.IsEqual <P.AsString> > .View.Select(Base, refNbr).RowCast <ARAdjust2>().FirstOrDefault(); if (soTax != null) { // setting Tax invoiceEntry.Taxes.SetValueExt <ARTaxTran.curyTaxAmt>(invTax, soTax.CuryTaxAmt); invoiceEntry.Taxes.Update(invTax); // setting Document invoiceEntry.Document.SetValueExt <ARInvoice.curyTaxTotal>(invoiceEntry.Document.Current, soTax.CuryTaxAmt); invoiceEntry.Document.SetValueExt <ARInvoice.curyDocBal>(invoiceEntry.Document.Current, balance + (soTax.CuryTaxAmt ?? 0)); invoiceEntry.Document.Update(invoiceEntry.Document.Current); invoiceEntry.Adjustments.SetValueExt <ARAdjust2.curyAdjdAmt>(adjd, adjd.CuryAdjdAmt + (soTax.CuryTaxAmt ?? 0)); invoiceEntry.Adjustments.Update(adjd); invoiceEntry.releaseFromCreditHold.Press(); invoiceEntry.Save.Press(); } } catch (Exception ex) { throw new Exception(ex.Message); } } sc.Complete(); } } } catch (Exception e) { PXProcessing.SetError <SOOrder>(e.Message); } return(adapter.Get()); }
protected virtual IEnumerable LumGererateYUSENNLFile(PXAdapter adapter, [PXDate] DateTime?shipDate, [PXInt] int?siteID, [SOOperation.List] string operation) { using (PXTransactionScope sc = new PXTransactionScope()) { try { // variable var shipmentList = new List <SOShipment>(); var soList = adapter.Get <SOOrder>().ToList(); var soListwithoutFM = new List <object>(); soListwithoutFM.AddRange(soList.Where(x => x.OrderType != "FM")); var graph = PXGraph.CreateInstance <SOShipmentEntry>(); // Find soOrder type != FM var newAdapter = new PXAdapter(new LumShipmentDocView(Base, adapter.View.BqlSelect, soListwithoutFM)); newAdapter.MassProcess = true; newAdapter.Arguments = adapter.Arguments; // Create SOShipment Graph Base.CreateShipmentIssue(newAdapter, shipDate, siteID); if ((PXLongOperation.GetCustomInfoForCurrentThread("PXProcessingState") as PXProcessingInfo).Errors != 0) { return(adapter.Get()); } // Get Shipments foreach (var order in soList.Where(x => x.OrderType != "FM")) { var soOrderShipment = SelectFrom <SOOrderShipment> .Where <SOOrderShipment.orderNbr.IsEqual <P.AsString> .And <SOOrderShipment.orderType.IsEqual <P.AsString> > > .View.Select(Base, order.OrderNbr, order.OrderType).RowCast <SOOrderShipment>().FirstOrDefault(); var shipment = SelectFrom <SOShipment> .Where <SOShipment.shipmentNbr.IsEqual <P.AsString> > .View.Select(Base, soOrderShipment.ShipmentNbr).RowCast <SOShipment>().FirstOrDefault(); // update field shipment.GetExtension <SOShipmentExt>().UsrSendToWareHouse = true; graph.Document.Update(shipment); // Remove Hold (Shipments) var shipAdapter = new PXAdapter(graph.Document) { Searches = new Object[] { shipment.ShipmentNbr } }; graph.releaseFromHold.PressButton(shipAdapter); if ((PXLongOperation.GetCustomInfoForCurrentThread("PXProcessingState") as PXProcessingInfo).Errors != 0) { return(adapter.Get()); } shipmentList.Add(shipment); } // Generate NL File, Success will throw PXRedirectToFileException int totalLine = 1; StringBuilder sb = new StringBuilder(); string line = string.Empty; #region FileHeader - HDR sb = graph.GetExtension <SOShipmentEntryExt>().CombineYusenHedaer(sb); #endregion // General Detail var result = graph.GetExtension <SOShipmentEntryExt>().CombineYusenDetail(sb, shipmentList, totalLine); sb = result.sb; // FBM Yuesn Detail result = graph.GetExtension <SOShipmentEntryExt>().CombineYusenDetailForFBM(sb, soList.Where(x => x.OrderType == "FM").ToList(), result.totalLine); sb = result.sb; #region Filetrailer – TRL sb = graph.GetExtension <SOShipmentEntryExt>().CombineYusenFooter(sb, result.totalLine); #endregion // Create SM.FileInfo var fileName = $"Yusen-{DateTime.Now.ToString("yyyyMMddHHmmss")}.csv"; var data = new UTF8Encoding(true).GetBytes(sb.ToString()); FileInfo fi = new FileInfo(fileName, null, data); // DownLoad File if ((PXLongOperation.GetCustomInfoForCurrentThread("PXProcessingState") as PXProcessingInfo).Errors == 0) { throw new PXRedirectToFileException(fi, true); } } // Success catch (PXRedirectToFileException) { sc.Complete(); throw; } catch (Exception ex) { PXProcessing.SetError(ex.Message); } } return(adapter.Get()); }
private static void GenerateProc(GAFPeriod gafPeriod) { var gafGenerationProcess = PXGraph.CreateInstance <GAFGenerationProcess>(); IGAFRepository gafRepository = new GAFRepository(gafGenerationProcess); var recordBuilderByVendorData = new PurchaseRecordBuilderByVendorData(gafRepository); var recordBuilderByCustomerData = new SupplyRecordBuilderByCustomerData(gafRepository); var recordBuilderByRegister = new GafRecordBuilderByRegister(gafRepository); var recordCountryBuilderForSO = new SupplyRecordCountryBuilderForSOInvoice(gafRepository); var recordCountryBuilderForAR = new SupplyRecordCountryBuilderForARInvoice(gafRepository); var apInvoiceGAFRecordsCreator = new APInvoiceGAFRecordsCreator(gafRepository, new PurchaseRecordBuilderByInvoiceTran(gafRepository, recordBuilderByVendorData, recordBuilderByRegister), new PurchaseRecordBuilderByTaxTranFromTaxDocument(gafRepository, recordBuilderByVendorData, recordBuilderByRegister), new PurchaseRecordBuilderByAPInvoiceTaxTranForTaxCalcedOnDocumentAmt(gafRepository, recordBuilderByRegister, recordBuilderByVendorData)); var arInvoiceGAFRecordsCreator = new ARInvoiceGAFRecordsCreator(gafRepository, new SupplyRecordBuilderByARInvoice(gafRepository, recordBuilderByRegister, recordBuilderByCustomerData, recordCountryBuilderForAR), new SupplyRecordBuilderByARInvoiceTaxTranForTaxCalcedOnDocumentAmt(gafRepository, recordBuilderByRegister, recordBuilderByCustomerData, recordCountryBuilderForAR)); var arInvoiceFromSOGAFRecordsCreator = new ARInvoiceFromSOGAFRecordsCreator(gafRepository, new SupplyRecordBuilderBySOInvoice(gafRepository, recordBuilderByRegister, recordBuilderByCustomerData, recordCountryBuilderForSO), new SupplyRecordBuilderBySOInvoiceTaxTranForTaxCalcedOnDocumentAmt(gafRepository, recordBuilderByRegister, recordBuilderByCustomerData, recordCountryBuilderForSO)); var apPaymentGAFRecordsCreator = new APPaymentGAFRecordsCreator(gafRepository, new PurchaseRecordBuilderByTaxTranOfAPPayment(gafRepository, recordBuilderByVendorData, recordBuilderByRegister)); var caDocumentPurchaseGAFRecordsCreator = new CADocumentPurchaseGAFRecordsCreator(gafRepository, new PurchaseRecordBuilderByCADocument(gafRepository, recordBuilderByRegister), new PurchaseRecordBuilderByCADocumentTaxTranForTaxCalcedOnDocumentAmt(gafRepository, recordBuilderByRegister)); var caDocumentSupplyGAFRecordsCreator = new CADocumentSupplyGAFRecordsCreator(gafRepository, new SupplyRecordBuilderByCADocument(gafRepository, recordBuilderByRegister), new SupplyRecordBuilderByCADocumentTaxTranForTaxCalcedOnDocumentAmt(gafRepository, recordBuilderByRegister)); var taxAdjustmentGafRecordsCreator = new TaxAdjustmentGAFRecordsCreator(gafRepository, new GafRecordBuilderByTaxAdjustmentTaxTran(gafRepository)); var glDocumentGAFRecordsCreator = new GLDocumentGAFRecordsCreator(gafRepository, new GafRecordBuilderByGLTranAndTaxTran(gafRepository)); var gafCreationHelper = new GAFValidator(gafRepository); var gafDataCreator = new GAFDataCreator(gafRepository, gafCreationHelper, new GLGAFLedgerRecordsCreator(gafRepository), apInvoiceGAFRecordsCreator, arInvoiceGAFRecordsCreator, arInvoiceFromSOGAFRecordsCreator, apPaymentGAFRecordsCreator, caDocumentPurchaseGAFRecordsCreator, caDocumentSupplyGAFRecordsCreator, taxAdjustmentGafRecordsCreator, glDocumentGAFRecordsCreator, new GafRecordWriter(gafRepository)); var gafPeriodFromDB = gafRepository.FindGAFPeriodByKey(gafPeriod.BranchID, gafPeriod.TaxAgencyID, gafPeriod.TaxPeriodID); gafPeriod = gafPeriodFromDB ?? gafGenerationProcess.GAFPeriodView.Insert(gafPeriod); var gstAuditFile = gafDataCreator.Create(gafPeriod, gafGenerationProcess.Accessinfo.BusinessDate.Value); if (gstAuditFile == null) { return; } gafPeriod.GAFMajorVersion = gstAuditFile.MajorVersion; gafPeriod.GAFMinorLastVersion = gstAuditFile.MinorVersion; gafGenerationProcess.GAFPeriodView.Update(gafPeriod); using (var ts = new PXTransactionScope()) { PX.Objects.Common.Tools.UploadFileHelper.AttachDataAsFile(gstAuditFile.FileName, gstAuditFile.Data, gafPeriod, gafGenerationProcess); gafGenerationProcess.Actions.PressSave(); ts.Complete(); } }
public static void CreatePayments(List <ARRegister> list, ARWriteOffFilter filter) { if (string.IsNullOrEmpty(filter.ReasonCode)) { throw new PXException(Messages.ReasonCodeIsRequired); } bool failed = false; IARWriteOffEntry pe = null; if (filter.WOType == ARDocType.SmallBalanceWO) { pe = PXGraph.CreateInstance <ARSmallBalanceWriteOffEntry>(); } else { pe = PXGraph.CreateInstance <ARSmallCreditWriteOffEntry>(); } List <ARRegister> orig = list; list = new List <ARRegister>(orig); List <ARRegister> paylist = new List <ARRegister>(); List <int> paybind = new List <int>(); var cache = (pe as PXGraph).Caches[typeof(ARRegisterEx)]; list = list.OrderBy(doc => new Tuple <string, string, string, string, string>( (string)(cache.GetValueExt <ARRegisterEx.branchID>(doc) as PXFieldState).Value, doc.CuryID, (string)(cache.GetValueExt <ARRegisterEx.customerID>(doc) as PXFieldState).Value, doc.DocType, doc.RefNbr )).ToList(); for (int i = 0; i < list.Count; i++) { ARRegisterEx doc = (ARRegisterEx)list[i]; int idx = orig.IndexOf(doc); try { ReasonCode reasonCode = PXSelect <ReasonCode, Where <ReasonCode.reasonCodeID, Equal <Required <ReasonCode.reasonCodeID> > > > .Select((PXGraph)pe, doc.ReasonCode ?? filter.ReasonCode); if (reasonCode == null) { throw new PXException("Reason Code with the given id was not found in the system. Code: " + filter.ReasonCode); } Location customerLocation = PXSelect <Location, Where <Location.bAccountID, Equal <Required <Location.bAccountID> >, And <Location.locationID, Equal <Required <Location.locationID> > > > > .Select((PXGraph)pe, doc.CustomerID, doc.CustomerLocationID); CRLocation companyLocation = PXSelectJoin <CRLocation, InnerJoin <BAccountR, On <CRLocation.bAccountID, Equal <BAccountR.bAccountID>, And <CRLocation.locationID, Equal <BAccountR.defLocationID> > >, InnerJoin <GL.Branch, On <BAccountR.bAccountID, Equal <GL.Branch.bAccountID> > > >, Where <Branch.branchID, Equal <Required <Branch.branchID> > > > .Select((PXGraph)pe, doc.BranchID); object value = null; if (reasonCode.Usage == ReasonCodeUsages.BalanceWriteOff || reasonCode.Usage == ReasonCodeUsages.CreditWriteOff) { value = ReasonCodeSubAccountMaskAttribute.MakeSub <ReasonCode.subMask>((PXGraph)pe, reasonCode.SubMask, new object[] { reasonCode.SubID, customerLocation.CSalesSubID, companyLocation.CMPSalesSubID }, new Type[] { typeof(ReasonCode.subID), typeof(Location.cSalesSubID), typeof(CRLocation.cMPSalesSubID) }); } else { throw new PXException(Messages.InvalidReasonCode); } pe.CreateWriteOff(reasonCode, value.ToString(), filter.WODate, filter.WOFinPeriodID, doc); if (pe.ARDocument != null && !paylist.Contains(pe.ARDocument)) { paylist.Add(pe.ARDocument); paybind.Add(idx); } } catch (Exception e) { PXProcessing <ARRegister> .SetError(idx, e); failed = true; } } if (paylist.Count > 0) { try { ARDocumentRelease.ReleaseDoc(paylist, false); } catch (PXMassProcessException e) { PXProcessing <ARRegister> .SetError(paybind[e.ListIndex], e.InnerException); failed = true; } } if (failed) { throw new PXException(GL.Messages.DocumentsNotReleased); } }
public virtual List <Balance> Run(int?projectID) { Dictionary <string, Balance> balances = new Dictionary <string, Balance>(); List <PMTran> expenseTrans = CreateExpenseTransactions(projectID); 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); return(new List <Balance>()); } PMAllocatorEmulator ae = PXGraph.CreateInstance <PMAllocatorEmulator>(); ae.SourceTransactions = expenseTrans; foreach (PMTran tran in expenseTrans) { ae.Transactions.Insert(tran); } PXSelectBase <PMTask> selectTasks = new PXSelect <PMTask, Where <PMTask.projectID, Equal <Required <PMTask.projectID> >, And <PMTask.allocationID, IsNotNull> > >(this); List <PMTask> tasks = new List <PMTask>(); foreach (PMTask pmTask in selectTasks.Select(projectID)) { tasks.Add(pmTask); } ae.Execute(tasks); 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; } 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 = DateTime.Now.AddDays(1); //Get ARTrans for Bill: Debug.Print("Bill using the following Billing date={0}", billingDate); PMBillEngineEmulator engine = PXGraph.CreateInstance <PMBillEngineEmulator>(); engine.FieldVerifying.AddHandler <PMTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); //Project can be completed. engine.FieldVerifying.AddHandler <PMTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); //Task can be completed. engine.FieldVerifying.AddHandler <PMTran.inventoryID>((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(); engine.Bill(projectID, billingDate, null); Debug.Print("AR Trans:"); Debug.Indent(); foreach (ARTran tran in engine.InvoiceEntry.Transactions.Select()) { if (tran.TaskID == null) { continue; } 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(engine.InvoiceEntry, tran.AccountID); if (acct.AccountGroupID == null) { throw new PXException(Messages.FailedEmulateBilling); } string key = string.Format("{0}.{1}.{2}", tran.TaskID.Value, 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.TaskID = tran.TaskID.Value; b.AccountGroupID = acct.AccountGroupID.Value; b.InventoryID = tran.InventoryID ?? PMInventorySelectorAttribute.EmptyInventoryID; b.CostCodeID = tran.CostCodeID ?? CostCodeAttribute.GetDefaultCostCode(); b.Amount = tran.TranAmt ?? 0; b.Quantity = tran.Qty ?? 0; balances.Add(key, b); } } return(new List <Balance>(balances.Values)); }
public static void Transfer(TransferFilter filter, List <FixedAsset> list) { TransferProcess graph = PXGraph.CreateInstance <TransferProcess>(); graph.DoTransfer(filter, list); }
public static bool ReleaseWithoutPost(List <PMRegister> list, bool isMassProcess, out List <ProcessInfo <Batch> > infoList) { bool failed = false; infoList = new List <ProcessInfo <Batch> >(); if (!list.Any()) { return(!failed); } RegisterReleaseProcess rg = PXGraph.CreateInstance <RegisterReleaseProcess>(); JournalEntry je = PXGraph.CreateInstance <JournalEntry>(); PMAllocator allocator = PXGraph.CreateInstance <PMAllocator>(); //Task may be IsActive=False - it may be completed. User cannot create transactions with this //TaskID. But the system has to process the given task - hence override the FieldVerification in the Selector. je.FieldVerifying.AddHandler <GLTran.projectID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); je.FieldVerifying.AddHandler <GLTran.taskID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); for (int i = 0; i < list.Count; i++) { ProcessInfo <Batch> info = new ProcessInfo <Batch>(i); infoList.Add(info); PMRegister doc = list[i]; try { List <PMTask> allocTasks; info.Batches.AddRange(rg.Release(je, doc, out allocTasks)); allocator.Clear(); allocator.TimeStamp = je.TimeStamp; if (allocTasks.Count > 0) { allocator.Execute(allocTasks); allocator.Actions.PressSave(); } if (allocator.Document.Current != null && rg.AutoReleaseAllocation) { List <PMTask> allocTasks2; info.Batches.AddRange(rg.Release(je, allocator.Document.Current, out allocTasks2)); } if (isMassProcess) { PXProcessing <PMRegister> .SetInfo(i, ActionsMessages.RecordProcessed); } } catch (Exception e) { if (isMassProcess) { PXProcessing <PMRegister> .SetError(i, e is PXOuterException?e.Message + "\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message); failed = true; } else { throw new PXMassProcessException(i, e); } } } return(!failed); }
public static void RefreshRates(RefreshFilter filter, List <RefreshRate> list, string apiKey) { bool hasError = false; var date = GetUtcSyncDate(filter.CuryEffDate.Value); string ratesRequestURL = String.Format( "http://openexchangerates.org/api/time-series.json?app_id={0}&base={1}&start={2:yyyy-MM-dd}&end={2:yyyy-MM-dd}", apiKey, filter.CuryID, date); PXTrace.WriteInformation("Refresh rates URL: " + ratesRequestURL); var client = new WebClient(); var response = client.DownloadString(new Uri(ratesRequestURL)); JObject json = (JObject)JsonConvert.DeserializeObject(response); if (json == null) { throw new PXException(Messages.CurrencyRateJsonError, response); } JToken rates = json.SelectToken(String.Format("rates.{0:yyyy-MM-dd}", date), true); CuryRateMaint graph = PXGraph.CreateInstance <CuryRateMaint>(); graph.Filter.Current.ToCurrency = filter.CuryID; graph.Filter.Current.EffDate = date; for (int i = 0; i < list.Count; i++) { RefreshRate rr = list[i]; var rate = rates.Children().Cast <JProperty>().Where(p => p.Name == rr.FromCuryID).FirstOrDefault(); if (rate == null) { PXProcessing <RefreshRate> .SetError(i, PXMessages.LocalizeFormatNoPrefixNLA(Messages.NoOnlyRatesFoundForCurrency, rr.FromCuryID)); hasError = true; } else { CurrencyRate curyRate = (CurrencyRate)graph.CuryRateRecordsEntry.Insert(); curyRate.FromCuryID = rr.FromCuryID; curyRate.ToCuryID = filter.CuryID; curyRate.CuryRateType = rr.CuryRateType; curyRate.CuryRate = rate.Value.Value <decimal>() * (1 + rr.OnlineRateAdjustment.GetValueOrDefault(0) / 100); curyRate.CuryMultDiv = "D"; rr.CuryRate = curyRate.CuryRate; graph.CuryRateRecordsEntry.Update(curyRate); PXProcessing <RefreshRate> .SetInfo(i, ActionsMessages.RecordProcessed); } } graph.Actions.PressSave(); if (hasError) { throw new PXOperationCompletedException(Messages.CurrencyRateFailedToRefresh); } }
protected virtual int ConsolidationRead(GLConsolSetup item) { int cnt = 0; string aFiscalPeriod = null; int? ledgerID = item.LedgerId; int? branchID = item.BranchID; var importSubaccountCDCalculator = CreateImportSubaccountMapper(item); var glConsolHistory = PXSelect<GLConsolHistory, Where<GLConsolHistory.setupID, Equal<Required<GLConsolHistory.setupID>>>> .Select(this, item.SetupID).ToList(); var roundFunc = GetRoundDelegateForLedger(ledgerID); JournalEntry je = PXGraph.CreateInstance<JournalEntry>(); if (item.BypassAccountSubValidation == true) { je.FieldVerifying.AddHandler<GLTran.accountID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); je.FieldVerifying.AddHandler<GLTran.subID>((PXCache sender, PXFieldVerifyingEventArgs e) => { e.Cancel = true; }); } consolSetup = DecryptRemoteUserPassword(item); using (PXSoapScope scope = new PXSoapScope(consolSetup.Url, consolSetup.Login, consolSetup.Password)) { GLConsolReadMaint reader = PXGraph.CreateInstance<GLConsolReadMaint>(); reader.ConsolRecords.Select(item.SourceLedgerCD, item.SourceBranchCD); scope.Process(reader); int min = 0; if (!String.IsNullOrEmpty(item.StartPeriod)) { int.TryParse(item.StartPeriod, out min); } int max = 0; if (!String.IsNullOrEmpty(item.EndPeriod)) { int.TryParse(item.EndPeriod, out max); } foreach (GLConsolData row in reader.ConsolRecords.Select()) { if (min > 0 || max > 0) { if (!String.IsNullOrEmpty(row.FinPeriodID)) { int p; if (int.TryParse(row.FinPeriodID, out p)) { if (min > 0 && p < min || max > 0 && p > max) { continue; } } } } if (aFiscalPeriod == null) { aFiscalPeriod = row.FinPeriodID; } else if (aFiscalPeriod != row.FinPeriodID) { if (listConsolRead.Count > 0) { cnt += AppendRemapped(aFiscalPeriod, ledgerID, branchID, item.SetupID, roundFunc); CreateBatch(je, aFiscalPeriod, ledgerID, branchID, item); } aFiscalPeriod = row.FinPeriodID; listConsolRead.Clear(); } GLConsolRead read = new GLConsolRead(); var account = AccountMaint.GetAccountByCD(this, row.AccountCD); if (account.AccountID == GLSetup.Current.YtdNetIncAccountID) { throw new PXException(Messages.ImportingYTDNetIncomeAccountDataIsProhibited); } read.AccountCD = account.AccountCD; read.AccountID = account.AccountID; var mappedValue = GetMappedValue(row); var subKeys = importSubaccountCDCalculator.GetMappedSubaccountKeys(mappedValue); read.MappedValue = subKeys.SubCD; read.SubID = subKeys.SubID; read.FinPeriodID = row.FinPeriodID; GLConsolHistory history = new GLConsolHistory(); history.SetupID = item.SetupID; history.FinPeriodID = read.FinPeriodID; history.AccountID = read.AccountID; history.SubID = read.SubID; history.LedgerID = item.LedgerId; history.BranchID = item.BranchID; history = (GLConsolHistory)Caches[typeof(GLConsolHistory)].Locate(history); if (history != null) { read.ConsolAmtCredit = roundFunc(row.ConsolAmtCredit) - roundFunc(history.PtdCredit); read.ConsolAmtDebit = roundFunc(row.ConsolAmtDebit) - roundFunc(history.PtdDebit); history.PtdCredit = 0m; history.PtdDebit = 0m; } else { read.ConsolAmtCredit = roundFunc(row.ConsolAmtCredit); read.ConsolAmtDebit = roundFunc(row.ConsolAmtDebit); } if (read.ConsolAmtCredit != 0m || read.ConsolAmtDebit != 0m) { listConsolRead.Add(read); cnt++; } } } if (listConsolRead.Count > 0) { cnt += AppendRemapped(aFiscalPeriod, ledgerID, branchID, item.SetupID, roundFunc); CreateBatch(je, aFiscalPeriod, ledgerID, branchID, item); } if (exception != null) { PXException ex = exception; exception = null; throw ex; } return cnt; }
public static void CreatePPDCreditMemos(PXCache cache, ARPPDCreditMemoParameters filter, ARSetup setup, List <PendingPPDCreditMemoApp> docs) { int i = 0; bool failed = false; List <ARRegister> toRelease = new List <ARRegister>(); ARInvoiceEntry ie = PXGraph.CreateInstance <ARInvoiceEntry>(); if (filter.GenerateOnePerCustomer == true) { if (filter.CreditMemoDate == null) { throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat, PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.creditMemoDate>(cache)); } if (filter.FinPeriodID == null) { throw new PXSetPropertyException(CR.Messages.EmptyValueErrorFormat, PXUIFieldAttribute.GetDisplayName <ARPPDCreditMemoParameters.finPeriodID>(cache)); } Dictionary <PPDCreditMemoKey, List <PendingPPDCreditMemoApp> > dict = new Dictionary <PPDCreditMemoKey, List <PendingPPDCreditMemoApp> >(); foreach (PendingPPDCreditMemoApp doc in docs) { CurrencyInfo info = PXSelect <CurrencyInfo, Where <CurrencyInfo.curyInfoID, Equal <Required <CurrencyInfo.curyInfoID> > > > .Select(ie, doc.InvCuryInfoID); PPDCreditMemoKey key = new PPDCreditMemoKey(); doc.Index = i++; key.BranchID = doc.AdjdBranchID; key.CustomerID = doc.AdjdCustomerID; key.CustomerLocationID = doc.InvCustomerLocationID; key.CuryID = info.CuryID; key.CuryRate = info.CuryRate; key.ARAccountID = doc.AdjdARAcct; key.ARSubID = doc.AdjdARSub; key.TaxZoneID = doc.InvTaxZoneID; List <PendingPPDCreditMemoApp> list; if (!dict.TryGetValue(key, out list)) { dict[key] = list = new List <PendingPPDCreditMemoApp>(); } list.Add(doc); } foreach (List <PendingPPDCreditMemoApp> list in dict.Values) { ARInvoice invoice = CreatePPDCreditMemo(ie, filter, setup, list); if (invoice != null) { toRelease.Add(invoice); } else { failed = true; } } } else { foreach (PendingPPDCreditMemoApp doc in docs) { List <PendingPPDCreditMemoApp> list = new List <PendingPPDCreditMemoApp>(1); doc.Index = i++; list.Add(doc); ARInvoice invoice = CreatePPDCreditMemo(ie, filter, setup, list); if (invoice != null) { toRelease.Add(invoice); } else { failed = true; } } } if (setup.AutoReleasePPDCreditMemo == true && toRelease.Count > 0) { using (new PXTimeStampScope(null)) { ARDocumentRelease.ReleaseDoc(toRelease, true); } } if (failed) { throw new PXException(GL.Messages.DocumentsNotReleased); } }
public void PrepareAndImportAmazonRecords(SOScheduleProcess graph, List <SOPrepareAndImport> listOfPrepareAndImport) { objSyncOrderResponse = new InvokeServicesCallResponse(); amwOrders = new List <Order>(); amwLineItems = new List <OrderItem>(); SOAmazonSetup objSOAmazonSetup = null; SOPartialMaint logGraph = PXGraph.CreateInstance <SOPartialMaint>(); SOOrderEntry orderEntry = PXGraph.CreateInstance <SOOrderEntry>(); ARPaymentEntry paymentGraph = PXGraph.CreateInstance <ARPaymentEntry>(); bool isErrorOccured = false; DateTime? businessDateTime = PX.Common.PXTimeZoneInfo.Now; List <string> liCarriers = PXSelect <Carrier> .Select(graph).RowCast <Carrier>().Select(c => c.CarrierID).ToList(); try { SOSetupAmazonExt objSOOSetupext = orderEntry.sosetup.Current.GetExtension <SOSetupAmazonExt>(); if (SOHelper.IsSOPreferencesDetailsExist(orderEntry, objSOOSetupext)) { foreach (SOPrepareAndImport currentRecord in listOfPrepareAndImport) { objSOAmazonSetup = null; if (SOHelper.MarketplaceConfigurations(graph, currentRecord.IntegrationID, out objSOAmazonSetup)) { objSyncOrderResponse = objSyncOrderResponse != null ? null : objSyncOrderResponse; if (amwOrders != null && amwOrders.Count > 0) { amwOrders.Clear(); } if (amwLineItems != null && amwLineItems.Count > 0) { amwLineItems.Clear(); } orderEntry.Clear(); logGraph.Clear(); paymentGraph.Clear(); objServiceCallParams = new ServiceCallParameters(); objServiceCallParams.objSOAmazonSetup = objSOAmazonSetup; objServiceCallParams.amwOrderID = string.Empty; objServiceCallParams.methodCall = SOConstants.invokeListOrders; objServiceCallParams.fromDate = currentRecord.LastSyncDate; objServiceCallParams.toDate = currentRecord.ToDate; // Prepare action is invoked objSyncOrderResponse = new SOOrdersServiceCall(clientOrder).InvokeServicesCalls(graph, objServiceCallParams); if (amwLineItems != null && amwLineItems.Count > 0) { amwLineItems.Clear(); } if (objSyncOrderResponse != null && objSyncOrderResponse.objListOrderResponse != null && objSyncOrderResponse.objListOrderResponse.ListOrdersResult != null && objSyncOrderResponse.objListOrderResponse.ListOrdersResult.Orders != null && objSyncOrderResponse.objListOrderResponse.ListOrdersResult.Orders.Count > 0) { amwOrders = objSyncOrderResponse.objListOrderResponse.ListOrdersResult.Orders.ToList(); // Saving the prepare action response objScheduleParams = new PrepareAndImportOrdersParams(); objScheduleParams.objSOPrepareAndImport = currentRecord; objScheduleParams.objSOAmazonSetup = objSOAmazonSetup; objScheduleParams.objSOOrderEntry = orderEntry; objScheduleParams.objSOPartialMaint = logGraph; objScheduleParams.businessDateTime = businessDateTime; objScheduleParams.paymentGraph = paymentGraph; objScheduleParams.listOfCarriers = liCarriers; objScheduleParams.amwOrders = amwOrders; SOHelper.PrepareRecord(graph, objScheduleParams, ref isErrorOccured); if (objSyncOrderResponse.objListOrderResponse.ListOrdersResult.NextToken != null) { objScheduleParams.objNextToken = objSyncOrderResponse.objListOrderResponse.ListOrdersResult.NextToken; objScheduleParams.paymentGraph = paymentGraph; GetAmazonOrdersbyNextToken(graph, objScheduleParams, ref isErrorOccured); } } else { SOLogService.LogImportCount(null, currentRecord.IntegrationID, logGraph, currentRecord.ProcessID, SOConstants.scheduleimportorders, true); } } else { throw new PXException(SOMessages.apidetailsMissing); } } } else { throw new PXException(SOMessages.configMissing); } } catch (Exception ex) { SOLogService.LogImportStatus(objScheduleParams, false, ex.Message); throw new PXException(ex.Message); } }
protected void MergeDuplicates(int targetID, List <TMain> duplicateEntities, List <FieldValue> values, bool IsContractBasedAPI) { TMain targetEntity = GetTargetEntity(targetID); object realTargetEntity = targetEntity; var graphType = new EntityHelper(Base).GetPrimaryGraphType(ref realTargetEntity, false); if (graphType == null) { return; } PXGraph targetGraph = PXGraph.CreateInstance(graphType); PXCache cache = targetGraph.Caches[typeof(TMain)]; var refNoteIdField = EntityHelper.GetNoteField(cache.GetItemType()); realTargetEntity = cache.CreateCopy(realTargetEntity); Contact targetContact = GetTargetContact(targetEntity); Address targetAddress = GetTargetAddress(targetEntity); Dictionary <Type, object> targets = new Dictionary <Type, object> { [typeof(TMain)] = realTargetEntity, [typeof(Contact)] = targetContact, [typeof(Address)] = targetAddress }; foreach (FieldValue fieldValue in values) { if (fieldValue.AttributeID == null) { Type type = Type.GetType(fieldValue.CacheName); PXFieldState state = (PXFieldState)targetGraph.Caches[type].GetStateExt(targets[type], fieldValue.Name); if (state == null || !Equals(state.Value, fieldValue.Value)) { targetGraph.Caches[type].SetValueExt(targets[type], fieldValue.Name, fieldValue.Value); targets[type] = targetGraph.Caches[type].CreateCopy(targetGraph.Caches[type].Update(targets[type])); } } else { PXCache attrCache = cache.Graph.Caches[typeof(CSAnswers)]; CSAnswers attr = new CSAnswers { AttributeID = fieldValue.AttributeID, RefNoteID = cache.GetValue(targetEntity, refNoteIdField) as Guid?, Value = fieldValue.Value, }; Dictionary <string, object> keys = new Dictionary <string, object>(); foreach (string key in attrCache.Keys.ToArray()) { keys[key] = attrCache.GetValue(attr, key); } if (attrCache.Locate(keys) == 0) { attrCache.Insert(attr); } else { var located = attrCache.Locate(attr) as CSAnswers; located.Value = attr.Value; attrCache.Update(located); } } } PXPrimaryGraphCollection primaryGraph = new PXPrimaryGraphCollection(targetGraph); using (PXTransactionScope scope = new PXTransactionScope()) { foreach (TMain duplicateEntity in duplicateEntities) { // only int, only single field if (cache.GetValue(duplicateEntity, cache.Keys[0]) as int? == targetID) { continue; } targetGraph.Caches[realTargetEntity.GetType()].Current = realTargetEntity; MergeEntities(targetGraph, realTargetEntity as TMain, duplicateEntity); targetGraph.Actions.PressSave(); PXGraph operGraph = primaryGraph[duplicateEntity]; RunActionWithAppliedAutomation(operGraph, duplicateEntity, nameof(CloseAsDuplicate)); operGraph.Actions.PressSave(); } scope.Complete(); } // should become validated if no possible duplicates Base.Views[Base.PrimaryView].Cache.Current = targetEntity; Base.Actions.PressCancel(); RunActionWithAppliedAutomation(Base, targetEntity, nameof(CheckForDuplicates)); if (!IsContractBasedAPI) { RunActionWithAppliedAutomation(targetGraph, realTargetEntity, "Cancel"); throw new PXRedirectRequiredException(targetGraph, ""); } }
public static void Revalue(RevalueFilter filter, List <RevaluedARHistory> list) { JournalEntry je = PXGraph.CreateInstance <JournalEntry>(); PostGraph pg = PXGraph.CreateInstance <PostGraph>(); PXCache cache = je.Caches[typeof(CuryARHist)]; PXCache basecache = je.Caches[typeof(ARHist)]; je.Views.Caches.Add(typeof(CuryARHist)); je.Views.Caches.Add(typeof(ARHist)); string extRefNbrNumbering = je.CMSetup.Current.ExtRefNbrNumberingID; if (string.IsNullOrEmpty(extRefNbrNumbering) == false) { RevaluationRefNbrHelper helper = new RevaluationRefNbrHelper(extRefNbrNumbering); helper.Subscribe(je); } DocumentList <Batch> created = new DocumentList <Batch>(je); Currency currency = PXSelect <Currency, Where <Currency.curyID, Equal <Required <Currency.curyID> > > > .Select(je, filter.CuryID); using (PXTransactionScope ts = new PXTransactionScope()) { foreach (RevaluedARHistory hist in list) { if (hist.FinPtdRevalued == 0m) { continue; } if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted) { je.Save.Press(); if (created.Find(je.BatchModule.Current) == null) { created.Add(je.BatchModule.Current); } } Batch cmbatch = created.Find <Batch.branchID>(hist.BranchID) ?? new Batch(); if (cmbatch.BatchNbr == null) { je.Clear(); CurrencyInfo info = new CurrencyInfo(); info.CuryID = hist.CuryID; info.CuryEffDate = hist.CuryEffDate; info.BaseCalc = false; info = je.currencyinfo.Insert(info) ?? info; cmbatch = new Batch(); cmbatch.BranchID = hist.BranchID; cmbatch.Module = "CM"; cmbatch.Status = "U"; cmbatch.AutoReverse = true; cmbatch.Released = true; cmbatch.Hold = false; cmbatch.DateEntered = filter.CuryEffDate; cmbatch.FinPeriodID = filter.FinPeriodID; cmbatch.TranPeriodID = filter.FinPeriodID; cmbatch.CuryID = hist.CuryID; cmbatch.CuryInfoID = info.CuryInfoID; cmbatch.DebitTotal = 0m; cmbatch.CreditTotal = 0m; cmbatch.Description = filter.Description; je.BatchModule.Insert(cmbatch); CurrencyInfo b_info = je.currencyinfo.Select(); if (b_info != null) { b_info.CuryID = hist.CuryID; b_info.CuryEffDate = hist.CuryEffDate; b_info.CuryRateTypeID = hist.CuryRateTypeID; b_info.CuryRate = hist.CuryRate; b_info.RecipRate = hist.RateReciprocal; b_info.CuryMultDiv = hist.CuryMultDiv; je.currencyinfo.Update(b_info); } } else { if (!je.BatchModule.Cache.ObjectsEqual(je.BatchModule.Current, cmbatch)) { je.Clear(); } je.BatchModule.Current = je.BatchModule.Search <Batch.batchNbr>(cmbatch.BatchNbr, cmbatch.Module); } { GLTran tran = new GLTran(); tran.SummPost = false; tran.AccountID = currency.ARProvAcctID ?? hist.AccountID; tran.SubID = currency.ARProvSubID ?? hist.SubID; tran.CuryDebitAmt = 0m; tran.CuryCreditAmt = 0m; tran.DebitAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued; tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m; tran.TranType = "REV"; tran.TranClass = AccountType.Asset; tran.RefNbr = string.Empty; tran.TranDesc = filter.Description; tran.TranPeriodID = filter.FinPeriodID; tran.FinPeriodID = filter.FinPeriodID; tran.TranDate = filter.CuryEffDate; tran.CuryInfoID = null; tran.Released = true; tran.ReferenceID = hist.CustomerID; je.GLTranModuleBatNbr.Insert(tran); } foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { GLTran.tranClass.UnrealizedAndRevaluationGOL })) { je.GLTranModuleBatNbr.Delete(tran); } CustomerClass custclass = PXSelectReadonly <CustomerClass, Where <CustomerClass.customerClassID, Equal <Required <CustomerClass.customerClassID> > > > .Select(je, hist.CustomerClassID); if (custclass == null) { custclass = new CustomerClass(); } if (custclass.UnrealizedGainAcctID == null) { custclass.UnrealizedGainSubID = null; } if (custclass.UnrealizedLossAcctID == null) { custclass.UnrealizedLossSubID = null; } { GLTran tran = new GLTran(); tran.SummPost = true; tran.ZeroPost = false; tran.CuryDebitAmt = 0m; tran.CuryCreditAmt = 0m; if (je.BatchModule.Current.DebitTotal > je.BatchModule.Current.CreditTotal) { tran.AccountID = custclass.UnrealizedGainAcctID ?? currency.UnrealizedGainAcctID; tran.SubID = custclass.UnrealizedGainSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedGainSubID>(je, hist.BranchID, currency); tran.DebitAmt = 0m; tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal); } else { tran.AccountID = custclass.UnrealizedLossAcctID ?? currency.UnrealizedLossAcctID; tran.SubID = custclass.UnrealizedLossSubID ?? GainLossSubAccountMaskAttribute.GetSubID <Currency.unrealizedLossSubID>(je, hist.BranchID, currency); tran.DebitAmt = (je.BatchModule.Current.CreditTotal - je.BatchModule.Current.DebitTotal); tran.CreditAmt = 0m; } tran.TranType = "REV"; tran.TranClass = GLTran.tranClass.UnrealizedAndRevaluationGOL; tran.RefNbr = string.Empty; tran.TranDesc = filter.Description; tran.Released = true; tran.ReferenceID = null; je.GLTranModuleBatNbr.Insert(tran); } { CuryARHist arhist = new CuryARHist(); arhist.BranchID = hist.BranchID; arhist.AccountID = hist.AccountID; arhist.SubID = hist.SubID; arhist.FinPeriodID = filter.FinPeriodID; arhist.CustomerID = hist.CustomerID; arhist.CuryID = hist.CuryID; arhist = (CuryARHist)cache.Insert(arhist); arhist.FinPtdRevalued += hist.FinPtdRevalued; } { ARHist arhist = new ARHist(); arhist.BranchID = hist.BranchID; arhist.AccountID = hist.AccountID; arhist.SubID = hist.SubID; arhist.FinPeriodID = filter.FinPeriodID; arhist.CustomerID = hist.CustomerID; arhist = (ARHist)basecache.Insert(arhist); arhist.FinPtdRevalued += hist.FinPtdRevalued; } } if (je.GLTranModuleBatNbr.Cache.IsInsertedUpdatedDeleted) { je.Save.Press(); if (created.Find(je.BatchModule.Current) == null) { created.Add(je.BatchModule.Current); } } ts.Complete(); } CMSetup cmsetup = PXSelect <CMSetup> .Select(je); for (int i = 0; i < created.Count; i++) { if (cmsetup.AutoPostOption == true) { pg.Clear(); pg.PostBatchProc(created[i]); } } if (created.Count > 0) { je.BatchModule.Current = created[created.Count - 1]; throw new PXRedirectRequiredException(je, "Preview"); } }
public virtual IEnumerable NewVendor(PXAdapter adapter) { VendorMaint graph = PXGraph.CreateInstance <VendorMaint>(); throw new PXRedirectRequiredException(graph, Messages.NewVendor); }
public virtual void ReleaseDocProc(EPExpenseClaim claim) { ExpenseClaimEntry expenseClaimGraph = PXGraph.CreateInstance <ExpenseClaimEntry>(); EPExpenseClaim checkClaim = PXSelectReadonly <EPExpenseClaim, Where <EPExpenseClaim.refNbr, Equal <Required <EPExpenseClaim.refNbr> > > > .Select(expenseClaimGraph, claim.RefNbr); if (checkClaim.Released == true) { throw new PXException(Messages.AlreadyReleased); } var receipts = PXSelect <EPExpenseClaimDetails, Where <EPExpenseClaimDetails.refNbr, Equal <Required <EPExpenseClaim.refNbr> >, And <EPExpenseClaimDetails.released, Equal <False> > > > .Select(expenseClaimGraph, claim.RefNbr) .RowCast <EPExpenseClaimDetails>() .ToArray(); IFinPeriodUtils finPeriodUtils = expenseClaimGraph.GetService <IFinPeriodUtils>(); if (claim.FinPeriodID != null) { finPeriodUtils.ValidateFinPeriod <EPExpenseClaimDetails>(receipts, m => claim.FinPeriodID, m => m.BranchID.SingleToArray()); } List <APRegister> apDocs = new List <APRegister>(); using (var ts = new PXTransactionScope()) { if (receipts.Any()) { var receiptsByPaidWithType = receipts.GroupBy(receipt => receipt.PaidWith); foreach (var receiptGroup in receiptsByPaidWithType) { List <APRegister> res = null; if (receiptGroup.Key == EPExpenseClaimDetails.paidWith.PersonalAccount) { res = ReleaseClaimDetails < Invoice, InvoiceMapping, APInvoiceEntry, APInvoiceEntry.APInvoiceEntryDocumentExtension>( expenseClaimGraph, claim, receiptGroup, receiptGroup.Key); } else if (receiptGroup.Key == EPExpenseClaimDetails.paidWith.CardCompanyExpense) { res = ReleaseClaimDetails < PaidInvoice, PaidInvoiceMapping, APQuickCheckEntry, APQuickCheckEntry.APQuickCheckEntryDocumentExtension>( expenseClaimGraph, claim, receiptGroup, receiptGroup.Key); } else if (receiptGroup.Key == EPExpenseClaimDetails.paidWith.CardPersonalExpense) { res = ReleaseClaimDetails < Invoice, InvoiceMapping, APInvoiceEntry, APInvoiceEntry.APInvoiceEntryDocumentExtension>( expenseClaimGraph, claim, receiptGroup, receiptGroup.Key); } else { throw new NotImplementedException(); } apDocs.AddRange(res); } } else { apDocs = ReleaseClaimDetails <Invoice, InvoiceMapping, APInvoiceEntry, APInvoiceEntry.APInvoiceEntryDocumentExtension>( expenseClaimGraph, claim, new EPExpenseClaimDetails[0], EPExpenseClaimDetails.paidWith.PersonalAccount); } ts.Complete(); } EPSetup epsetup = PXSelectReadonly <EPSetup> .Select(this); if (epsetup.AutomaticReleaseAP == true) { APDocumentRelease.ReleaseDoc(apDocs, false); } }
public static PXRedirectRequiredException CreatePOOrders2( System.Collections.Generic.List <POFixedDemand> list, DateTime?PurchDate, bool extSort) { POOrderEntry docgraph = PXGraph.CreateInstance <POOrderEntry>(); docgraph.Views.Caches.Add(typeof(POOrderEntry.SOLineSplit3)); POSetup current = docgraph.POSetup.Current; DocumentList <POOrder> documentList1 = new DocumentList <POOrder>((PXGraph)docgraph); Dictionary <string, DocumentList <POLine> > dictionary = new Dictionary <string, DocumentList <POLine> >(); list.Sort((Comparison <POFixedDemand>)((a, b) => { string empty1 = string.Empty; string empty2 = string.Empty; string str; if (a.PlanType == "90") { PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, a.InventoryID); str = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD); } else { POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)a.PlanID); str = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault()); } string strB; if (b.PlanType == "90") { PX.Objects.IN.InventoryItem inventoryItem = PX.Objects.IN.InventoryItem.PK.Find((PXGraph)docgraph, b.InventoryID); strB = string.Format("ZZ.{0}", inventoryItem == null ? (object)string.Empty : (object)inventoryItem.InventoryCD); } else { POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3)PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)b.PlanID); strB = soLineSplit3 == null ? string.Empty : string.Format("{0}.{1}.{2:D7}", (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.SortOrder.GetValueOrDefault()); } return(str.CompareTo(strB)); })); POOrder poOrder1 = (POOrder)null; bool flag1 = false; foreach (POFixedDemand demand in list) { if (!(demand.FixedSource != "P")) { string OrderType = demand.PlanType == "6D" ? "DP" : (demand.PlanType == "6E" ? "DP" : "RO"); string str1 = (string)null; int? nullable1 = demand.VendorID; int num1; if (nullable1.HasValue) { nullable1 = demand.VendorLocationID; num1 = !nullable1.HasValue ? 1 : 0; } else { num1 = 1; } if (num1 != 0) { PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), "Vendor and vendor location should be defined."); } else { PXErrorLevel pxErrorLevel = PXErrorLevel.RowInfo; string empty = string.Empty; try { PX.Objects.SO.SOOrder soOrder = (PX.Objects.SO.SOOrder) PXSelectBase <PX.Objects.SO.SOOrder, PXSelect <PX.Objects.SO.SOOrder, Where <PX.Objects.SO.SOOrder.noteID, Equal <Required <PX.Objects.SO.SOOrder.noteID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.RefNoteID); POOrderEntry.SOLineSplit3 soLineSplit3 = (POOrderEntry.SOLineSplit3) PXSelectBase <POOrderEntry.SOLineSplit3, PXSelect <POOrderEntry.SOLineSplit3, Where <POOrderEntry.SOLineSplit3.planID, Equal <Required <POOrderEntry.SOLineSplit3.planID> > > > .Config> .Select((PXGraph)docgraph, (object)demand.PlanID); string str2 = (string)null; string str3 = (string)null; if (demand.PlanType == "6B" || demand.PlanType == "6E") { str2 = soLineSplit3.POType; str3 = soLineSplit3.PONbr; } System.Collections.Generic.List <FieldLookup> fieldLookupList1 = new System.Collections.Generic.List <FieldLookup>() { (FieldLookup) new FieldLookup <POOrder.orderType>((object)OrderType), (FieldLookup) new FieldLookup <POOrder.vendorID>((object)demand.VendorID), (FieldLookup) new FieldLookup <POOrder.vendorLocationID>((object)demand.VendorLocationID), (FieldLookup) new FieldLookup <POOrder.bLOrderNbr>((object)str3) }; if (OrderType == "RO") { bool?projectPerDocument = docgraph.apsetup.Current.RequireSingleProjectPerDocument; bool flag2 = true; if (projectPerDocument.GetValueOrDefault() == flag2 & projectPerDocument.HasValue) { nullable1 = demand.ProjectID; int?nullable2 = nullable1.HasValue ? nullable1 : ProjectDefaultAttribute.NonProject(); fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.projectID>((object)nullable2)); } int num2; if (poOrder1 != null && poOrder1.ShipDestType == "L") { nullable1 = poOrder1.SiteID; num2 = !nullable1.HasValue ? 1 : 0; } else { num2 = 0; } if (num2 == 0) { fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID)); } } else if (OrderType == "DP") { fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderType>((object)soLineSplit3.OrderType)); fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.sOOrderNbr>((object)soLineSplit3.OrderNbr)); } else { fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToBAccountID>((object)soOrder.CustomerID)); fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.shipToLocationID>((object)soOrder.CustomerLocationID)); fieldLookupList1.Add((FieldLookup) new FieldLookup <POOrder.siteID>((object)demand.POSiteID)); } poOrder1 = documentList1.Find(fieldLookupList1.ToArray()) ?? new POOrder(); if (poOrder1.OrderNbr == null) { docgraph.Clear(); poOrder1.OrderType = OrderType; poOrder1 = PXCache <POOrder> .CreateCopy(docgraph.Document.Insert(poOrder1)); poOrder1.VendorID = demand.VendorID; poOrder1.VendorLocationID = demand.VendorLocationID; poOrder1.SiteID = demand.POSiteID; nullable1 = demand.ProjectID; if (nullable1.HasValue) { poOrder1.ProjectID = demand.ProjectID; } poOrder1.OrderDate = PurchDate; poOrder1.BLType = str2; poOrder1.BLOrderNbr = str3; if (OrderType == "DP" | extSort) { poOrder1.SOOrderType = soLineSplit3.OrderType; poOrder1.SOOrderNbr = soLineSplit3.OrderNbr; } if (!string.IsNullOrEmpty(poOrder1.BLOrderNbr)) { POOrder poOrder2 = (POOrder)PXSelectBase <POOrder, PXSelect <POOrder, Where <POOrder.orderType, Equal <Current <POOrder.bLType> >, And <POOrder.orderNbr, Equal <Current <POOrder.bLOrderNbr> > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1] { (object)poOrder1 }); if (poOrder2 != null) { poOrder1.VendorRefNbr = poOrder2.VendorRefNbr; } } if (OrderType == "DP") { poOrder1.ShipDestType = "C"; poOrder1.ShipToBAccountID = soOrder.CustomerID; poOrder1.ShipToLocationID = soOrder.CustomerLocationID; } else if (current.ShipDestType == "S") { poOrder1.ShipDestType = "S"; poOrder1.SiteID = demand.POSiteID; } if (PXAccess.FeatureInstalled <PX.Objects.CS.FeaturesSet.multicurrency>()) { docgraph.currencyinfo.Current.CuryID = (string)null; } poOrder1 = docgraph.Document.Update(poOrder1); if (OrderType == "DP") { SOAddress soAddress = (SOAddress)PXSelectBase <SOAddress, PXSelect <SOAddress, Where <SOAddress.addressID, Equal <Required <PX.Objects.SO.SOOrder.shipAddressID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipAddressID); bool?isDefaultAddress = soAddress.IsDefaultAddress; bool flag2 = false; if (isDefaultAddress.GetValueOrDefault() == flag2 & isDefaultAddress.HasValue) { SharedRecordAttribute.CopyRecord <POOrder.shipAddressID>(docgraph.Document.Cache, (object)poOrder1, (object)soAddress, true); } SOContact soContact = (SOContact)PXSelectBase <SOContact, PXSelect <SOContact, Where <SOContact.contactID, Equal <Required <PX.Objects.SO.SOOrder.shipContactID> > > > .Config> .Select((PXGraph)docgraph, (object)soOrder.ShipContactID); bool?isDefaultContact = soContact.IsDefaultContact; bool flag3 = false; if (isDefaultContact.GetValueOrDefault() == flag3 & isDefaultContact.HasValue) { SharedRecordAttribute.CopyRecord <POOrder.shipContactID>(docgraph.Document.Cache, (object)poOrder1, (object)soContact, true); } DateTime?expectedDate = poOrder1.ExpectedDate; DateTime?requestDate = soOrder.RequestDate; if (expectedDate.HasValue & requestDate.HasValue && expectedDate.GetValueOrDefault() < requestDate.GetValueOrDefault()) { poOrder1 = PXCache <POOrder> .CreateCopy(poOrder1); poOrder1.ExpectedDate = soOrder.RequestDate; poOrder1 = docgraph.Document.Update(poOrder1); } } } else if (!docgraph.Document.Cache.ObjectsEqual((object)docgraph.Document.Current, (object)poOrder1)) { docgraph.Document.Current = (POOrder)docgraph.Document.Search <POOrder.orderNbr>((object)poOrder1.OrderNbr, (object)poOrder1.OrderType); } poOrder1.UpdateVendorCost = new bool?(false); POLine poLine1 = (POLine)null; DocumentList <POLine> documentList2; if (!dictionary.TryGetValue(demand.PlanType, out documentList2)) { documentList2 = dictionary[demand.PlanType] = new DocumentList <POLine>((PXGraph)docgraph); } if (OrderType == "RO" && demand.PlanType != "6B") { System.Collections.Generic.List <FieldLookup> fieldLookupList2 = new System.Collections.Generic.List <FieldLookup>(); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorID>((object)demand.VendorID)); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.vendorLocationID>((object)demand.VendorLocationID)); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.siteID>((object)demand.POSiteID)); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.inventoryID>((object)demand.InventoryID)); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.subItemID>((object)demand.SubItemID)); fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.requestedDate>((object)(DateTime?)soLineSplit3?.ShipDate)); int?nullable2; if (soLineSplit3 == null) { nullable1 = new int?(); nullable2 = nullable1; } else { nullable2 = soLineSplit3.ProjectID; } fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.projectID>((object)nullable2)); int?nullable3; if (soLineSplit3 == null) { nullable1 = new int?(); nullable3 = nullable1; } else { nullable3 = soLineSplit3.TaskID; } fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.taskID>((object)nullable3)); int?nullable4; if (soLineSplit3 == null) { nullable1 = new int?(); nullable4 = nullable1; } else { nullable4 = soLineSplit3.CostCodeID; } fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.costCodeID>((object)nullable4)); int?nullable5; if (soLineSplit3 == null) { nullable1 = new int?(); nullable5 = nullable1; } else { nullable5 = soLineSplit3.LineNbr; } fieldLookupList2.Add((FieldLookup) new FieldLookup <POLine.lineNbr>((object)nullable5)); System.Collections.Generic.List <FieldLookup> fieldLookupList3 = fieldLookupList2; bool?nullable6 = current.CopyLineDescrSO; bool flag2 = true; if (nullable6.GetValueOrDefault() == flag2 & nullable6.HasValue && soLineSplit3 != null) { fieldLookupList3.Add((FieldLookup) new FieldLookup <POLine.tranDesc>((object)soLineSplit3.TranDesc)); poLine1 = documentList2.Find(fieldLookupList3.ToArray()); int num2; if (poLine1 != null) { nullable6 = current.CopyLineNoteSO; bool flag3 = true; if (nullable6.GetValueOrDefault() == flag3 & nullable6.HasValue) { num2 = PXNoteAttribute.GetNote(docgraph.Caches[typeof(POLine)], (object)poLine1) != null ? 1 : (PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3) != null ? 1 : 0); goto label_67; } } num2 = 0; label_67: if (num2 != 0) { poLine1 = (POLine)null; } } else { poLine1 = documentList2.Find(fieldLookupList3.ToArray()); } } POLine dest = poLine1 ?? new POLine(); POLine copy1; if (dest.OrderNbr == null) { docgraph.FillPOLineFromDemand(dest, demand, OrderType, soLineSplit3); POLine line = docgraph.Transactions.Insert(dest); bool? copyLineNoteSo = current.CopyLineNoteSO; bool flag2 = true; if (copyLineNoteSo.GetValueOrDefault() == flag2 & copyLineNoteSo.HasValue && soLineSplit3 != null) { PXNoteAttribute.SetNote(docgraph.Transactions.Cache, (object)line, PXNoteAttribute.GetNote(docgraph.Caches[typeof(POOrderEntry.SOLineSplit3)], (object)soLineSplit3)); } if (docgraph.onCopyPOLineFields != null) { docgraph.onCopyPOLineFields(demand, line); } copy1 = PXCache <POLine> .CreateCopy(line); documentList2.Add(copy1); } else { copy1 = PXCache <POLine> .CreateCopy((POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POOrder.orderType> >, And <POLine.orderNbr, Equal <Current <POOrder.orderNbr> >, And <POLine.lineNbr, Equal <Current <POLine.lineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1] { (object)dest })); POLine poLine2 = copy1; Decimal?orderQty1 = poLine2.OrderQty; Decimal?orderQty2 = demand.OrderQty; poLine2.OrderQty = orderQty1.HasValue & orderQty2.HasValue ? new Decimal?(orderQty1.GetValueOrDefault() + orderQty2.GetValueOrDefault()) : new Decimal?(); } if (demand.PlanType == "6B" || demand.PlanType == "6E") { str1 = demand.PlanType == "6B" ? "66" : "6D"; demand.FixedSource = "P"; copy1.POType = soLineSplit3.POType; copy1.PONbr = soLineSplit3.PONbr; copy1.POLineNbr = soLineSplit3.POLineNbr; POLine poLine2 = (POLine)PXSelectBase <POLine, PXSelect <POLine, Where <POLine.orderType, Equal <Current <POLine.pOType> >, And <POLine.orderNbr, Equal <Current <POLine.pONbr> >, And <POLine.lineNbr, Equal <Current <POLine.pOLineNbr> > > > > > .Config> .SelectSingleBound((PXGraph)docgraph, new object[1] { (object)copy1 }); if (poLine2 != null) { Decimal?nullable2 = demand.PlanQty; Decimal?baseOpenQty = poLine2.BaseOpenQty; if (nullable2.GetValueOrDefault() > baseOpenQty.GetValueOrDefault() & (nullable2.HasValue & baseOpenQty.HasValue)) { POLine poLine3 = copy1; Decimal?orderQty = poLine3.OrderQty; nullable2 = demand.OrderQty; poLine3.OrderQty = orderQty.HasValue & nullable2.HasValue ? new Decimal?(orderQty.GetValueOrDefault() - nullable2.GetValueOrDefault()) : new Decimal?(); if (string.Equals(copy1.UOM, poLine2.UOM)) { POLine poLine4 = copy1; nullable2 = poLine4.OrderQty; Decimal?openQty = poLine2.OpenQty; poLine4.OrderQty = nullable2.HasValue & openQty.HasValue ? new Decimal?(nullable2.GetValueOrDefault() + openQty.GetValueOrDefault()) : new Decimal?(); } else { PXDBQuantityAttribute.CalcBaseQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1); POLine poLine4 = copy1; Decimal?baseOrderQty = poLine4.BaseOrderQty; nullable2 = poLine2.BaseOpenQty; poLine4.BaseOrderQty = baseOrderQty.HasValue & nullable2.HasValue ? new Decimal?(baseOrderQty.GetValueOrDefault() + nullable2.GetValueOrDefault()) : new Decimal?(); PXDBQuantityAttribute.CalcTranQty <POLine.orderQty>(docgraph.Transactions.Cache, (object)copy1); } pxErrorLevel = PXErrorLevel.RowWarning; empty += PXMessages.LocalizeFormatNoPrefixNLA("Order Quantity reduced to Blanket Order: '{0}' Open Qty. for this item", (object)copy1.PONbr); } copy1.CuryUnitCost = poLine2.CuryUnitCost; copy1.UnitCost = poLine2.UnitCost; } } copy1.SiteID = POCreate_Extension.GetWasrehouseByBranch((PXGraph)docgraph, copy1.BranchID); short? vleadTime = docgraph.location.Current.VLeadTime; POLine poLine5 = copy1; DateTime dateTime = soLineSplit3.ShipDate.Value; ref DateTime local = ref dateTime; short? nullable7 = vleadTime; nullable1 = nullable7.HasValue ? new int?((int)nullable7.GetValueOrDefault()) : new int?(); int num3 = 0; double num4 = nullable1.GetValueOrDefault() > num3 & nullable1.HasValue ? (double)-vleadTime.Value : -14.0; DateTime?nullable8 = new DateTime?(local.AddDays(num4)); poLine5.RequestedDate = nullable8; POLine poLine6 = docgraph.Transactions.Update(copy1); PXCache cach = docgraph.Caches[typeof(INItemPlan)]; POCreate_Extension.CreateSplitDemand2(cach, demand); cach.SetStatus((object)demand, PXEntryStatus.Updated); demand.SupplyPlanID = poLine6.PlanID; if (str1 != null) { cach.RaiseRowDeleted((object)demand); demand.PlanType = str1; cach.RaiseRowInserted((object)demand); } if (soLineSplit3 != null) { int num2; if (demand.AlternateID != null) { nullable1 = demand.InventoryID; num2 = nullable1.HasValue ? 1 : 0; } else { num2 = 0; } if (num2 != 0) { PXSelectBase <INItemXRef> pxSelectBase = (PXSelectBase <INItemXRef>) new PXSelect <INItemXRef, Where <INItemXRef.inventoryID, Equal <Required <INItemXRef.inventoryID> >, And <INItemXRef.alternateID, Equal <Required <INItemXRef.alternateID> > > > >((PXGraph)docgraph); INItemXRef inItemXref1 = (INItemXRef)pxSelectBase.Select((object)demand.InventoryID, (object)demand.AlternateID); if (inItemXref1 != null && inItemXref1.AlternateType == "GLBL") { int num5; if (poLine6.AlternateID != null) { nullable1 = poLine6.InventoryID; num5 = nullable1.HasValue ? 1 : 0; } else { num5 = 0; } if (num5 != 0) { INItemXRef inItemXref2 = (INItemXRef)pxSelectBase.Select((object)poLine6.InventoryID, (object)poLine6.AlternateID); if (inItemXref2 != null && inItemXref2.AlternateType == "GLBL") { poLine6.AlternateID = demand.AlternateID; } } else { poLine6.AlternateID = demand.AlternateID; } } } soLineSplit3.POType = poLine6.OrderType; soLineSplit3.PONbr = poLine6.OrderNbr; soLineSplit3.POLineNbr = poLine6.LineNbr; soLineSplit3.RefNoteID = docgraph.Document.Current.NoteID; PX.Objects.SO.SOLine soLine = SelectFrom <PX.Objects.SO.SOLine> .Where <PX.Objects.SO.SOLine.orderType.IsEqual <P.AsString> .And <PX.Objects.SO.SOLine.orderNbr.IsEqual <P.AsString> .And <PX.Objects.SO.SOLine.lineNbr.IsEqual <P.AsInt> > > > .View.ReadOnly.Select((PXGraph)docgraph, (object)soLineSplit3.OrderType, (object)soLineSplit3.OrderNbr, (object)soLineSplit3.LineNbr); POLineExt extension1 = poLine6.GetExtension <POLineExt>(); SOLineExt extension2 = soLine.GetExtension <SOLineExt>(); extension1.UsrEndCustomerID = extension2.UsrEndCustomerID; extension1.UsrNonStockItem = extension2.UsrNonStockItem; extension1.UsrProjectNbr = extension2.UsrProjectNbr; if (!string.IsNullOrEmpty(extension2.UsrProjectNbr)) { FLXProject flxProject = SelectFrom <FLXProject> .Where <FLXProject.projectNbr.IsEqual <P.AsString> > .View.ReadOnly.Select((PXGraph)docgraph, (object)extension2.UsrProjectNbr); extension1.UsrCust2Factory = flxProject.Cust2Factory; extension1.UsrFactoryPN = flxProject.FactoryPN; } docgraph.GetExtension <POOrderEntry_Extension>().UpdateSOLine(soLineSplit3, docgraph.Document.Current.VendorID, true); docgraph.FixedDemand.Cache.SetStatus((object)soLineSplit3, PXEntryStatus.Updated); } if (docgraph.Transactions.Cache.IsInsertedUpdatedDeleted) { using (PXTransactionScope transactionScope = new PXTransactionScope()) { docgraph.Save.Press(); if (demand.PlanType == "90") { docgraph.Replenihment.Current = (INReplenishmentOrder)docgraph.Replenihment.Search <INReplenishmentOrder.noteID>((object)demand.RefNoteID); if (docgraph.Replenihment.Current != null) { INReplenishmentLine copy2 = PXCache <INReplenishmentLine> .CreateCopy(docgraph.ReplenishmentLines.Insert(new INReplenishmentLine())); copy2.InventoryID = poLine6.InventoryID; copy2.SubItemID = poLine6.SubItemID; copy2.UOM = poLine6.UOM; copy2.VendorID = poLine6.VendorID; copy2.VendorLocationID = poLine6.VendorLocationID; copy2.Qty = poLine6.OrderQty; copy2.POType = poLine6.OrderType; copy2.PONbr = docgraph.Document.Current.OrderNbr; copy2.POLineNbr = poLine6.LineNbr; copy2.SiteID = demand.POSiteID; copy2.PlanID = demand.PlanID; docgraph.ReplenishmentLines.Update(copy2); docgraph.Caches[typeof(INItemPlan)].Delete((object)demand); docgraph.Save.Press(); } } transactionScope.Complete(); } if (pxErrorLevel == PXErrorLevel.RowInfo) { PXProcessing <POFixedDemand> .SetInfo(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty); } else { PXProcessing <POFixedDemand> .SetWarning(list.IndexOf(demand), PXMessages.LocalizeFormatNoPrefixNLA("Purchase Order '{0}' created.", (object)docgraph.Document.Current.OrderNbr) + "\r\n" + empty); } if (documentList1.Find((object)docgraph.Document.Current) == null) { documentList1.Add(docgraph.Document.Current); } } }
public static void Redirect(PXCache sender, CATran catran) { if (catran == null) { return; } if (catran.OrigTranType == CAAPARTranType.GLEntry) { JournalEntry graph = PXGraph.CreateInstance <JournalEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.BatchModule.Current = PXSelect <Batch, Where <Batch.module, Equal <Required <Batch.module> >, And <Batch.batchNbr, Equal <Required <Batch.batchNbr> > > > > .Select(graph, catran.OrigModule, catran.OrigRefNbr); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.AP && (catran.OrigTranType == AP.APDocType.QuickCheck || catran.OrigTranType == AP.APDocType.VoidQuickCheck)) { APQuickCheckEntry graph = PXGraph.CreateInstance <APQuickCheckEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = PXSelect <APQuickCheck, Where <APQuickCheck.refNbr, Equal <Required <APQuickCheck.refNbr> >, And <APQuickCheck.docType, Equal <Required <APQuickCheck.docType> > > > > .Select(graph, catran.OrigRefNbr, catran.OrigTranType); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.AP && catran.OrigTranType == CATranType.CABatch) { CABatchEntry graph = PXGraph.CreateInstance <CABatchEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = PXSelect <CABatch, Where <CABatch.batchNbr, Equal <Required <CATran.origRefNbr> > > > .Select(graph, catran.OrigRefNbr); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.AP) { APPaymentEntry graph = PXGraph.CreateInstance <APPaymentEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = (APPayment)PXSelect <APPayment, Where <APPayment.refNbr, Equal <Required <APPayment.refNbr> >, And <APPayment.docType, Equal <Required <APPayment.docType> > > > > .Select(graph, catran.OrigRefNbr, catran.OrigTranType); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.AR && (catran.OrigTranType == ARDocType.CashSale || catran.OrigTranType == ARDocType.CashReturn)) { ARCashSale document = (ARCashSale)PXSelect <ARCashSale, Where <ARCashSale.refNbr, Equal <Required <ARCashSale.refNbr> >, And <ARCashSale.docType, Equal <Required <ARCashSale.docType> > > > > .Select(sender.Graph, catran.OrigRefNbr, catran.OrigTranType); if (document.OrigModule == BatchModule.SO && document.Released == false) { SO.SOInvoiceEntry graph = PXGraph.CreateInstance <SO.SOInvoiceEntry>(); graph.Clear(); sender.IsDirty = false; graph.Document.Current = (ARInvoice)PXSelect <ARInvoice, Where <ARInvoice.refNbr, Equal <Required <ARInvoice.refNbr> >, And <ARInvoice.docType, Equal <Required <ARInvoice.docType> > > > > .Select(sender.Graph, catran.OrigRefNbr, catran.OrigTranType); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else { ARCashSaleEntry graph = PXGraph.CreateInstance <ARCashSaleEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = document; throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } } else if (catran.OrigModule == GL.BatchModule.AR) { ARPaymentEntry graph = PXGraph.CreateInstance <ARPaymentEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = (ARPayment)PXSelect <ARPayment, Where <ARPayment.refNbr, Equal <Required <ARPayment.refNbr> >, And <ARPayment.docType, Equal <Required <ARPayment.docType> > > > > .Select(graph, catran.OrigRefNbr, catran.OrigTranType); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.CA && catran.OrigTranType == CATranType.CAAdjustment) { CATranEntry graph = PXGraph.CreateInstance <CATranEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.CAAdjRecords.Current = PXSelect <CAAdj, Where <CAAdj.tranID, Equal <Required <CAAdj.tranID> > > > .Select(graph, catran.TranID); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.CA && catran.OrigTranType == CATranType.CATransferExp) { CATranEntry graph = PXGraph.CreateInstance <CATranEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.CAAdjRecords.Current = PXSelect <CAAdj, Where <CAAdj.adjTranType, Equal <CAAPARTranType.cATransferExp>, And <CAAdj.transferNbr, Equal <Required <CATran.origRefNbr> > > > > .Select(graph, catran.OrigRefNbr); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else if (catran.OrigModule == GL.BatchModule.CA) { if (catran.OrigTranType == CATranType.CADeposit || catran.OrigTranType == CATranType.CAVoidDeposit) { CADepositEntry graph = PXGraph.CreateInstance <CADepositEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Document.Current = PXSelect <CADeposit, Where <CADeposit.tranType, Equal <Required <CADeposit.tranType> >, And <CADeposit.refNbr, Equal <Required <CADeposit.refNbr> > > > > .Select(graph, catran.OrigTranType, catran.OrigRefNbr); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } else { CashTransferEntry graph = PXGraph.CreateInstance <CashTransferEntry>(); graph.Clear(); if (sender != null) { sender.IsDirty = false; } graph.Transfer.Current = PXSelect <CATransfer, Where <CATransfer.tranIDOut, Equal <Required <CATransfer.tranIDOut> >, Or <CATransfer.tranIDIn, Equal <Required <CATransfer.tranIDIn> > > > > .Select(graph, catran.TranID, catran.TranID); throw new PXRedirectRequiredException(graph, true, "Document") { Mode = PXBaseRedirectException.WindowMode.NewWindow }; } } }
/// <summary> /// Creates one or more documents in Inventory depending of the number of FSAppointmentInventoryItem in the list [fsAppointmentInventoryItemRows]. /// </summary> public virtual int CreateDocumentsInIN(FSPostBatch fsPostBatchRow, List <FSAppointmentDet> fsAppointmentInventoryItemRows, List <SharedClasses.AppointmentInventoryItemGroup> listGroupToUpdateInInventory, UpdateInventoryFilter filter) { INReceiptEntry graphINReceiptEntry = PXGraph.CreateInstance <INReceiptEntry>(); INIssueEntry graphINIssueEntry = PXGraph.CreateInstance <INIssueEntry>(); int linesPosted = 0; foreach (SharedClasses.AppointmentInventoryItemGroup groupToUpdateInInventory in listGroupToUpdateInInventory) { string iNRefNbr = null; string iNDocType = null; foreach (SharedClasses.AppointmentInventoryItemInfo appointmentInventoryItemInfoRow in groupToUpdateInInventory.AppointmentInventoryItems) { using (var ts_GroupToUpdateInInventory = new PXTransactionScope()) { try { if (groupToUpdateInInventory.ServiceType == ID.Service_Action_Type.PICKED_UP_ITEMS) { // create receipt CreateDocumentReceipt(graphINReceiptEntry, appointmentInventoryItemInfoRow, fsAppointmentInventoryItemRows[appointmentInventoryItemInfoRow.Index], filter.DocumentDate, filter.FinPeriodID, fsPostBatchRow, ref iNRefNbr, ref iNDocType); } else if (groupToUpdateInInventory.ServiceType == ID.Service_Action_Type.DELIVERED_ITEMS) { // create issue CreateDocumentIssue(graphINIssueEntry, appointmentInventoryItemInfoRow, fsAppointmentInventoryItemRows[appointmentInventoryItemInfoRow.Index], filter.DocumentDate, filter.FinPeriodID, fsPostBatchRow, ref iNRefNbr, ref iNDocType); } else if (groupToUpdateInInventory.ServiceType == ID.Service_Action_Type.NO_ITEMS_RELATED) { PXProcessing <FSAppointmentDet> .SetError(appointmentInventoryItemInfoRow.Index, TX.Error.APPOINTMENT_ITEM_CANNOT_BE_POSTED_TO_IN_NO_ITEMS_RELATED); } PXProcessing <FSAppointmentDet> .SetInfo(appointmentInventoryItemInfoRow.Index, TX.Messages.RECORD_PROCESSED_SUCCESSFULLY); linesPosted++; ts_GroupToUpdateInInventory.Complete(); } catch (Exception e) { Exception latestException = ExceptionHelper.GetExceptionWithContextMessage(PXMessages.Localize(TX.Messages.COULD_NOT_PROCESS_RECORD), e); PXProcessing <FSAppointmentDet> .SetError(appointmentInventoryItemInfoRow.Index, latestException); ts_GroupToUpdateInInventory.Dispose(); graphINReceiptEntry.Actions.PressCancel(); } } } } return(linesPosted); }
public virtual void viewSubcontract() { var graph = PXGraph.CreateInstance <SubcontractEntry>(); ViewPoEntity(graph, ApMessages.ViewSubcontract, x => x.OrderType == POOrderType.RegularSubcontract); }
/// <summary> /// Creates or updates the smartsheet users listed in "EPUsersListSS" master table /// </summary> /// <param name="refreshedToken"></param> public void GetUsersSS(string refreshedToken = "") { //The smartsheet account should support the UserResources.ListUsers() functionality //Otherwise the message "The operation you are attempting to perform is not supported by your plan." is received // User connection with SmartSheet Users userRecord = PXSelect < Users, Where <Users.pKID, Equal <Required <AccessInfo.userID> > > > .Select(this.Base, this.Base.Accessinfo.UserID); if (userRecord == null) { throw new PXException(SmartsheetConstants.Messages.ERROR_USER); } UsersSSExt userRecordSSExt = PXCache <Users> .GetExtension <UsersSSExt>(userRecord); try { Token token = new Token(); token.AccessToken = (String.IsNullOrEmpty(refreshedToken)) ? userRecordSSExt.UsrSmartsheetToken : refreshedToken; SmartsheetClient smartsheetClient = new SmartsheetBuilder() .SetAccessToken(token.AccessToken) .SetDateTimeFixOptOut(true) //See NOTE ON 2.93.0 RELEASE on https://github.com/smartsheet-platform/smartsheet-csharp-sdk .Build(); PaginatedResult <User> smartsheetUserSet = smartsheetClient.UserResources.ListUsers(null, null); if (smartsheetUserSet.TotalCount > 0) { PXCache <EPUsersListSS> usersListCache = this.Base.Caches <EPUsersListSS>(); foreach (User dataUsers in smartsheetUserSet.Data) { EPUsersListSS epUsersListSSRow = UserList.Select().Where(x => ((EPUsersListSS)x).Ssuserid == dataUsers.Id).FirstOrDefault(); if (epUsersListSSRow == null) { EPUsersListSS ci = (EPUsersListSS)usersListCache.Insert(new EPUsersListSS { Ssuserid = dataUsers.Id, FirstName = dataUsers.FirstName, LastName = dataUsers.LastName, Email = dataUsers.Email }); } else { epUsersListSSRow.FirstName = dataUsers.FirstName; epUsersListSSRow.LastName = dataUsers.LastName; epUsersListSSRow.Email = dataUsers.Email; usersListCache.Update(epUsersListSSRow); } } this.Base.Persist(); } } catch (Exception e) { if (e.Message.Contains(SmartsheetConstants.SSConstants.EXPIRED_TOKEN_MESSAGE)) { MyProfileMaint profileMaintGraph = PXGraph.CreateInstance <MyProfileMaint>(); MyProfileMaintExt graphExtended = profileMaintGraph.GetExtension <MyProfileMaintExt>(); string updatedToken = graphExtended.RefreshSmartsheetToken(); GetUsersSS(updatedToken); } else { throw new PXException(e.Message); } } }