private static Message GetListOfMessagesContent(SubmitFeedParamaters objSubmitFeedParams)
        {
            Message objMessage = new Message();

            objMessage.MessageID = objSubmitFeedParams.shipmentNbr;
            OrderFulfillment objOrderFulfillment = new OrderFulfillment();
            FulfillmentData  objFulfillmentData  = new FulfillmentData();

            objOrderFulfillment.AmazonOrderID = objSubmitFeedParams.amazonOrderID;

            objOrderFulfillment.FulfillmentDate = new DateTimeOffset(Convert.ToDateTime(objSubmitFeedParams.shipmentDate),
                                                                     PXTimeZoneInfo.FindSystemTimeZoneById("GMTM0800A").UtcOffset).ToString("yyyy-MM-ddTHH:mm:sszzz");

            PXTrace.WriteInformation(String.Format("Shipment# {0} FulfillmentDate {1}",
                                                   objMessage.MessageID, objOrderFulfillment.FulfillmentDate));
            objFulfillmentData.CarrierName           = objSubmitFeedParams.carrierCode;
            objFulfillmentData.ShippingMethod        = objSubmitFeedParams.shipVia;
            objFulfillmentData.ShipperTrackingNumber = objSubmitFeedParams.trackingNbr;
            objOrderFulfillment.FulfillmentData      = objFulfillmentData;
            if (objSubmitFeedParams.liShipItem != null && objSubmitFeedParams.liShipItem.Count > 0)
            {
                objOrderFulfillment.Item = objSubmitFeedParams.liShipItem;
            }
            objMessage.OrderFulfillment = objOrderFulfillment;
            return(objMessage);
        }
        public virtual void VerifyApiAccessPermission()
        {
            KCSiteMaster row = SiteMaster.Current;

            if (row == null)
            {
                return;
            }

            if (row.ApplicationId != "" && row.SharedSecret != "")
            {
                PXLongOperation.StartOperation(this, delegate()
                {
                    KCInternalReponse response = new KCSiteMasterHelper().VerifyApiAccess(row);
                    if (response != null)
                    {
                        if (!response.IsSuccess && !string.IsNullOrEmpty(response.Message))
                        {
                            throw new PXException(response.Message);
                        }
                        else if (!string.IsNullOrEmpty(response.Message))
                        {
                            PXTrace.WriteInformation(response.Message);
                        }
                    }
                    else
                    {
                        string exceptionmsg = string.Format(KCConstants.DualParameters, KCConstants.VerifyApiAccess, KCMessages.NullException);
                        throw new PXException(exceptionmsg);
                    }
                });
            }
        }
        protected void PersistMessages(IEnumerable <CRSMEmail> messages)
        {
            using (PXTransactionScope ts = new PXTransactionScope())
            {
                foreach (CRSMEmail item in messages)
                {
                    try
                    {
                        var activityCache = Graph.Caches[item.GetType()];
                        PXDBDefaultAttribute.SetSourceType <CRSMEmail.refNoteID>(activityCache, item, null);
                        activityCache.PersistInserted(item);
                    }
                    catch (Exception e)
                    {
                        if (!MassProcessMode)
                        {
                            throw;
                        }
                        PXTrace.WriteInformation(e);
                    }
                }
                Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Insert);
                Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Update);

                ts.Complete();
            }
        }
        public void ShipPackages(SOShipment shiporder, Action <SOShipment> baseMethod)
        {
            if (shiporder.Operation == SOOperation.Issue)
            {
                if (String.IsNullOrEmpty(shiporder.ShipVia) || shiporder.ShipVia == "FREESHIP" || shiporder.ShipVia == "GROUND" || shiporder.ShipVia == "OVERNIGHT" || shiporder.ShipVia == "2DAY")
                {
                    Base.Clear();
                    Base.Document.Current = Base.Document.Search <SOShipment.shipmentNbr>(shiporder.ShipmentNbr);
                    shiporder             = Base.Document.Current;

                    SOPackageDetail p = Base.Packages.SelectSingle();
                    if (p == null)
                    {
                        throw new PXException(PX.Objects.SO.Messages.PackageIsRequired);
                    }

                    SelectLeastExpensiveShipVia();
                }
                else
                {
                    PXTrace.WriteInformation("Skipping rate shopping because a Ship Via is already selected.");
                }
            }

            var sw = new Stopwatch();

            sw.Start();
            baseMethod(shiporder);
            sw.Stop();
            PXTrace.WriteInformation($"ShipPackages took {sw.ElapsedMilliseconds}ms.");
        }
예제 #5
0
 public void Debug(string message)
 {
     if (_debugEnabled)
     {
         PXTrace.WriteInformation($"{TaxProviderName} - {message}");
     }
 }
예제 #6
0
        public async Task <string> PostPrediction(string querystring)
        {
            string add = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/717af479-1d8c-40f9-afb3-fd800eda8bca";

            Uri address = new Uri(add);

            using (var client = new HttpClient(new HttpClientHandler()))
            {
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "2b9324da598d4b52b6b78eccb45a7a05");
                try
                {
                    var result = await client.PostAsJsonAsync(address, querystring);

                    if (result.IsSuccessStatusCode)
                    {
                        return(await result.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        PXTrace.WriteInformation(address.ToString());
                        PXTrace.WriteInformation(result.ToString());
                        return(result.ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw new PX.Data.PXException(ex.Message);
                }
            }
        }
예제 #7
0
        public async Task <string> GetPrediction(string querystring)
        {
            string add          = "https://westus.api.cognitive.microsoft.com/luis/v2.0/apps/717af479-1d8c-40f9-afb3-fd800eda8bca?verbose=true&timezoneOffset=0&subscription-key=2b9324da598d4b52b6b78eccb45a7a05";
            string querystring2 = System.Web.HttpUtility.UrlEncode(querystring);

            add = add + "q=" + querystring2;
            Uri address = new Uri(add);

            using (var client = new HttpClient())
            {
                try
                {
                    var result = await client.GetAsync(address);

                    if (result.IsSuccessStatusCode)
                    {
                        return(await result.Content.ReadAsStringAsync());
                    }
                    else
                    {
                        PXTrace.WriteInformation(address.ToString());
                        PXTrace.WriteInformation(result.ToString());
                        return(result.ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw new PX.Data.PXException(ex.Message);
                }
            }
        }
예제 #8
0
 private void TraceTransactionsInformation()
 {
     foreach (var line in subcontractLines)
     {
         PXTrace.WriteInformation(line.Dump());
     }
 }
예제 #9
0
        public virtual IEnumerable AuthorizeCCPayment(PXAdapter adapter)
        {
            var        methodName = GetClassMethodName();
            AccessInfo info       = this.Base.Accessinfo;

            PXTrace.WriteInformation($"{methodName} started.");
            List <TPrimary> list = new List <TPrimary>();

            foreach (TPrimary doc in adapter.Get <TPrimary>())
            {
                CheckDocumentUpdatedInDb(doc);
                PXCache cache = this.Base.Caches[typeof(TPrimary)];
                bool    prevAllowUpdateState = cache.AllowUpdate;
                cache.AllowUpdate = true;
                ICCPayment pDoc = GetPaymentDoc(doc);
                PXTrace.WriteInformation($"{methodName}. RefNbr:{pDoc.RefNbr}; UserName:{info.UserName}");
                list.Add(doc);
                BeforeAuthorizePayment(doc);
                var            afterAuthorizeActions = GetAfterAuthorizeActions();
                CCPaymentEntry paymentEntry          = GetCCPaymentEntry();
                foreach (var item in afterAuthorizeActions)
                {
                    paymentEntry.AddAfterProcessCallback(item);
                }
                if (ReleaseAfterAuthorize)
                {
                    paymentEntry.AddAfterProcessCallback(ReleaseARDocument);
                }
                paymentEntry.AuthorizeCCpayment(pDoc, new GenericExternalTransactionAdapter <ExternalTransactionDetail>(ExternalTransaction));
                cache.AllowUpdate = prevAllowUpdateState;
            }
            return(list);
        }
예제 #10
0
        public static void SendData(IEnumerable <SOOrder> data, string name = "orders.csv")
        {
            //Create needed graphs
            var graph = PXGraph.CreateInstance <AFSetupMaint>();

            AFSetup setup = graph.AFSetupView.Current ?? graph.AFSetupView.Select();

            //-----------------------------------------------------------------------------
            //Change for Setup daya
            string bucketName      = setup.AFBucketName;    //"acumatica-forecast";
            string s3DirectoryName = setup.AFDirectoryName; //"dynamics/facturas";
            string accessKey       = setup.AFAccessKey;
            string secretKey       = setup.AFSecretKey;

            //-----------------------------------------------------------------------------

            PXTrace.WriteInformation($"AFAccessKey: {accessKey} AFSecretKey: {secretKey} AFBucketName: {bucketName} AFDirectoryName: {s3DirectoryName}");

            //if (data?.Count == 0) return;

            using (var stream = new MemoryStream())
            {
                using (StreamWriter sw = new StreamWriter(stream))
                {
                    try
                    {
                        // Convert to csv and upload
                        foreach (var i in data)
                        {
                            try
                            {
                                //var row = data[i];
                                //Check current item
                                //PXProcessing.SetCurrentItem(row);

                                //sw.WriteLine(i);
                            }
                            catch (Exception e)
                            {
                                PXProcessing <SOOrder> .SetError(e.Message);
                            }
                        }

                        var line = $"TEST,2020-01-25T00:10:10,1.00";
                        sw.WriteLine(line);

                        //Si existe el CFDI permite la subida del XML y PDF
                        //Se crea la instancia a S3
                        AFAmazonTools myUploader = new AFAmazonTools();
                        var           result     = myUploader.UploadToS3(accessKey, secretKey, stream.ToArray(), bucketName, s3DirectoryName, name);
                    }
                    catch (Exception e)
                    {
                        PXProcessing <SOOrder> .SetError(e.Message);
                    }
                }
            }
        }
예제 #11
0
        public virtual IEnumerable IndexCustomArticles(PXAdapter adapter)
        {
            PXLongOperation.StartOperation(this, delegate()
            {
                foreach (var result in WikiArticles.Select())
                {
                    string plaintext = null;

                    var _wp = (WikiPage)result[typeof(WikiPage)];
                    var _wr = (WikiRevision)result[typeof(WikiRevision)];
                    var _wl = (WikiPageLanguage)result[typeof(WikiPageLanguage)];

                    if (_wp.IsHtml != true)
                    {
                        WikiReader reader       = PXGraph.CreateInstance <WikiReader>();
                        PXWikiSettings settings = new PXWikiSettings(new PXPage(), reader);
                        PXTxtRenderer renderer  = new PXTxtRenderer(settings.Absolute);
                        var ctx      = new PXDBContext(settings.Absolute);
                        ctx.Renderer = renderer;
                        plaintext    = (_wl.Title ?? "") + Environment.NewLine + PXWikiParser.Parse(_wr.Content, ctx);
                    }
                    else
                    {
                        plaintext = (_wl.Title ?? "") + Environment.NewLine + SearchService.Html2PlainText(_wr.Content);
                    }


                    //Try updating the article in current Company
                    if (!PXDatabase.Update <WikiRevision>(
                            new PXDataFieldAssign("PlainText", PXDbType.NVarChar, plaintext),
                            new PXDataFieldRestrict("PageID", PXDbType.UniqueIdentifier, _wr.PageID),
                            new PXDataFieldRestrict("PageRevisionID", PXDbType.Int, _wr.PageRevisionID),
                            new PXDataFieldRestrict("Language", PXDbType.VarChar, _wr.Language)
                            ))
                    {
                        //Article may be shared. Try updating the article through graph (thus handling the shared record update stratagy)
                        //if article is not updatable an exception may be thrown - ignore.
                        try
                        {
                            ArticleUpdater updater = PXGraph.CreateInstance <ArticleUpdater>();
                            WikiRevision rev       = updater.Revision.Select(_wr.PageID, _wr.PageRevisionID, _wr.Language);
                            rev.PlainText          = plaintext;
                            updater.Revision.Update(rev);
                            updater.Persist();
                        }
                        catch (Exception ex)
                        {
                            PXTrace.WriteInformation("Plain text field could not be updated for article = {0}. Error Message: {1}", _wr.PageID, ex.Message);
                        }
                    }
                }
            });



            return(adapter.Get());
        }
예제 #12
0
        public virtual decimal GetPerUnitTaxAmountForTaxableAdjustmentCalculation(Tax taxForTaxableAdustment, TaxDetail taxDetail, PXCache taxDetailCache,
                                                                                  object row, PXCache rowCache, string curyTaxAmtFieldName,
                                                                                  Func <List <object> > perUnitTaxSelector)
        {
            taxForTaxableAdustment.ThrowOnNull(nameof(taxForTaxableAdustment));
            taxDetail.ThrowOnNull(nameof(taxDetail));
            taxDetailCache.ThrowOnNull(nameof(taxDetailCache));
            row.ThrowOnNull(nameof(row));
            rowCache.ThrowOnNull(nameof(rowCache));
            curyTaxAmtFieldName.ThrowOnNullOrWhiteSpace(nameof(curyTaxAmtFieldName));
            perUnitTaxSelector.ThrowOnNull(nameof(perUnitTaxSelector));

            if (taxForTaxableAdustment.TaxType == CSTaxType.PerUnit)
            {
                return(0m);
            }

            Type          taxAmountField  = taxDetailCache.GetBqlField(curyTaxAmtFieldName);
            List <object> allPerUnitTaxes = perUnitTaxSelector?.Invoke();

            if (allPerUnitTaxes == null || allPerUnitTaxes.Count == 0)
            {
                return(0m);
            }

            var(perUnitInclusiveTaxes, perUnitLevel1Taxes) = GetNonExcludedPerUnitTaxesByCalculationLevel(allPerUnitTaxes);

            if (perUnitInclusiveTaxes.Count == 0 && perUnitLevel1Taxes.Count == 0)
            {
                return(0m);
            }

            switch (taxForTaxableAdustment.TaxCalcLevel)
            {
            case CSTaxCalcLevel.Inclusive when perUnitLevel1Taxes.Count > 0:
                PXTrace.WriteInformation(Messages.CombinationOfExclusivePerUnitTaxAndInclusveTaxIsForbiddenErrorMsg);
                throw new PXSetPropertyException(Messages.CombinationOfExclusivePerUnitTaxAndInclusveTaxIsForbiddenErrorMsg, PXErrorLevel.Error);

            case CSTaxCalcLevel.Inclusive:
                //The adjustment to taxable is amount of all per unit taxes. The level 1 per unit taxes are prohibited.
                return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, perUnitInclusiveTaxes, taxAmountField));

            case CSTaxCalcLevel.CalcOnItemAmt:
                var allNonExcludedPerUnitTaxes = perUnitInclusiveTaxes.Concat(perUnitLevel1Taxes);
                return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, allNonExcludedPerUnitTaxes, taxAmountField));

            case CSTaxCalcLevel.CalcOnItemAmtPlusTaxAmt:
                // For level 2 taxes:
                // Taxable = LineAmt - InclusiveTaxAmt (including per unit inclusive taxes) + Level 1 Taxes amount (including per unit level 1 taxes)
                // Therefore, we need to add only the previously subtracted amount of inclusive per unit taxes
                return(SumTaxAmountsWithReverseAdjustment(taxDetailCache.Graph, perUnitInclusiveTaxes, taxAmountField));

            default:
                return(0m);
            }
        }
예제 #13
0
        /// <summary>
        /// MAKE API CALLS ----> GET,POST,PUT,PATCH
        /// </summary>
        /// <param name="apiurl"></param>
        /// <param name="apirequest"></param>
        /// <param name="apimethod"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static KCAPIWebReponse CallWebAPI(string apiurl, string apirequest, string apimethod, WebHeaderCollection header, string contenttype = "application/json")
        {
            KCAPIWebReponse response = new KCAPIWebReponse();

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
                                                   | SecurityProtocolType.Tls11
                                                   | SecurityProtocolType.Tls12
                                                   | SecurityProtocolType.Ssl3;
            HttpWebRequest web_request = (HttpWebRequest)WebRequest.Create(apiurl);

            web_request.Headers     = header;
            web_request.Method      = apimethod;
            web_request.ContentType = contenttype;// ;
            if (!string.IsNullOrEmpty(apirequest))
            {
                byte[] byteArray = Encoding.ASCII.GetBytes(apirequest);
                web_request.ContentLength = byteArray.Length;
                Stream req_datastream = web_request.GetRequestStream();
                req_datastream.Write(byteArray, 0, byteArray.Length);
                req_datastream.Close();
            }

            try
            {
                HttpWebResponse web_response   = (HttpWebResponse)web_request.GetResponse();
                Stream          res_datastream = web_response.GetResponseStream();

                using (StreamReader reader = new StreamReader(res_datastream))

                {
                    string responseFromServer = reader.ReadToEnd();

                    response.httpWebRes = web_response;
                    response.response   = responseFromServer;
                    response.Message    = "Success";
                    response.IsSuccess  = true;
                    reader.Close();
                    //res_datastream.Close();
                    web_response.Close();
                }
            }
            catch (WebException exception)
            {
                string sResponse = new StreamReader(exception.Response.GetResponseStream()).ReadToEnd();
                PXTrace.WriteInformation(sResponse);
                response.Message   = exception.Message + Environment.NewLine;
                response.IsSuccess = false;
            }
            catch (Exception exception)
            {
                response.Message   = exception.Message;
                response.IsSuccess = false;
            }

            return(response);
        }
예제 #14
0
        public virtual IEnumerable importForecast(PXAdapter adapter)
        {
            PXLongOperation.StartOperation(this, delegate()
            {
                //Create needed graphs
                var graph = PXGraph.CreateInstance <AFResultMaint>();

                AFSetup setup = graph.Setup.Current ?? graph.Setup.Select();

                //-----------------------------------------------------------------------------
                //Change for Setup daya
                string bucketName      = setup.AFBucketName;
                string s3DirectoryName = setup.AFOutDirectoryName;
                string accessKey       = setup.AFAccessKey;
                string secretKey       = setup.AFSecretKey;
                //-----------------------------------------------------------------------------

                PXTrace.WriteInformation($"AFAccessKey: {accessKey} AFSecretKey: {secretKey} AFBucketName: {bucketName} AFDirectoryName: {s3DirectoryName}");

                //if (data?.Count == 0) return;


                try
                {
                    AFAmazonTools myUploader = new AFAmazonTools();
                    var result = myUploader.DownloadFromS3(accessKey, secretKey, bucketName, s3DirectoryName);

                    foreach (var line in result)
                    {
                        try
                        {
                            var item          = new AFResult();
                            item.ResultID     = line[0];
                            item.ResultTstamp = DateTime.Parse(line[1], null, System.Globalization.DateTimeStyles.RoundtripKind);
                            item.ResultP10    = Convert.ToDecimal(line[2]);
                            item.ResultE50    = Convert.ToDecimal(line[3]);
                            item.ResultP90    = Convert.ToDecimal(line[4]);

                            graph.AFResultView.Update(item);
                        }
                        catch (Exception e)
                        {
                            PXTrace.WriteError($"Error parsing data ({String.Join(",", line)}): {e.Message}");
                        }
                    }
                    graph.Save.Press();
                }
                catch (Exception e)
                {
                    throw new PXException(e.Message, e);
                }
            });

            return(adapter.Get());
        }
예제 #15
0
        private ListOrdersResponse InvokeListOrders(PXGraph graph, ServiceCallParameters objParams)
        {
            ListOrdersResponse response = new ListOrdersResponse();

            try
            {
                ListOrdersRequest request = new ListOrdersRequest();
                request.SellerId     = objParams.objSOAmazonSetup.SellerId;
                request.MWSAuthToken = objParams.objSOAmazonSetup.AuthToken;
                List <string> marketplaceId = new List <string>();
                marketplaceId.Add(objParams.objSOAmazonSetup.MarketplaceId);
                request.MarketplaceId = marketplaceId;
                request.CreatedAfter  = Convert.ToDateTime(objParams.fromDate);
                if (objParams.toDate.Value.Date < DateTime.Now.Date)
                {
                    request.CreatedBefore = objParams.toDate.Value.AddDays(1).AddTicks(-1);
                }
                PXTrace.WriteInformation("objParams.fromDate.Value.Date:" + objParams.fromDate.Value.Date.ToString());
                PXTrace.WriteInformation("objParams.toDate.Value.Date:" + objParams.toDate.Value.Date.ToString());
                PXTrace.WriteInformation("request.CreatedAfter:" + request.CreatedAfter.ToString());
                PXTrace.WriteInformation("request.CreatedBefore:" + request.CreatedBefore.ToString());
                List <string> liFulfillmentChannel = null;
                List <string> liOrderStatus        = null;
                SOHelper.GetFilterValues(objParams.objSOAmazonSetup.IntegrationType.Trim(), out liFulfillmentChannel, out liOrderStatus);
                request.FulfillmentChannel = liFulfillmentChannel;
                request.OrderStatus        = liOrderStatus;
                response = this.clientOrder.ListOrders(request);
            }
            catch (Exception ex)
            {
                if (ex is MarketplaceWebServiceOrdersException)
                {
                    MarketplaceWebServiceOrdersException exception = ex as MarketplaceWebServiceOrdersException;
                    if (!string.IsNullOrEmpty(exception.ErrorCode) && exception.ErrorCode.ToLower().Trim() == SOMessages.requestThrottled)
                    {
                        Thread.Sleep(SOHelper.DelayProcess(graph, SOConstants.apiListOrders));
                        response = InvokeListOrders(graph, objParams);
                    }
                    else
                    {
                        throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message :
                                              ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message
                           : SOConstants.exceptionIsEmpty);
                    }
                }
                else
                {
                    throw new PXException(!string.IsNullOrEmpty(ex.Message) ? ex.Message :
                                          ex.InnerException != null && ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message
                            : SOConstants.exceptionIsEmpty);
                }
            }
            return(response);
        }
            public void GetPaymentForm(V2.ProcessingInput inputData)
            {
                var formProcessor = GetProcessor <V2.ICCHostedPaymentFormProcessor>();
                var result        = V2PluginErrorHandler.ExecuteAndHandleError(() => {
                    CheckWebhook();
                    return(formProcessor.GetDataForPaymentForm(inputData));
                });

                PXTrace.WriteInformation($"Perform PaymentRedirectException. Url: {result.Url}");
                throw new PXPaymentRedirectException(result.Caption, result.Url, result.UseGetMethod, result.Token, result.Parameters);
            }
        protected override bool Process(Package package)
        {
            PXTrace.WriteInformation("Processing email package. ");

            var account    = package.Account;
            var accountExt = account.GetExtension <PX.SM.EMailAccountExt>();

            //Checkin if Incoming Processing is active & SO Processing
            if (account.IncomingProcessing != true ||
                accountExt.UsrCustomMailer != true)
            {
                PXTrace.WriteInformation("IncomingProcessing: " + account.IncomingProcessing + ", SOProcessing: " + accountExt.UsrCustomMailer + ". ");
                return(false);
            }

            var message = package.Message;

            //Check if not empty email
            if (!string.IsNullOrEmpty(message.Exception) ||
                message.IsIncome != true ||
                message.RefNoteID != null)
            {
                PXTrace.WriteInformation("IsIncome: " + message.IsIncome + ", RefNoteID: " + message.RefNoteID + ". ");
                return(false);
            }

            string  mailBody         = HtmlRemoval.StripTagsRegexCompiled(package.Message.Body);
            LuisAPI predictionEngine = PXGraph.CreateInstance <LuisAPI>();
            var     myTask           = predictionEngine.PostPrediction(mailBody);
            string  result;

            try
            {
                result = myTask.Result;
            }
            catch (Exception ex)
            {
                throw new PXException(ex.Message);
            }

            //Create BuildersPO Graph

            //Get File Attachment
            UploadFile file = SelectFrom <UploadFile> .
                              InnerJoin <NoteDoc> .On <UploadFile.fileID.IsEqual <NoteDoc.fileID> > .SingleTableOnly.
                              Where <UploadFile.noteID.IsEqual <@P.AsGuid> > .View.Select(package.Graph, message.NoteID);

            MailerSOGraph soGraph = PXGraph.CreateInstance <MailerSOGraph>();

            soGraph.GenerateSalesOrders(result, package.Message.MailFrom, Convert.ToDateTime(package.Message.CreatedDateTime));

            return(true);
        }
            private void CheckWebhook()
            {
                V2SettingsGenerator seetingsGen = new V2SettingsGenerator(_provider);

                if (!CCProcessingFeatureHelper.IsFeatureSupported(_plugin.GetType(), CCProcessingFeature.WebhookManagement))
                {
                    PXTrace.WriteInformation("Skip check webhook. Plugin doesn't implement this feature.");
                    return;
                }

                V2.ICCWebhookProcessor processor = _plugin.CreateProcessor <V2.ICCWebhookProcessor>(seetingsGen.GetSettings());
                if (!processor.WebhookEnabled)
                {
                    PXTrace.WriteInformation("Skip check webhook. This feature is disabled.");
                    return;
                }
                string eCompanyName = V2.CCServiceEndpointHelper.EncodeUrlSegment(CompanyName);
                string eProcCenter  = V2.CCServiceEndpointHelper.EncodeUrlSegment(ProcessingCenterId);
                string url          = V2.CCServiceEndpointHelper.GetEndpointUrl(eCompanyName, eProcCenter);

                if (url == null || url.Contains("localhost"))
                {
                    PXTrace.WriteInformation($"Skip check webhook. Not valid Url: {url}");
                    return;
                }

                bool result = checkUrl.IsMatch(url);

                if (!result)
                {
                    PXTrace.WriteInformation($"Skip check webhook. Not valid Url: {url}");
                    return;
                }

                IEnumerable <V2.Webhook> list = processor.GetAttachedWebhooks();

                V2.Webhook res = list.Where(i => i.Url == url).FirstOrDefault();
                if (res == null)
                {
                    string name = "AcumaticaWebhook";
                    PXTrace.WriteInformation($"Webhook not found. Performing add webhook with name = {name}, url = {url}");
                    V2.Webhook webhook = new V2.Webhook();
                    webhook.Enable = true;
                    webhook.Events = new List <V2.WebhookEvent>()
                    {
                        V2.WebhookEvent.CreateAuthTran,
                        V2.WebhookEvent.CreateAuthCaptureTran,
                    };
                    webhook.Name = name;
                    webhook.Url  = url;
                    processor.AddWebhook(webhook);
                }
            }
예제 #19
0
        public virtual IEnumerable ManageCCPaymentMethodHF(PXAdapter adapter)
        {
            ICCPaymentProfile currentPaymentMethod = CustomerPaymentMethod.Current;
            string            methodName           = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            PXTrace.WriteInformation($"{methodName}; CCProcessingCenterID:{currentPaymentMethod.CCProcessingCenterID}.");
            var graph = PXGraph.CreateInstance <CCCustomerInformationManagerGraph>();

            graph.GetManagePaymentProfileForm(this.Base, currentPaymentMethod);
            return(adapter.Get());
        }
        public void Commit()
        {
            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.None || !_errors.Any())
            {
                return;
            }

            foreach (InconsistencyError error in _errors)
            {
                foreach (RecordContextInfo contextInfo in error.ContextData)
                {
                    PXTrace.WriteInformation(contextInfo.Cache.GetFullDescription(contextInfo.Record));
                }

                PXTrace.WriteInformation($"{error.ErrorCode} {error.IntegrityException.Message}");
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Prevent)
            {
                DataIntegrityException firstError = _errors.First().IntegrityException;

                throw new DataIntegrityException(
                          firstError.InconsistencyCode,
                          Messages.DataIntegrityErrorDuringProcessingFormat,
                          firstError.Message);
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Log)
            {
                DateTime now = DateTime.UtcNow;

                foreach (InconsistencyError error in _errors)
                {
                    DataIntegrityLog logEntry = _graph.Caches <DataIntegrityLog>().Insert(new DataIntegrityLog
                    {
                        UtcTime          = now,
                        UserBranchID     = _graph.Accessinfo.BranchID,
                        UserID           = _graph.Accessinfo.UserID,
                        ExceptionMessage = error.IntegrityException.Message,
                        ContextInfo      = error.ContextData.Any()
                                                        ? string.Format(
                            "<Context>\r\n{0}\r\n</Context>",
                            string.Join("\r\n", error.ContextData.Select(contextInfo => contextInfo.Cache.ToXml(contextInfo.Record))))
                                                        : null,
                        InconsistencyCode = error.IntegrityException.InconsistencyCode,
                    }) as DataIntegrityLog;
                }

                _graph.Caches <DataIntegrityLog>().Persist(PXDBOperation.Insert);
                _graph.Caches <DataIntegrityLog>().Persisted(false);
            }
        }
예제 #21
0
        public virtual IEnumerable CreateCCPaymentMethodHF(PXAdapter adapter)
        {
            string methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            CustomerPaymentMethod currentPaymentMethod = CustomerPaymentMethod.Current;

            if (currentPaymentMethod.CCProcessingCenterID == null)
            {
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.cCProcessingCenterID>(currentPaymentMethod);
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.customerCCPID>(currentPaymentMethod);
            }
            var graph = PXGraph.CreateInstance <CCCustomerInformationManagerGraph>();

            graph.GetCreatePaymentProfileForm(this.Base, new GenericCCPaymentProfileAdapter <CustomerPaymentMethod>(CustomerPaymentMethod));
            return(adapter.Get());
        }
        public override IEnumerable CaptureCCPayment(PXAdapter adapter)
        {
            IEnumerable ret;
            string      methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            ShowProcessingWarnIfLock(adapter);
            if (!UseAcceptHostedForm)
            {
                ret = base.CaptureCCPayment(adapter);
            }
            else
            {
                ret = CaptureThroughForm(adapter);
            }
            return(ret);
        }
예제 #23
0
        public virtual IEnumerable CaptureOnlyCCPayment(PXAdapter adapter)
        {
            var methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            AccessInfo info       = this.Base.Accessinfo;
            var        parameters = InputPaymentInfo.Current;

            if (parameters == null)
            {
                return(adapter.Get());
            }
            if (string.IsNullOrEmpty(parameters.AuthNumber))
            {
                if (InputPaymentInfo.Cache.RaiseExceptionHandling <InputPaymentInfo.authNumber>(parameters,
                                                                                                null, new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(InputPaymentInfo.authNumber).Name)))
                {
                    throw new PXRowPersistingException(typeof(InputPaymentInfo.authNumber).Name, null, ErrorMessages.FieldIsEmpty, typeof(InputPaymentInfo.authNumber).Name);
                }
                return(adapter.Get());
            }
            List <TPrimary> list = new List <TPrimary>();

            foreach (TPrimary doc in adapter.Get <TPrimary>())
            {
                CheckDocumentUpdatedInDb(doc);
                ICCPayment pDoc = GetPaymentDoc(doc);
                PXTrace.WriteInformation($"{methodName}. RefNbr:{pDoc.RefNbr}; UserName:{info.UserName}");
                list.Add(doc);
                BeforeCaptureOnlyPayment(doc);
                var            tranAdapter  = new GenericExternalTransactionAdapter <ExternalTransactionDetail>(ExternalTransaction);
                var            afterActions = GetAfterCaptureOnlyActions();
                CCPaymentEntry paymentEntry = GetCCPaymentEntry();
                foreach (var item in afterActions)
                {
                    paymentEntry.AddAfterProcessCallback(item);
                }
                if (ReleaseAfterCaptureOnly)
                {
                    paymentEntry.AddAfterProcessCallback(ReleaseARDocument);
                }
                paymentEntry.CaptureOnlyCCPayment(parameters, pDoc, tranAdapter);
            }
            return(list);
        }
예제 #24
0
        private List <object> ExecuteRule(Table item, EPRule rule, ref bool isSuccessful)
        {
            try
            {
                List <EPRuleBaseCondition> conditions =
                    PXSelectReadonly <EPRuleCondition,
                                      Where <EPRuleCondition.ruleID, Equal <Required <EPRule.ruleID> >, And <EPRuleCondition.isActive, Equal <boolTrue> > > >
                    .Select(this, rule.RuleID)
                    .Select(_ => (EPRuleBaseCondition)_)
                    .ToList();

                if (conditions.Count == 0)
                {
                    return(null);
                }


                Type resultViewType = CreateResultView(processGraph, conditions);


                PXView itemView = new PXView(processGraph, false, BqlCommand.CreateInstance(resultViewType),
                                             (PXSelectDelegate)getItemRecord);

                Select(item, itemView, conditions.Select(_ => GraphHelper.GetType(_.Entity)).Distinct().ToList(), null);


                PXFilterRow[] filters = GenerateFilters(item, conditions).ToArray <PXFilterRow>();

                int           startRow  = 0;
                int           totalRows = 0;
                List <object> result    = itemView.Select(null, null, null, null, null, filters, ref startRow, 0, ref totalRows);

                results.Clear();

                TraceResult(rule, conditions, result.Count);

                return(result);
            }
            catch (Exception e)
            {
                isSuccessful = false;
                PXTrace.WriteInformation(e);
                return(null);
            }
        }
예제 #25
0
        private static string GetReturnUrl()
        {
            // Code taken from PX.Api.Webhooks.Owin.Configuration.ReturnUrl._get
            // Added here because WebHookMaint crashes when retrieving the WebHook URL in background thread
            // because HttpContext.Current is null
            //PXTrace.WriteInformation(HttpContext.Current.Request.GetWebsiteUrl());
            if (HttpContext.Current != null)
            {
                // Get application path from URL with no starting slash
                string applicationPath = HttpContext.Current.Request.ApplicationPath.TrimStart('/');

                // Print WebsiteUrl to trace
                PXTrace.WriteInformation(HttpContext.Current.Request.GetWebsiteUrl());

                // Join base with path parts
                _returnUrl = JoinUriSegments(HttpContext.Current.Request.GetWebsiteUrl(), applicationPath, "Webhooks");
            }
            return(_returnUrl);
        }
예제 #26
0
        public virtual IEnumerable SyncCCPaymentMethods(PXAdapter adapter)
        {
            string methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            CustomerPaymentMethod currentPaymentMethod = CustomerPaymentMethod.Current;

            PXTrace.WriteInformation($"{methodName}. CCProcessingCenterID:{currentPaymentMethod.CCProcessingCenterID}; UserName:{this.Base.Accessinfo.UserName}");
            IEnumerable ret = adapter.Get();

            bool isCancel = false;

            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            var cancelStr = request.Form.Get("__CLOSECCHFORM");

            bool.TryParse(cancelStr, out isCancel);
            if (isCancel)
            {
                return(ret);
            }

            if (currentPaymentMethod.CCProcessingCenterID == null)
            {
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.cCProcessingCenterID>(currentPaymentMethod);
                CustomerPaymentMethod.Cache.SetDefaultExt <CustomerPaymentMethod.customerCCPID>(currentPaymentMethod);
            }
            var graph = PXGraph.CreateInstance <CCCustomerInformationManagerGraph>();

            ICCPaymentProfileAdapter       paymentProfile = new GenericCCPaymentProfileAdapter <CustomerPaymentMethod>(CustomerPaymentMethod);
            ICCPaymentProfileDetailAdapter profileDetail  = new GenericCCPaymentProfileDetailAdapter <CustomerPaymentMethodDetail, PaymentMethodDetail>(CustomerPaymentMethodDetail, PaymentMethodDetail);
            bool isIDFilled = CCProcessingHelper.IsCCPIDFilled(this.Base, CustomerPaymentMethod.Current.PMInstanceID);

            if (!isIDFilled)
            {
                graph.GetNewPaymentProfiles(this.Base, paymentProfile, profileDetail);
            }
            else
            {
                graph.GetPaymentProfile(this.Base, paymentProfile, profileDetail);
            }
            this.Base.Persist();
            return(ret);
        }
        public void Commit()
        {
            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.None || !_errors.Any())
            {
                return;
            }

            foreach (InconsistencyError error in _errors)
            {
                foreach (RecordContextInfo contextInfo in error.ContextData)
                {
                    PXTrace.WriteInformation(contextInfo.Cache.GetFullDescription(contextInfo.Record));
                }

                PXTrace.WriteInformation($"{error.ErrorCode} {error.IntegrityException.Message}");
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Prevent)
            {
                DataIntegrityException firstError = _errors.First().IntegrityException;

                throw new DataIntegrityException(
                          firstError.InconsistencyCode,
                          Messages.DataIntegrityErrorDuringProcessingFormat,
                          firstError.Message);
            }

            if (_inconsistencyHandlingMode == InconsistencyHandlingMode.Log)
            {
                DateTime now = DateTime.UtcNow;

                foreach (InconsistencyError error in _errors)
                {
                    string context = error.ContextData.Any()
                                                ? string.Join("\r\n",
                                                              error.ContextData.Select(contextInfo => contextInfo.Cache.ToXml(contextInfo.Record)))
                                                : string.Empty;
                    var errorMsg = $"Error message: {error.IntegrityException.Message}; Date: {DateTime.Now}; Screen: {_graph.Accessinfo.ScreenID}; Context: {context}; InconsistencyCode: {error.IntegrityException.InconsistencyCode}";
                    PXTrace.WriteError(errorMsg);
                }
            }
        }
        public override IEnumerable ValidateCCPayment(PXAdapter adapter)
        {
            string methodName = GetClassMethodName();

            PXTrace.WriteInformation($"{methodName} started.");
            ShowProcessingWarnIfLock(adapter);
            Base.Actions.PressCancel();
            List <TPrimary> list = new List <TPrimary>();

            foreach (TPrimary doc in adapter.Get <TPrimary>())
            {
                list.Add(doc);
                PXLongOperation.StartOperation(Base, delegate
                {
                    CheckPaymentTranForceSync(doc);
                    RemoveSyncLock(doc);
                });
            }
            return(list);
        }
        ///<summary>
        /// Finding inconsistency between document and its applications.
        /// Run this method at end point of the "Release" process.
        /// Validating case:
        /// Released flag for document and its applications should always
        /// be the same after the "Release" process.
        ///</summary>
        public DataIntegrityValidator <TRegister> CheckApplicationsReleasedForDocument <TAdjust, TAdjgDocType, TAdjgRefNbr, TReleased>(bool disableCheck = false)
            where TAdjust : class, IBqlTable, new()
            where TAdjgDocType : IBqlField
            where TAdjgRefNbr : IBqlField
            where TReleased : IBqlField
        {
            if (IsSkipCheck(disableCheck))
            {
                return(this);
            }

            PXSelectBase <TAdjust> selectTAdjust = new PXSelect <
                TAdjust,
                Where <
                    TAdjgDocType, Equal <Required <TAdjgDocType> >,
                    And <TAdjgRefNbr, Equal <Required <TAdjgRefNbr> >,
                         And <TReleased, NotEqual <Required <TReleased> > > > > >(_graph);

            TAdjust adj = selectTAdjust.SelectSingle(_doc.DocType, _doc.RefNbr, _released);

            if (adj != null)
            {
                PXTrace.WriteInformation(_docCache.GetFullDescription(_doc));
                PXTrace.WriteInformation(selectTAdjust.Cache.GetFullDescription(adj));

                if (_released == true)
                {
                    _errors.Add(new InconsistencyError <InconsistencyCode.releasedDocumentHasUnreleasedApplications>(
                                    new RecordContextInfo(_docCache, _doc),
                                    new RecordContextInfo(selectTAdjust.Cache, adj)));
                }
                else
                {
                    _errors.Add(new InconsistencyError <InconsistencyCode.unreleasedDocumentHasReleasedApplications>(
                                    new RecordContextInfo(_docCache, _doc),
                                    new RecordContextInfo(selectTAdjust.Cache, adj)));
                }
            }

            return(this);
        }
예제 #30
0
        protected void PersistMessages(IEnumerable <CRSMEmail> messages)
        {
            using (PXTransactionScope ts = new PXTransactionScope())
            {
                if (_newAttachments.Count > 0)
                {
                    var upload = PXGraph.CreateInstance <UploadFileMaintenance>();
                    upload.IgnoreFileRestrictions = true;
                    foreach (FileInfo file in _newAttachments)
                    {
                        upload.SaveFile(file);
                        if (file.UID == null)
                        {
                            throw new Exception(string.Format("Cannot save file '{0}'" + file.Name));
                        }
                    }
                }

                foreach (CRSMEmail item in messages)
                {
                    try
                    {
                        var activityCache = Graph.Caches[item.GetType()];
                        PXDBDefaultAttribute.SetSourceType <CRSMEmail.refNoteID>(activityCache, item, null);
                        activityCache.PersistInserted(item);
                    }
                    catch (Exception e)
                    {
                        if (!MassProcessMode)
                        {
                            throw;
                        }
                        PXTrace.WriteInformation(e);
                    }
                }
                Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Insert);
                Graph.Caches <CRActivityStatistics>().Persist(PXDBOperation.Update);

                ts.Complete();
            }
        }