public static bool Post(List <ProcessInfo <Batch> > infoList, bool isMassProcess) { PostGraph pg = PXGraph.CreateInstance <PostGraph>(); PMSetup setup = PXSelect <PMSetup> .Select(pg); bool failed = false; if (setup != null && setup.AutoPost == true) { foreach (ProcessInfo <Batch> t in infoList) { foreach (Batch batch in t.Batches) { try { pg.Clear(); pg.PostBatchProc(batch); } catch (Exception e) { if (isMassProcess) { failed = true; PXProcessing <PMRegister> .SetError(t.RecordIndex, e is PXOuterException ?e.Message + "\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message); } else { throw new PXMassProcessException(t.RecordIndex, new PXException(PXMessages.LocalizeNoPrefix(Messages.PostToGLFailed) + "\r\n" + e.Message, e)); } } } } } return(!failed); }
protected virtual INTran PrepareTransaction(INCostStatus layer, INSite site, InventoryItem inventoryItem, decimal?tranCost) { try { ValidateProjectLocation(site, inventoryItem); } catch (PXException ex) { PXProcessing <INUpdateStdCostRecord> .SetError(ex.Message); return(null); } INTran tran = new INTran(); if (layer.LayerType == INLayerType.Oversold) { tran.TranType = INTranType.NegativeCostAdjustment; } else { tran.TranType = INTranType.StandardCostAdjustment; } tran.BranchID = site.BranchID; tran.InvtAcctID = layer.AccountID; tran.InvtSubID = layer.SubID; var postClass = INPostClass.PK.Find(this, inventoryItem.PostClassID); tran.AcctID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevAcctID> (je, inventoryItem, site, postClass); tran.SubID = INReleaseProcess.GetAccountDefaults <INPostClass.stdCstRevSubID> (je, inventoryItem, site, postClass); tran.InventoryID = layer.InventoryID; tran.SubItemID = layer.CostSubItemID; tran.SiteID = layer.CostSiteID; tran.Qty = 0m; tran.TranCost = tranCost; return(tran); }
/// <summary> /// Generate sales order line. /// </summary> public static void CreateOrderDetail(SOOrderEntry orderEntry, LUM3DCartSetup curSetup, SOOrder order) { try { List <MyArray> list = GetResponse(curSetup, "3dCartWebAPI/v2/Orders/" + order.CustomerOrderNbr).Result; UpdateSOContactAddress(orderEntry, list, order); var itemList = list.Find(x => x.OrderItemList.Count > 0).OrderItemList; for (int i = 0; i < itemList.Count; i++) { SOLine line = orderEntry.Transactions.Cache.CreateInstance() as SOLine; line.InventoryID = GetAcuInventoryID(orderEntry, itemList[i].ItemID); line.OrderQty = (decimal)itemList[i].ItemQuantity; line.UnitPrice = (decimal)itemList[i].ItemUnitPrice; orderEntry.Transactions.Insert(line); } orderEntry.Taxes.Cache.SetValueExt <SOTaxTran.curyTaxAmt>(orderEntry.Taxes.Current, list[0].SalesTax + list[0].SalesTax2); orderEntry.CurrentDocument.SetValueExt <SOOrder.paymentMethodID>(order, GetAcuPymtMethod(orderEntry, order.CustomerID, list[0].BillingPaymentMethod)); string tranID = list.Find(x => x.TransactionList.Count > 0).TransactionList[0].TransactionID; int index = tranID.IndexOf(':') + 2; // Because there is a space between the ':' of transaction ID. order.CustomerRefNbr = tranID.Contains(PX.Objects.PO.Messages.Completed) ? tranID.Substring(index, tranID.Length - index) : null; // Refer to PX.AmazonIntegration project SetDocumentLevelDiscountandTaxData() to manully update SOOrder total amount fields. order.CuryTaxTotal = orderEntry.Taxes.Current.CuryTaxAmt; order.CuryOrderTotal += order.CuryTaxTotal; } catch (PXException ex) { PXProcessing.SetError <LUM3DCartProcessOrder>(ex.Message); throw; } }
private static void Process(List <Screen> list, FolderSynchronisationOptionsFilter filter) { FileHandler graph = PXGraph.CreateInstance <FileHandler>(); var userTokenHandler = PXGraph.CreateInstance <UserTokenHandler>(); bool failed = false; if (userTokenHandler.GetCurrentUser() == null || userTokenHandler.GetCurrentUser().AccessToken == null || userTokenHandler.GetCurrentUser().RefreshToken == null) { throw new Exception(Messages.BoxUserNotFoundOrTokensExpired); } var rootFolder = graph.GetRootFolder(); for (int i = 0; i < list.Count; i++) { try { graph.Clear(); graph.SynchronizeScreen(list[i], rootFolder, filter.IsForceRescaningFolder.GetValueOrDefault()); if (filter.IsForceUpdatingFolderDescription == true) { graph.UpdateFolderDescriptions(list[i]); } PXProcessing <Screen> .SetInfo(i, ActionsMessages.RecordProcessed); } catch (Exception e) { failed = true; PXProcessing <Screen> .SetError(i, e is PXOuterException?e.Message + "\r\n" + string.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message); } } if (failed) { throw new PXException(Messages.SynchronizationError); } }
public static void ReleaseDoc(List <APInvoiceLCInfo> list) { LandedCostProcess lcGraph = PXGraph.CreateInstance <LandedCostProcess>(); PXSelectBase <LandedCostTran> select = new PXSelect <LandedCostTran, Where <LandedCostTran.source, Equal <LandedCostTranSource.fromAP>, And <LandedCostTran.processed, Equal <False>, And <LandedCostTran.aPRefNbr, Equal <Required <LandedCostTran.aPRefNbr> >, And <LandedCostTran.aPDocType, Equal <Required <LandedCostTran.aPDocType> > > > > > >(lcGraph); bool failed = false; int index = 0; foreach (APInvoiceLCInfo iRct in list) { if ((iRct.Selected ?? false)) { List <LandedCostTran> trans = new List <LandedCostTran>(); foreach (LandedCostTran itr in select.Select(iRct.RefNbr, iRct.DocType)) { trans.Add(itr); } try { lcGraph.Clear(); lcGraph.ReleaseLCTrans(trans, null, null); PXProcessing <APRegister> .SetInfo(index, ActionsMessages.RecordProcessed); } catch (Exception e) { PXProcessing <APInvoiceLCInfo> .SetError(index, e); failed = true; } } index++; } if (failed) { throw new PXException(Messages.ProcessingOfLandedCostTransForAPDocFailed); } }
private void ValidateAmounts(IEnumerable <DocumentDetails> documents) { bool hasAmountProblems = false; for (int i = 0; i < documents.Count(); i++) { decimal paid = documents.ElementAt(i).TotalPay; decimal claim = documents.ElementAt(i).Document.CuryRUTROTDistributedAmt ?? 0.0m; decimal maxDiff = GetDistributor(documents.ElementAt(i).Document.CuryInfoID).FinishStep; decimal deductionPct = (documents.ElementAt(i).Document.RUTROTDeductionPct ?? 0.0m) * 0.01m; decimal minPay = claim / deductionPct * (1 - deductionPct); if (minPay - paid > maxDiff) { hasAmountProblems = true; PXProcessing.SetError(i, new PXException(RUTROTMessages.PaymentMustCoverDeductible)); } if (claim + paid - (documents.ElementAt(i).Document.CuryOrigDocAmt ?? 0.0m) > maxDiff) { hasAmountProblems = true; PXProcessing.SetError(i, new PXException(RUTROTMessages.ClaimedPaidMustNotExceedTotal)); } } if (hasAmountProblems) { throw new PXException(RUTROTMessages.SomeAmountsIncorrect); } decimal totalClaimAmt = documents.Sum(d => d.Document.CuryRUTROTTotalAmt ?? 0.0m); if (totalClaimAmt > 50000) { throw new PXException(RUTROTMessages.ClaimedTotalTooMuch); } }
public ConvertItemsToEquipmentProcess() { SMEquipmentMaint graphSMEquipmentMaint; InventoryItems.SetProcessDelegate( delegate(List <SoldInventoryItem> inventoryItemRows) { graphSMEquipmentMaint = CreateInstance <SMEquipmentMaint>(); bool error = false; for (int i = 0; i < inventoryItemRows.Count; i++) { SoldInventoryItem soldInventoryItemRow = inventoryItemRows[i]; error = false; try { int?iteratorMax = (int?)(soldInventoryItemRow.ShippedQty > 0m ? soldInventoryItemRow.ShippedQty : soldInventoryItemRow.Qty); InventoryItem inventoryItemRow = SharedFunctions.GetInventoryItemRow(graphSMEquipmentMaint, soldInventoryItemRow.InventoryID); for (int j = 0; j < iteratorMax; j++) { SharedFunctions.CreateSoldEquipment(graphSMEquipmentMaint, soldInventoryItemRow, null, null, null, null, inventoryItemRow); } } catch (Exception e) { error = true; PXProcessing <SoldInventoryItem> .SetError(i, e.Message); } if (error == false) { PXProcessing <SoldInventoryItem> .SetInfo(i, TX.Messages.RECORD_PROCESSED_SUCCESSFULLY); } } }); }
public virtual void CreateAdjustments(INUpdateStdCostRecord itemsite, Func <INCostStatus, decimal?> getTranCost) { var localAdjustments = new List <INRegister>(); foreach (INCostStatus layer in LoadCostStatuses(itemsite)) { decimal?tranCost = getTranCost(layer); var doc = AddToAdjustment(layer, tranCost); if (doc != null && !localAdjustments.Contains(doc)) { localAdjustments.Add(doc); } } if (localAdjustments.Any()) { SaveAdjustment(); PXProcessing <INUpdateStdCostRecord> .SetInfo( PXMessages.LocalizeFormatNoPrefixNLA(Messages.AdjustmentsCreated, string.Join(", ", localAdjustments.Select(x => x.RefNbr)))); } }
private static ARInvoice CreatePPDCreditMemo(ARInvoiceEntry ie, ARPPDCreditMemoParameters filter, List <PendingPPDCreditMemoApp> list) { int index = 0; ARInvoice invoice; try { ie.Clear(PXClearOption.ClearAll); PXUIFieldAttribute.SetError(ie.Document.Cache, null, null, null); invoice = ie.CreatePPDCreditMemo(filter, list, ref index); PXProcessing <PendingPPDCreditMemoApp> .SetInfo(index, ActionsMessages.RecordProcessed); } catch (Exception e) { PXProcessing <PendingPPDCreditMemoApp> .SetError(index, e); invoice = null; } return(invoice); }
private static List <ScheduledTran> GetValidatedItems(List <ScheduledTran> items, ScheduleMaint scheduleMaint) { List <ScheduledTran> validatedItems = new List <ScheduledTran>(); foreach (ScheduledTran item in items) { PXProcessing <ScheduledTran> .SetCurrentItem(item); try { FinPeriod finPeriod = scheduleMaint.GetService <IFinPeriodRepository>().FindByID(PXAccess.GetParentOrganizationID(item.BranchID), item.FinPeriodID); scheduleMaint.GetService <IFinPeriodUtils>().CanPostToPeriod(finPeriod).RaiseIfHasError(); validatedItems.Add(item); } catch (Exception ex) { PXProcessing <ScheduledTran> .SetError(ex.Message); } } return(validatedItems); }
public static void Process(List <SOOrder> list, bool isMassProcess) { Stopwatch sw = new Stopwatch(); sw.Start(); SOOrderEntry rg = PXGraph.CreateInstance <SOOrderEntry>(); rg.RowSelecting.RemoveHandler <SOOrder>(rg.SOOrder_RowSelecting); sw.Stop(); Debug.Print("{0} PXGraph.CreateInstance<SOOrderEntry> in {1} millisec", DateTime.Now.TimeOfDay, sw.ElapsedMilliseconds); for (int i = 0; i < list.Count; i++) { try { rg.Clear(); sw.Reset(); sw.Start(); rg.Document.Current = PXSelect <SOOrder, Where <SOOrder.orderType, Equal <Required <SOOrder.orderType> >, And <SOOrder.orderNbr, Equal <Required <SOOrder.orderNbr> > > > > .Select(rg, list[i].OrderType, list[i].OrderNbr); sw.Stop(); Debug.Print("{0} Select SOOrder in {1} millisec", DateTime.Now.TimeOfDay, sw.ElapsedMilliseconds); rg.CalculateAvalaraTax(rg.Document.Current); PXProcessing <SOOrder> .SetInfo(i, ActionsMessages.RecordProcessed); } catch (Exception e) { if (isMassProcess) { PXProcessing <SOOrder> .SetError(i, e is PXOuterException?e.Message + "\r\n" + String.Join("\r\n", ((PXOuterException)e).InnerMessages) : e.Message); } else { throw new PXMassProcessException(i, e); } } } }
protected virtual IEnumerable CreateDCLShipment(PXAdapter adapter) { List <SOOrder> list = adapter.Get <SOOrder>().ToList(); var adapterSlice = (adapter.MassProcess, adapter.QuickProcessFlow, adapter.AllowRedirect); for (int i = 0; i < list.Count; i++) { var order = list[i]; if (adapterSlice.MassProcess) { PXProcessing <SOOrder> .SetCurrentItem(order); } DCLShipmentRequestEntity model = new DCLShipmentRequestEntity(); CombineDLCShipmentEntity(model, order); PXNoteAttribute.SetNote(Base.Document.Cache, order, APIHelper.GetJsonString(model)); order.GetExtension <SOOrderExt>().UsrDCLShipmentCreated = true; #region Send Data to DCL for Create Shipment(Implement) //var dclResult = DCLHelper.CallDCLToCreateShipment(this.DCLSetup.Select().RowCast<LUMVendCntrlSetup>().FirstOrDefault(), model); //var response = APIHelper.GetObjectFromString<DCLShipmentResponseEntity>(dclResult.ContentResult); //if (dclResult.StatusCode == System.Net.HttpStatusCode.OK) // order.GetExtension<SOOrderExt>().UsrDCLShipmentCreated = true; //else // throw new PXException(response.error_message); #endregion Base.Document.Cache.Update(order); } Base.Persist(); return(adapter.Get()); }
private bool ProcessJointPayment(APInvoiceEntry invoiceEntry, APPaymentEntry paymentEntry, IReadOnlyCollection <APAdjust> adjustments, PayBillsFilter filter) { var invoice = InvoiceDataProvider.GetInvoice( Base, adjustments.First().AdjdDocType, adjustments.First().AdjdRefNbr); if (IsPaymentCycleWorkflow(invoice)) { PXProcessing <APAdjust> .SetError(JointCheckMessages.PaymentCycleWorkflowIsStarted); return(false); } paymentEntry.Clear(); var jointCheckPreparePaymentCreator = new JointCheckPreparePaymentCreator(invoiceEntry, paymentEntry, Base1); jointCheckPreparePaymentCreator.GenerateChecks(invoice, adjustments, filter); if (Base.APSetup.Current.HoldEntry == false) { lienWaiverHoldPaymentService.HoldPaymentsIfNeeded(invoice.RefNbr, LienWaiverSetup.Current.ShouldStopPayments); Base.Caches <APPayment>().Persist(PXDBOperation.Update); } return(true); }
private static void Process(IList <KCStore> stores) { LoggerProperties.RequestId = GetRequestId(); logger = new KCLoggerProvider(LoggerProperties); int index = 0; foreach (KCStore store in stores) { try { ProcessStore(store); PXProcessing <KCStore> .SetInfo(index, $"Data Exchange for {store.SiteMasterCD} has been processed successfully"); } catch (Exception exception) { string log = KCMessages.ProcessException(store.SiteMasterCD, exception.Message, exception.StackTrace); logger.ClearLoggingIds(); logger.Error(log); PXProcessing <KCStore> .SetError(index, new Exception(log)); } index++; } }
public virtual ProcessingResult CheckFinPeriod(string finPeriodID, int? branchID) { ProcessingResult result = new ProcessingResult(); int? organizationID = PXAccess.GetParentOrganizationID(branchID); FinPeriod period = FinPeriodRepository.FindByID(organizationID, finPeriodID); if (period == null) { result.AddErrorMessage(GL.Messages.FinPeriodDoesNotExistForCompany, FinPeriodIDFormattingAttribute.FormatForError(finPeriodID), PXAccess.GetOrganizationCD(PXAccess.GetParentOrganizationID(branchID))); } else { result = FinPeriodUtils.CanPostToPeriod(period); } if (!result.IsSuccess) { PXProcessing<THistory>.SetError(new PXException(result.GetGeneralMessage())); } return result; }
private static void UpdateSubmitLogDetails(List <ProjectionShipmentDAC> list, SubmitFeedParamaters objSubmitFeedParams, ProjectionShipmentDAC currentRecord, AMSubmitFeedServiceCall.Result item) { objSubmitFeedParams.acmOrderNbr = currentRecord.OrderNbr; objSubmitFeedParams.amazonOrderID = currentRecord.AmazonOrderID; objSubmitFeedParams.objSOAmazonSetup.IntegrationID = currentRecord.IntegrationID; objSubmitFeedParams.shipmentNbr = currentRecord.ShipmentNbr; objSubmitFeedParams.shipmentType = currentRecord.ShipmentType; if (item != null) { objSubmitFeedParams.importOrderStatus = false; objSubmitFeedParams.xmlMessage = item.ResultDescription; objSubmitFeedParams.feedMessage = item.ResultDescription; PXProcessing <ProjectionShipmentDAC> .SetError(list.IndexOf(currentRecord), item.ResultDescription); } else { objSubmitFeedParams.importOrderStatus = true; objSubmitFeedParams.xmlMessage = SOConstants.feedSubmitted; objSubmitFeedParams.feedMessage = SOConstants.feedSubmitted; PXProcessing <ProjectionShipmentDAC> .SetInfo(list.IndexOf(currentRecord), SOConstants.feedSubmitted); } SOLogService.LogSubmitStatus(objSubmitFeedParams); }
//SALES APPROVAL public void ApproveOrder(SalesOrder order, bool isMassProcess = false) { Orders.Current = order; if (order.Status == OrderStatus.Hold) { throw new PXException(String.Format( "Order {0} is On Hold and cannot be approved.", order.OrderNbr)); } else if (order.Status != OrderStatus.Open) { throw new PXException(String.Format( "Order {0} is already approved.", order.OrderNbr)); } order.Status = OrderStatus.Approved; Orders.Update(order); Persist(); if (isMassProcess) { PXProcessing.SetInfo(String.Format( "Order {0} has been successfully approved.", order.OrderNbr)); } }
public static void ReleasePayments(List <APPayment> list, string Action) { APReleaseChecks releaseChecksGraph = CreateInstance <APReleaseChecks>(); APPaymentEntry pe = CreateInstance <APPaymentEntry>(); CABatchEntry be = CreateInstance <CABatchEntry>(); bool failed = false; bool successed = false; List <APRegister> docs = new List <APRegister>(list.Count); foreach (APPayment payment in list) { if (payment.Passed == true) { releaseChecksGraph.TimeStamp = pe.TimeStamp = payment.tstamp; } switch (Action) { case ReleaseChecksFilter.action.ReleaseChecks: payment.Printed = true; break; case ReleaseChecksFilter.action.ReprintChecks: case ReleaseChecksFilter.action.VoidAndReprintChecks: payment.ExtRefNbr = null; payment.Printed = false; break; default: continue; } PXProcessing <APPayment> .SetCurrentItem(payment); if (Action == ReleaseChecksFilter.action.ReleaseChecks) { try { pe.Document.Current = pe.Document.Search <APPayment.refNbr>(payment.RefNbr, payment.DocType); if (pe.Document.Current?.ExtRefNbr != payment.ExtRefNbr) { APPayment payment_copy = PXCache <APPayment> .CreateCopy(pe.Document.Current); payment_copy.ExtRefNbr = payment.ExtRefNbr; pe.Document.Update(payment_copy); } if (PaymentRefAttribute.PaymentRefMustBeUnique(pe.paymenttype.Current) && string.IsNullOrEmpty(payment.ExtRefNbr)) { throw new PXException(ErrorMessages.FieldIsEmpty, typeof(APPayment.extRefNbr).Name); } payment.IsReleaseCheckProcess = true; APPrintChecks.AssignNumbersWithNoAdditionalProcessing(pe, payment); pe.Save.Press(); object[] persisted = PXTimeStampScope.GetPersisted(pe.Document.Cache, pe.Document.Current); if (persisted == null || persisted.Length == 0) { //preserve timestamp which will be @@dbts after last record committed to db on previous Persist(). //otherwise another process updated APAdjust. docs.Add(payment); } else { if (payment.Passed == true) { pe.Document.Current.Passed = true; } docs.Add(pe.Document.Current); } successed = true; } catch (PXException e) { PXProcessing <APPayment> .SetError(e); docs.Add(null); failed = true; } } if (Action == ReleaseChecksFilter.action.ReprintChecks || Action == ReleaseChecksFilter.action.VoidAndReprintChecks) { try { payment.IsPrintingProcess = true; using (PXTransactionScope transactionScope = new PXTransactionScope()) { #region Update CABatch if ReprintChecks CABatch caBatch = PXSelectJoin <CABatch, InnerJoin <CABatchDetail, On <CABatch.batchNbr, Equal <CABatchDetail.batchNbr> > >, Where <CABatchDetail.origModule, Equal <Required <APPayment.origModule> >, And <CABatchDetail.origDocType, Equal <Required <APPayment.docType> >, And <CABatchDetail.origRefNbr, Equal <Required <APPayment.refNbr> > > > > > . Select(be, payment.OrigModule, payment.DocType, payment.RefNbr); if (caBatch != null) { be.Document.Current = caBatch; int DetailCount = be.Details.Select().Count; // load CABatchDetail detail = be.Details.Locate(new CABatchDetail() { BatchNbr = be.Document.Current.BatchNbr, OrigModule = payment.OrigModule, OrigDocType = payment.DocType, OrigRefNbr = payment.RefNbr, OrigLineNbr = CABatchDetail.origLineNbr.DefaultValue, }); if (detail != null) { // payment.Status is recalculated in CABatchEntry.Delete if (DetailCount == 1) { be.Document.Delete(be.Document.Current); // Details will delete by PXParent } else { be.Details.Delete(detail); // recalculated batch totals } } be.Save.Press(); } else { PXCache cacheAPPayment = releaseChecksGraph.APPaymentList.Cache; cacheAPPayment.SetValueExt <APPayment.printed>(payment, false); cacheAPPayment.SetValueExt <APPayment.hold>(payment, false); cacheAPPayment.SetValueExt <APPayment.extRefNbr>(payment, null); // APPayment.Status is recalculated by SetStatusCheckAttribute cacheAPPayment.MarkUpdated(payment); cacheAPPayment.PersistUpdated(payment); cacheAPPayment.Persisted(false); } #endregion // TODO: Need to rework. Use legal CRUD methods of caches! releaseChecksGraph.TimeStamp = PXDatabase.SelectTimeStamp(); // delete check numbers only if Reprint (not Void and Reprint) PaymentMethod pm = pe.paymenttype.Select(payment.PaymentMethodID); if (pm.APPrintChecks == true && Action == ReleaseChecksFilter.action.ReprintChecks) { APPayment doc = payment; new HashSet <string>(pe.Adjustments_Raw.Select(doc.DocType, doc.RefNbr) .RowCast <APAdjust>() .Select(adj => adj.StubNbr)) .ForEach(nbr => PaymentRefAttribute.DeleteCheck((int)doc.CashAccountID, doc.PaymentMethodID, nbr)); // sync PaymentMethodAccount.APLastRefNbr with actual last CashAccountCheck number PaymentMethodAccount det = releaseChecksGraph.cashaccountdetail.SelectSingle(payment.CashAccountID, payment.PaymentMethodID); PaymentRefAttribute.LastCashAccountCheckSelect.Clear(releaseChecksGraph); CashAccountCheck cacheck = PaymentRefAttribute.LastCashAccountCheckSelect.SelectSingleBound(releaseChecksGraph, new object[] { det }); det.APLastRefNbr = cacheck?.CheckNbr; releaseChecksGraph.cashaccountdetail.Cache.PersistUpdated(det); releaseChecksGraph.cashaccountdetail.Cache.Persisted(false); } // END TODO if (string.IsNullOrEmpty(payment.ExtRefNbr)) { //try to get next number releaseChecksGraph.APPaymentList.Cache.SetDefaultExt <APPayment.extRefNbr>(payment); } transactionScope.Complete(); } } catch (PXException e) { PXProcessing <APPayment> .SetError(e); } docs.Add(null); } } if (successed) { APDocumentRelease.ReleaseDoc(docs, true); } if (failed) { throw new PXOperationCompletedWithErrorException(GL.Messages.DocumentsNotReleased); } }
public void Revalue(RevalueFilter filter, List <RevaluedGLHistory> list) { JournalEntry je = PXGraph.CreateInstance <JournalEntry>(); PostGraph pg = PXGraph.CreateInstance <PostGraph>(); PXCache basecache = je.Caches[typeof(AcctHist)]; je.Views.Caches.Add(typeof(AcctHist)); 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); bool hasErrors = false; using (PXTransactionScope ts = new PXTransactionScope()) { foreach (RevaluedGLHistory hist in list) { PXProcessing <RevaluedGLHistory> .SetCurrentItem(hist); if (hist.FinPtdRevalued == 0m) { PXProcessing <RevaluedGLHistory> .SetProcessed(); continue; } string FinPeriod = FinPeriodRepository.GetFinPeriodByMasterPeriodID(PXAccess.GetParentOrganizationID(hist.BranchID), filter.FinPeriodID) .Result .FinPeriodID; ProcessingResult result = CheckFinPeriod(FinPeriod, hist.BranchID); if (!result.IsSuccess) { hasErrors = true; 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 = false; cmbatch.Released = true; cmbatch.Hold = false; cmbatch.DateEntered = filter.CuryEffDate; FinPeriodIDAttribute.SetPeriodsByMaster <Batch.finPeriodID>(je.BatchModule.Cache, cmbatch, 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 = hist.AccountID; tran.SubID = hist.SubID; tran.CuryDebitAmt = 0m; tran.CuryCreditAmt = 0m; if (hist.AccountType == AccountType.Asset || hist.AccountType == AccountType.Expense) { tran.DebitAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued; tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m; } else { tran.DebitAmt = (hist.FinPtdRevalued < 0m) ? -1m * hist.FinPtdRevalued : 0m; tran.CreditAmt = (hist.FinPtdRevalued < 0m) ? 0m : hist.FinPtdRevalued; } tran.TranType = "REV"; tran.TranClass = hist.AccountType; tran.RefNbr = string.Empty; tran.TranDesc = filter.Description; FinPeriodIDAttribute.SetPeriodsByMaster <GLTran.finPeriodID>(je.GLTranModuleBatNbr.Cache, tran, filter.FinPeriodID); tran.TranDate = filter.CuryEffDate; tran.CuryInfoID = null; tran.Released = true; tran.ReferenceID = null; tran.ProjectID = PM.ProjectDefaultAttribute.NonProject(); je.GLTranModuleBatNbr.Insert(tran); } foreach (GLTran tran in je.GLTranModuleBatNbr.SearchAll <Asc <GLTran.tranClass> >(new object[] { "G" })) { je.GLTranModuleBatNbr.Delete(tran); } { 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 = currency.RevalGainAcctID; tran.SubID = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalGainSubID>(je, hist.BranchID, currency); tran.DebitAmt = 0m; tran.CreditAmt = (je.BatchModule.Current.DebitTotal - je.BatchModule.Current.CreditTotal); } else { tran.AccountID = currency.RevalLossAcctID; tran.SubID = GainLossSubAccountMaskAttribute.GetSubID <Currency.revalLossSubID>(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); } { AcctHist accthist = new AcctHist(); accthist.BranchID = hist.BranchID; accthist.LedgerID = hist.LedgerID; accthist.AccountID = hist.AccountID; accthist.SubID = hist.SubID; accthist.FinPeriodID = filter.FinPeriodID; accthist.CuryID = hist.CuryID; accthist.BalanceType = "A"; accthist = (AcctHist)basecache.Insert(accthist); accthist.FinPtdRevalued += hist.FinPtdRevalued; } PXProcessing <RevaluedGLHistory> .SetProcessed(); } 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 (hasErrors) { //Clean current to prevent set exception to the last item PXProcessing <RevaluedGLHistory> .SetCurrentItem(null); throw new PXException(ErrorMessages.SeveralItemsFailed); } if (created.Count > 0) { je.BatchModule.Current = created[created.Count - 1]; throw new PXRedirectRequiredException(je, "Preview"); } decimal val = 0m; foreach (RevaluedGLHistory res in GLAccountList.Cache.Updated) { if ((bool)res.Selected) { decimal sign = AccountRules.IsDEALAccount(res.AccountType) ? 1.0m : -1.0m; val += sign * (decimal)res.FinPtdRevalued; } } if (val == 0) { throw new PXOperationCompletedWithWarningException(Messages.NoRevaluationEntryWasMade); } }
public static void CreateShipment(System.Collections.Generic.List <SOShipmentPlan> list) { int num1 = 0; try { SOShipmentEntry instance = PXGraph.CreateInstance <SOShipmentEntry>(); DocumentList <PX.Objects.SO.SOShipment> list1 = new DocumentList <PX.Objects.SO.SOShipment>((PXGraph)instance); Dictionary <long, PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> > dictionary = new Dictionary <long, PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> >(); SOShipmentPlan soShipmentPlan1 = new SOShipmentPlan(); PX.Objects.SO.SOOrder soOrder = new PX.Objects.SO.SOOrder(); for (int index = 0; index < list.Count; ++index) { SOShipmentPlan i0 = list[index]; PX.Objects.SO.SOOrder i1 = SelectFrom <PX.Objects.SO.SOOrder> .Where <PX.Objects.SO.SOOrder.orderType.IsEqual <P.AsString> .And <PX.Objects.SO.SOOrder.orderNbr.IsEqual <P.AsString> > > .View.Select((PXGraph)instance, (object)i0.OrderType, (object)i0.OrderNbr); int?nullable1; int?customerLocationId; int?nullable2; int num2; if (num1 != 0) { int num3 = num1; nullable1 = i1.CustomerID; customerLocationId = i1.CustomerLocationID; nullable2 = nullable1.HasValue & customerLocationId.HasValue ? new int?(nullable1.GetValueOrDefault() + customerLocationId.GetValueOrDefault()) : new int?(); int valueOrDefault = nullable2.GetValueOrDefault(); num2 = num3 == valueOrDefault & nullable2.HasValue ? 1 : 0; } else { num2 = 1; } if (num2 == 0) { throw new PXException("Please Only Select The Same Customer ID & Location For One Shipment"); } nullable2 = i1.CustomerID; customerLocationId = i1.CustomerLocationID; int?nullable3; if (!(nullable2.HasValue & customerLocationId.HasValue)) { nullable1 = new int?(); nullable3 = nullable1; } else { nullable3 = new int?(nullable2.GetValueOrDefault() + customerLocationId.GetValueOrDefault()); } nullable1 = nullable3; num1 = nullable1.Value; dictionary.Add(i0.PlanID.Value, new PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder>(i0, i1)); } PX.Objects.SO.SOOrder order = new PX.Objects.SO.SOOrder(); foreach (PXResult <SOShipmentPlan, PX.Objects.SO.SOOrder> pxResult in dictionary.Values) { SOShipmentPlan soShipmentPlan2 = (SOShipmentPlan)pxResult; if (order.OrderNbr != pxResult.GetItem <PX.Objects.SO.SOOrder>().OrderNbr) { order = (PX.Objects.SO.SOOrder)pxResult; instance.GetExtension <SOShipmentEntry_Extension>().CreateShipment2(order, soShipmentPlan2.SiteID, soShipmentPlan2.PlanDate, new bool?(false), "I", list1, list); } } throw new PXPopupRedirectException((PXGraph)instance, "Shipment <*> is created", true); } catch (Exception ex) { if (ex.Message.Equals("Shipment <*> is created")) { PXProcessing.SetProcessed(); } else { PXProcessing.SetError(ex); } throw; } }
/// <summary> /// Creates or updates the Smartsheet project with information from Acumatica. /// New Tasks created in Smartsheet will be updated back in Acumatica /// </summary> /// <param name="projectEntryGraph">Project Entry graph</param> /// <param name="pmProjectRow">PMProject record</param> /// <param name="smartsheetClient">Smartsheet's SDK Client</param> /// <param name="isMassProcess">Indicates if it's used in a processing page</param> public void CreateUpdateGanttProject(ProjectEntry projectEntryGraph, PMProject pmProjectRow, SmartsheetClient smartsheetClient, bool isMassProcess = false) { //Primary Data View is set projectEntryGraph.Project.Current = pmProjectRow; PMProjectSSExt pmProjectSSExt = PXCache <PMProject> .GetExtension <PMProjectSSExt>(pmProjectRow); PMSetup setupRecord = projectEntryGraph.Setup.Select(); PMSetupSSExt pmSetupSSExt = PXCache <PMSetup> .GetExtension <PMSetupSSExt>(setupRecord); SmartsheetHelper smartSheetHelperObject = new SmartsheetHelper(); if (String.IsNullOrEmpty(pmProjectSSExt.UsrTemplateSS)) { throw new PXException(SmartsheetConstants.Messages.DEFAULT_TEMPLATE); } string sheetName = pmProjectRow.ContractCD.Trim() + " - " + pmProjectRow.Description.Trim(); sheetName = smartSheetHelperObject.Left(sheetName, SmartsheetConstants.SSConstants.SS_PROJECT_NAME_LENGTH); try { long?sheetSelected; Dictionary <string, long> currentColumnMap = new Dictionary <string, long>(); ////////////////// //Information from Acumatica is updated in Smartsheet ////////////////// PXResultset <PMSSMapping> templateMappingSet = PXSelect < PMSSMapping, Where <PMSSMapping.templateSS, Equal <Required <PMSSMapping.templateSS> > > > .Select(projectEntryGraph, pmProjectSSExt.UsrTemplateSS); if (pmProjectSSExt != null && pmProjectSSExt.UsrSmartsheetContractID != null) //Acumatica Project is already linked to SS { sheetSelected = pmProjectSSExt.UsrSmartsheetContractID; Sheet ssProjectSheet = smartsheetClient.SheetResources.GetSheet((long)sheetSelected, null, null, null, null, null, null, null); //Columns ID Mapping currentColumnMap = new Dictionary <string, long>(); foreach (Column currentColumn in ssProjectSheet.Columns) { currentColumnMap.Add(currentColumn.Title, (long)currentColumn.Id); } smartSheetHelperObject.UpdateSSProject(smartsheetClient, currentColumnMap, projectEntryGraph, sheetSelected, smartSheetHelperObject, templateMappingSet); } else //Acumatica Project has not been linked to Smartsheet { //Sheet is created from a the template selected in the Project Sheet sheet = new Sheet.CreateSheetFromTemplateBuilder(sheetName, Convert.ToInt64(pmProjectSSExt.UsrTemplateSS)).Build(); sheet = smartsheetClient.SheetResources.CreateSheet(sheet); Sheet newlyCreatedSheet = smartsheetClient.SheetResources.GetSheet((long)sheet.Id, null, null, null, null, null, null, null); currentColumnMap = new Dictionary <string, long>(); foreach (Column currentColumn in newlyCreatedSheet.Columns) { currentColumnMap.Add(currentColumn.Title, (long)currentColumn.Id); } //Acumatica Tasks are added as Smartsheet rows List <Row> newSSRows = smartSheetHelperObject.InsertAcumaticaTasksInSS(projectEntryGraph, currentColumnMap, null, true, templateMappingSet); IList <Row> ssRows = smartsheetClient.SheetResources.RowResources.AddRows((long)sheet.Id, newSSRows); int ssTaskIDPosition = 0; if (ssRows.Count > 0 && ssRows[0].Cells != null) { PMSSMapping mappingSS = templateMappingSet.Where(t => ((PMSSMapping)t).NameAcu.Trim().ToUpper() == SmartsheetConstants.ColumnMapping.TASKS_CD.Trim().ToUpper()).FirstOrDefault(); ssTaskIDPosition = smartSheetHelperObject.GetSSTaskPosition(ssRows[0].Cells, currentColumnMap[mappingSS.NameSS]); } // Add SubTasks smartSheetHelperObject.InsertAcumaticaSubTasks(projectEntryGraph, smartsheetClient, sheet, ssRows, smartSheetHelperObject, currentColumnMap, ssTaskIDPosition, templateMappingSet); foreach (Row currentRow in ssRows) { foreach (PMTask rowTask in projectEntryGraph.Tasks.Select()) { if (currentRow.Cells[ssTaskIDPosition].Value != null && rowTask.TaskCD != null && string.Equals(currentRow.Cells[ssTaskIDPosition].Value.ToString().Trim(), rowTask.TaskCD.Trim(), StringComparison.OrdinalIgnoreCase)) { PMTaskSSExt pmTaskSSExtRow = PXCache <PMTask> .GetExtension <PMTaskSSExt>(rowTask); pmTaskSSExtRow.UsrSmartsheetTaskID = currentRow.Id; projectEntryGraph.Tasks.Update(rowTask); break; } } } sheetSelected = (long)sheet.Id; PMProjectSSExt pmProjectSSExtRow = PXCache <PMProject> .GetExtension <PMProjectSSExt>(pmProjectRow); pmProjectSSExtRow.UsrSmartsheetContractID = sheetSelected; projectEntryGraph.Project.Update(pmProjectRow); } ////////////////// //Information from Smartsheet is updated in Acumatica ////////////////// Sheet updatedSheet = smartsheetClient.SheetResources.GetSheet((long)sheetSelected, null, null, null, null, null, null, null); int columnPosition = 0; Dictionary <string, int> columnPositionMap = new Dictionary <string, int>(); foreach (Column currentColumn in updatedSheet.Columns) { columnPositionMap.Add(currentColumn.Title, columnPosition); columnPosition += 1; } smartSheetHelperObject.UpdateAcumaticaTasks(projectEntryGraph, pmProjectRow, pmSetupSSExt, updatedSheet, columnPositionMap, templateMappingSet); projectEntryGraph.Actions.PressSave(); if (isMassProcess) { PXProcessing.SetInfo(String.Format(SmartsheetConstants.Messages.SUCCESSFULLY_SYNCED, pmProjectRow.ContractCD)); } } catch (Exception e) { throw new PXException(e.Message); } }
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> > > > > .Select(scheduleMaint, tr.ScheduleID, tr.ComponentID ?? DRScheduleDetail.EmptyComponentID); 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.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); } }
protected void ProcessInternal(ProcessingContext context) { Dictionary <int, List <int> > processing = new Dictionary <int, List <int> >( ); foreach (EMailSyncAccount account in context.Accounts) { List <int> list; if (!processing.TryGetValue(account.ServerID.Value, out list)) { processing[account.ServerID.Value] = list = new List <int>(); } list.Add(account.EmployeeID.Value); } foreach (int serverID in processing.Keys) { Dictionary <string, ProcessingBox> buckets = new Dictionary <string, ProcessingBox>(); EMailSyncServer server = null; foreach (PXResult <EMailSyncAccount, EMailSyncServer, EMailAccount, EPEmployee> row in PXSelectJoin <EMailSyncAccount, InnerJoin <EMailSyncServer, On <EMailSyncServer.accountID, Equal <EMailSyncAccount.serverID> >, InnerJoin <EMailAccount, On <EMailAccount.emailAccountID, Equal <EMailSyncAccount.emailAccountID> >, LeftJoin <EPEmployee, On <EMailSyncAccount.employeeID, Equal <EPEmployee.bAccountID> > > > >, Where <EMailSyncServer.accountID, Equal <Required <EMailSyncServer.accountID> >, And <EMailSyncAccount.address, IsNotNull> >, OrderBy <Asc <EMailSyncAccount.serverID, Asc <EMailSyncAccount.employeeID> > > > .Select(this, serverID)) { server = (EMailSyncServer)row; EMailSyncAccount account = (EMailSyncAccount)row; EMailAccount eMailAccount = (EMailAccount)row; if (!processing.ContainsKey(serverID) || !processing[serverID].Contains(account.EmployeeID.Value)) { continue; } string address = account.Address; EMailSyncPolicy policy = null; if (!String.IsNullOrEmpty(account.PolicyName)) { policy = context.Policies[account.PolicyName]; } if (policy == null && !String.IsNullOrEmpty(server.DefaultPolicyName)) { policy = context.Policies[server.DefaultPolicyName]; } if (policy == null) { throw new PXException(Messages.EmailExchangePolicyNotFound, account.Address); } ProcessingBox bucket; if (!buckets.TryGetValue(policy.PolicyName, out bucket)) { buckets[policy.PolicyName] = bucket = new ProcessingBox(policy); } if (policy.ContactsSync ?? false) { bucket.Contacts.Add( new PXSyncMailbox(address, account.EmployeeID.Value, account.EmailAccountID, new PXSyncMailboxPreset(account.ContactsExportDate, account.ContactsExportFolder), new PXSyncMailboxPreset(account.ContactsImportDate, account.ContactsImportFolder), eMailAccount.IncomingProcessing ?? false) { Reinitialize = account.ToReinitialize == true, IsReset = account.IsReset == true }); } if (policy.EmailsSync ?? false) { bucket.Emails.Add( new PXSyncMailbox(address, account.EmployeeID.Value, account.EmailAccountID, new PXSyncMailboxPreset(account.EmailsExportDate, account.EmailsExportFolder), new PXSyncMailboxPreset(account.EmailsImportDate, account.EmailsImportFolder), eMailAccount.IncomingProcessing ?? false) { Reinitialize = account.ToReinitialize == true, IsReset = account.IsReset == true }); } if (policy.TasksSync ?? false) { bucket.Tasks.Add( new PXSyncMailbox(address, account.EmployeeID.Value, account.EmailAccountID, new PXSyncMailboxPreset(account.TasksExportDate, account.TasksExportFolder), new PXSyncMailboxPreset(account.TasksImportDate, account.TasksImportFolder), eMailAccount.IncomingProcessing ?? false) { Reinitialize = account.ToReinitialize == true, IsReset = account.IsReset == true }); } if (policy.EventsSync ?? false) { bucket.Events.Add( new PXSyncMailbox(address, account.EmployeeID.Value, account.EmailAccountID, new PXSyncMailboxPreset(account.EventsExportDate, account.EventsExportFolder), new PXSyncMailboxPreset(account.EventsImportDate, account.EventsImportFolder), eMailAccount.IncomingProcessing ?? false) { Reinitialize = account.ToReinitialize == true, IsReset = account.IsReset == true }); } } if (server == null) { continue; } List <Exception> errors = new List <Exception>(); foreach (string policy in buckets.Keys) { ProcessingBox bucket = buckets[policy]; using (IEmailSyncProvider provider = PXEmailSyncHelper.GetExchanger(server, bucket.Policy)) { foreach (PXEmailSyncOperation.Operations operation in Enum.GetValues(typeof(PXEmailSyncOperation.Operations))) //do one time for all existing sync types { try { switch (operation) { case PXEmailSyncOperation.Operations.Emails: if (bucket.EmailsPending) { provider.EmailsSync(bucket.Policy, PXEmailSyncDirection.Parse(bucket.Policy.EmailsDirection), bucket.Emails); } break; case PXEmailSyncOperation.Operations.Contacts: if (bucket.ContactsPending) { provider.ContactsSync(bucket.Policy, PXEmailSyncDirection.Parse(bucket.Policy.ContactsDirection), bucket.Contacts); } break; case PXEmailSyncOperation.Operations.Tasks: if (bucket.TasksPending) { provider.TasksSync(bucket.Policy, PXEmailSyncDirection.Parse(bucket.Policy.TasksDirection), bucket.Tasks); } break; case PXEmailSyncOperation.Operations.Events: if (bucket.EventsPending) { provider.EventsSync(bucket.Policy, PXEmailSyncDirection.Parse(bucket.Policy.EventsDirection), bucket.Events); } break; } } catch (PXExchangeSyncItemsException ex) { if (bucket.Policy.SkipError == true) { continue; } if (ex.Errors.Count > 0) { foreach (string address in ex.Errors.Keys) { string message = String.Join(Environment.NewLine, ex.Errors[address].ToArray()); context.StoreError(serverID, address, message); } } } catch (PXExchangeSyncFatalException ex) { if (bucket.Policy.SkipError == true) { continue; } errors.Add(new PXException(Messages.EmailExchangeSyncOperationError, operation.ToString())); if (!String.IsNullOrEmpty(ex.Mailbox)) { context.StoreError(serverID, ex.Mailbox, ex.InnerMessage); } else { errors.Add(ex); } } catch (Exception ex) { if (bucket.Policy.SkipError == true) { continue; } errors.Add(new PXException(Messages.EmailExchangeSyncOperationError, operation.ToString())); errors.Add(ex); } } } } if (errors.Count > 0) { throw new PXException(String.Join(Environment.NewLine, errors.Select(e => e.Message).ToArray())); } } for (int index = 0; index < context.Accounts.Count; index++) { PXProcessing.SetInfo(index, ActionsMessages.RecordProcessed); } //handle exceptions if (context.Exceptions.Count > 0) { foreach (int index in context.Exceptions.Keys) { List <string> errors = context.Exceptions[index]; if (errors == null || errors.Count < 0) { continue; } PXProcessing.SetError(index, String.Join(Environment.NewLine, errors.ToArray( ))); } throw new PXException(Messages.EmailExchangeSyncFailed); } }
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 Upload(List <TWNGUITrans> tWNGUITrans) { try { // Avoid to create empty content file in automation schedule. if (tWNGUITrans.Count == 0) { return; } TWNExpGUIInv2BankPro graph = CreateInstance <TWNExpGUIInv2BankPro>(); string lines = "", fileName = ""; TWNGUIPreferences preferences = PXSelect <TWNGUIPreferences> .Select(graph); fileName = preferences.OurTaxNbr + "-InvoiceMD--Paper-" + DateTime.Today.ToString("yyyyMMdd") + "-" + DateTime.Now.ToString("hhmmss") + ".txt"; foreach (TWNGUITrans gUITrans in tWNGUITrans) { // File Type lines += "M" + verticalBar; // Bill type lines += GetBillType(gUITrans) + verticalBar; // Invoice No lines += gUITrans.GUINbr + verticalBar; // Invoice Date Time lines += gUITrans.GUIDate.Value.ToString("yyyy/MM/dd HH:mm:ss") + verticalBar; // Allowance Date // Cancel Date lines += verticalBar + GetCancelDate(gUITrans) + verticalBar; // Bill Attribute // Seller Ban lines += verticalBar + gUITrans.OurTaxNbr + verticalBar; // Seller Code lines += verticalBar; // Buyer Ban lines += gUITrans.TaxNbr + verticalBar; // Buyer Code lines += verticalBar; // Buyer CName lines += gUITrans.GUITitle + verticalBar; // Sales Amount lines += GetSalesAmt(gUITrans) + verticalBar; // Tax Type lines += GetTaxType(gUITrans.VATType) + verticalBar; // Tax Rate lines += GetTaxRate(gUITrans.VATType) + verticalBar; // Tax Amount lines += GetTaxAmt(gUITrans) + verticalBar; // Total Amount lines += (gUITrans.NetAmount + gUITrans.TaxAmount).Value + verticalBar; // Health Tax lines += "0" + verticalBar; // Buyer Remark lines += verticalBar; // Main Remark lines += verticalBar; // Order No = Relate Number1 lines += gUITrans.OrderNbr + verticalBar; // Relate Number2 // Relate Number3 // Relate Number4 // Relate Number5 // Group Mark // Customs Clearance Mark lines += new string(char.Parse(verticalBar), 5) + GetCustomClearance(gUITrans) + verticalBar; // Bonded Area Enum lines += verticalBar; // Random Number lines += (gUITrans.BatchNbr != null) ? gUITrans.BatchNbr.Substring(gUITrans.BatchNbr.Length - 4, 4) : null; lines += verticalBar; // Carrier Type lines += ARReleaseProcess_Extension.GetCarrierType(gUITrans.CarrierID) + verticalBar; // Carrier ID lines += ARReleaseProcess_Extension.GetCarrierID(gUITrans.TaxNbr, gUITrans.CarrierID) + verticalBar; // NPOBAN lines += ARReleaseProcess_Extension.GetNPOBAN(gUITrans.TaxNbr, gUITrans.NPONbr) + verticalBar; // Request Paper lines += gUITrans.B2CPrinted.Equals(true) ? "Y" : "N" + verticalBar; // Void Reason // Project Number Void Approved lines += new string(char.Parse(verticalBar), 2) + "\r\n"; // The following method is only for voided invoice. if (gUITrans.GUIStatus == TWNGUIStatus.Voided) { CreateVoidedDetailLine(verticalBar, gUITrans.OrderNbr, ref lines); } else { foreach (PXResult <ARTran> result in graph.RetrieveARTran(gUITrans.OrderNbr)) { ARTran aRTran = result; string taxCalcMode = SelectFrom <ARRegister> .Where <ARRegister.docType.IsEqual <@P.AsString> .And <ARRegister.refNbr.IsEqual <@P.AsString> > > .View.ReadOnly.Select(graph, aRTran.TranType, aRTran.RefNbr).TopFirst.TaxCalcMode; // File Type lines += "D" + verticalBar; // Description lines += aRTran.TranDesc + verticalBar; // Quantity lines += (aRTran.Qty ?? 1) + verticalBar; // Unit Price // Amount #region Convert design spec logic to code. //if (aRTran.CuryDiscAmt == 0m) //{ // if (taxCalcMode != PX.Objects.TX.TaxCalculationMode.Gross) // { // if (!string.IsNullOrEmpty(gUITrans.TaxNbr)) // { // lines += aRTran.UnitPrice + verticalBar; // } // else // { // lines += aRTran.UnitPrice * fixedRate + verticalBar; // } // } // else // { // if (!string.IsNullOrEmpty(gUITrans.TaxNbr)) // { // lines += aRTran.UnitPrice / fixedRate + verticalBar; // } // else // { // lines += aRTran.UnitPrice + verticalBar; // } // } //} //else //{ // if (taxCalcMode != PX.Objects.TX.TaxCalculationMode.Gross) // { // if (!string.IsNullOrEmpty(gUITrans.TaxNbr)) // { // lines += aRTran.TranAmt / aRTran.Qty + verticalBar; // } // else // { // lines += aRTran.TranAmt / aRTran.Qty * fixedRate + verticalBar; // } // } // else // { // if (!string.IsNullOrEmpty(gUITrans.TaxNbr)) // { // lines += aRTran.TranAmt / aRTran.Qty / fixedRate + verticalBar; // } // else // { // lines += aRTran.TranAmt / aRTran.Qty + verticalBar; // } // } //} #endregion decimal?unitPrice = (aRTran.CuryDiscAmt == 0m) ? aRTran.UnitPrice : (aRTran.TranAmt / aRTran.Qty); decimal?tranAmt = aRTran.TranAmt; if (string.IsNullOrEmpty(gUITrans.TaxNbr) && taxCalcMode != PX.Objects.TX.TaxCalculationMode.Gross) { unitPrice *= fixedRate; tranAmt *= fixedRate; } else if (!string.IsNullOrEmpty(gUITrans.TaxNbr) && taxCalcMode == PX.Objects.TX.TaxCalculationMode.Gross) { unitPrice /= fixedRate; tranAmt /= fixedRate; } lines += string.Format("{0:0.####}", unitPrice) + verticalBar; lines += string.Format("{0:0.####}", tranAmt) + verticalBar; // Unit lines += verticalBar; // Package lines += "0" + verticalBar; // Gift Number 1 (Box) lines += "0" + verticalBar; // Gift Number 2 (Piece) lines += "0" + verticalBar; // Order No lines += gUITrans.OrderNbr; // Buyer Barcode // Buyer Prod No // Seller Prod No // Seller Account No // Seller Shipping No // Remark // Relate Number1 // Relate Number2 (Invoice No) // Relate Number3 (Invoice Date) // Relate Number4 // Relate Number5 lines += new string(char.Parse(verticalBar), 11) + "\r\n"; } } } // Total Records lines += tWNGUITrans.Count; graph.UpdateGUITran(tWNGUITrans); graph.UploadFile2FTP(fileName, lines); } catch (Exception ex) { PXProcessing <TWNGUITrans> .SetError(ex); throw; } }
protected static void Approve(List <EPOwned> items, bool approve) { EntityHelper helper = new EntityHelper(new PXGraph()); var graphs = new Dictionary <Type, PXGraph>(); bool errorOccured = false; foreach (EPOwned item in items) { try { PXProcessing <EPApproval> .SetCurrentItem(item); if (item.RefNoteID == null) { throw new PXException(Messages.ApprovalRefNoteIDNull); } object row = helper.GetEntityRow(item.RefNoteID.Value, true); if (row == null) { throw new PXException(Messages.ApprovalRecordNotFound); } Type cahceType = row.GetType(); Type graphType = helper.GetPrimaryGraphType(row, false); PXGraph graph; if (!graphs.TryGetValue(graphType, out graph)) { graphs.Add(graphType, graph = PXGraph.CreateInstance(graphType)); } EPApproval approval = PXSelectReadonly <EPApproval, Where <EPApproval.approvalID, Equal <Current <EPOwned.approvalID> > > > .SelectSingleBound(graph, new object[] { item }); if (approval.Status == EPApprovalStatus.Pending) { graph.Clear(); graph.Caches[cahceType].Current = row; graph.Caches[cahceType].SetStatus(row, PXEntryStatus.Notchanged); PXAutomation.GetView(graph); string approved = typeof(EPExpenseClaim.approved).Name; if (graph.AutomationView != null) { PXAutomation.GetStep(graph, new object[] { graph.Views[graph.AutomationView].Cache.Current }, BqlCommand.CreateInstance( typeof(Select <>), graph.Views[graph.AutomationView].Cache.GetItemType()) ); } string actionName = approve ? nameof(Approve) : nameof(Reject); if (graph.Actions.Contains(actionName)) { graph.Actions[actionName].Press(); } else if (graph.AutomationView != null) { PXView view = graph.Views[graph.AutomationView]; BqlCommand select = view.BqlSelect; PXAdapter adapter = new PXAdapter(new PXView.Dummy(graph, select, new List <object> { row })); adapter.Menu = actionName; if (graph.Actions.Contains("Action")) { if (!CheckRights(graphType, cahceType)) { throw new PXException(Messages.DontHaveAppoveRights); } foreach (var i in graph.Actions["Action"].Press(adapter)) { ; } } else { throw new PXException(PXMessages.LocalizeFormatNoPrefixNLA(Messages.AutomationNotConfigured, graph)); } //PXAutomation.ApplyAction(graph, graph.Actions["Action"], "Approve", row, out rollback); } else if (graph.Caches[cahceType].Fields.Contains(approved)) { object upd = graph.Caches[cahceType].CreateCopy(row); graph.Caches[cahceType].SetValue(upd, approved, true); graph.Caches[cahceType].Update(upd); } graph.Persist(); } PXProcessing <EPApproval> .SetInfo(ActionsMessages.RecordProcessed); } catch (Exception ex) { errorOccured = true; PXProcessing <EPApproval> .SetError(ex); } } if (errorOccured) { throw new PXOperationCompletedWithErrorException(ErrorMessages.SeveralItemsFailed); } }
private static void GenerateRequisition(RQRequestSelection filter, List <RQRequestLineOwned> lines) { RQRequisitionEntry graph = PXGraph.CreateInstance <RQRequisitionEntry>(); RQRequisition requisition = (RQRequisition)graph.Document.Cache.CreateInstance(); graph.Document.Insert(requisition); requisition.ShipDestType = null; bool isCustomerSet = true; bool isVendorSet = true; bool isShipToSet = true; int? shipContactID = null; int? shipAddressID = null; var vendors = new HashSet <VendorRef>(); foreach (RQRequestLine line in lines) { PXResult <RQRequest, RQRequestClass> e = (PXResult <RQRequest, RQRequestClass>) PXSelectJoin <RQRequest, InnerJoin <RQRequestClass, On <RQRequestClass.reqClassID, Equal <RQRequest.reqClassID> > >, Where <RQRequest.orderNbr, Equal <Required <RQRequest.orderNbr> > > > .Select(graph, line.OrderNbr); RQRequest req = e; RQRequestClass reqclass = e; requisition = PXCache <RQRequisition> .CreateCopy(graph.Document.Current); if (reqclass.CustomerRequest == true && isCustomerSet) { if (requisition.CustomerID == null) { requisition.CustomerID = req.EmployeeID; requisition.CustomerLocationID = req.LocationID; } else if (requisition.CustomerID != req.EmployeeID || requisition.CustomerLocationID != req.LocationID) { isCustomerSet = false; } } else { isCustomerSet = false; } if (isShipToSet) { if (shipContactID == null && shipAddressID == null) { requisition.ShipDestType = req.ShipDestType; requisition.ShipToBAccountID = req.ShipToBAccountID; requisition.ShipToLocationID = req.ShipToLocationID; shipContactID = req.ShipContactID; shipAddressID = req.ShipAddressID; } else if (requisition.ShipDestType != req.ShipDestType || requisition.ShipToBAccountID != req.ShipToBAccountID || requisition.ShipToLocationID != req.ShipToLocationID) { isShipToSet = false; } } if (line.VendorID != null && line.VendorLocationID != null) { VendorRef vendor = new VendorRef() { VendorID = line.VendorID.Value, LocationID = line.VendorLocationID.Value }; vendors.Add(vendor); if (isVendorSet) { if (requisition.VendorID == null) { requisition.VendorID = line.VendorID; requisition.VendorLocationID = line.VendorLocationID; } else if (requisition.VendorID != line.VendorID || requisition.VendorLocationID != line.VendorLocationID) { isVendorSet = false; } } } else { isVendorSet = false; } if (!isCustomerSet) { requisition.CustomerID = null; requisition.CustomerLocationID = null; } if (!isVendorSet) { requisition.VendorID = null; requisition.VendorLocationID = null; requisition.RemitAddressID = null; requisition.RemitContactID = null; } else if (requisition.VendorID == req.VendorID && requisition.VendorLocationID == req.VendorLocationID) { requisition.RemitAddressID = req.RemitAddressID; requisition.RemitContactID = req.RemitContactID; } if (!isShipToSet) { requisition.ShipDestType = PX.Objects.PO.POShippingDestination.CompanyLocation; graph.Document.Cache.SetDefaultExt <RQRequisition.shipToBAccountID>(requisition); } graph.Document.Update(requisition); if (line.OpenQty > 0) { if (!graph.Lines.Cache.IsDirty && req.CuryID != requisition.CuryID) { requisition = PXCache <RQRequisition> .CreateCopy(graph.Document.Current); requisition.CuryID = req.CuryID; graph.Document.Update(requisition); } graph.InsertRequestLine(line, line.OpenQty.GetValueOrDefault(), filter.AddExists == true); } } if (isShipToSet) { foreach (PXResult <POAddress, POContact> res in PXSelectJoin <POAddress, CrossJoin <POContact>, Where <POAddress.addressID, Equal <Required <RQRequisition.shipAddressID> >, And <POContact.contactID, Equal <Required <RQRequisition.shipContactID> > > > > .Select(graph, shipAddressID, shipContactID)) { AddressAttribute.CopyRecord <RQRequisition.shipAddressID>(graph.Document.Cache, graph.Document.Current, (POAddress)res, true); AddressAttribute.CopyRecord <RQRequisition.shipContactID>(graph.Document.Cache, graph.Document.Current, (POContact)res, true); } } if (requisition.VendorID == null && vendors.Count > 0) { foreach (var vendor in vendors) { RQBiddingVendor bid = PXCache <RQBiddingVendor> .CreateCopy(graph.Vendors.Insert()); bid.VendorID = vendor.VendorID; bid.VendorLocationID = vendor.LocationID; graph.Vendors.Update(bid); } } if (graph.Lines.Cache.IsDirty) { graph.Save.Press(); throw new PXRedirectRequiredException(graph, string.Format(Messages.RequisitionCreated, graph.Document.Current.ReqNbr)); } for (int i = 0; i < lines.Count; i++) { PXProcessing <RQRequestLine> .SetInfo(i, PXMessages.LocalizeFormatNoPrefixNLA(Messages.RequisitionCreated, graph.Document.Current.ReqNbr)); } }
public static void SetProcessDelegate <ProcessGraph>(PXGraph graph, Parameters filter, PXProcessing <Schedule> view) where ProcessGraph : PXGraph <ProcessGraph>, IScheduleProcessing, new() { if (filter == null) { return; } short Times = Parameters.limitTypeSel.RunMultipleTimes == filter.LimitTypeSel ? (filter.RunLimit ?? 1) : short.MaxValue; DateTime Date = Parameters.limitTypeSel.RunTillDate == filter.LimitTypeSel ? (filter.EndDate ?? ((AccessInfo)graph.Caches[typeof(AccessInfo)].Current).BusinessDate.Value) : DateTime.MaxValue; view.SetProcessDelegate( delegate(ProcessGraph sp, Schedule schedule) { sp.Clear(); sp.GenerateProc(schedule, Times, Date); } ); }
public static void SetProcessDelegate <ProcessGraph>(PXGraph graph, ScheduleRun.Parameters filter, PXProcessing <Schedule> view) where ProcessGraph : PXGraph <ProcessGraph>, IScheduleProcessing, new() => ScheduleRunBase.SetProcessDelegate <ProcessGraph>(graph, filter, view);
public static void SetProcessDelegate <ProcessGraph>(PXGraph graph, ScheduleRun.Parameters filter, PXProcessing <Schedule> view) where ProcessGraph : PXGraph <ProcessGraph>, IScheduleProcessing, new() { if (filter == null) { return; } short times = filter.LimitTypeSel == ScheduleRunLimitType.StopAfterNumberOfExecutions ? filter.RunLimit ?? 1 : short.MaxValue; DateTime executionDate = filter.LimitTypeSel == ScheduleRunLimitType.StopOnExecutionDate ? filter.ExecutionDate ?? graph.Accessinfo.BusinessDate.Value : DateTime.MaxValue; Dictionary <string, string> parametersErrors = PXUIFieldAttribute.GetErrors( graph.Caches[typeof(ScheduleRun.Parameters)], filter); view.SetProcessDelegate(schedules => { if (parametersErrors.Any()) { throw new PXException(parametersErrors.First().Value); } ProcessGraph processGraph = PXGraph.CreateInstance <ProcessGraph>(); bool failed = false; foreach (Schedule schedule in schedules) { try { PXProcessing <Schedule> .SetCurrentItem(schedule); processGraph.Clear(); processGraph.GenerateProc(schedule, times, executionDate); PXProcessing <Schedule> .SetInfo(ActionsMessages.RecordProcessed); } catch (Exception e) { failed = true; PXProcessing <Schedule> .SetError(e); } } if (failed) { //Clean current to prevent set exception to the last item PXProcessing <Schedule> .SetCurrentItem(null); throw new PXException(AR.Messages.OneOrMoreItemsAreNotProcessed); } }); }