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);
        }
        private static void UpdateFeedStatus(SubmitFeedParamaters objParams)
        {
            if (objParams != null && objParams.importOrderStatus)
            {
                SOShipment currentshipment = objParams.objPartialMaint.Shipment.Select(objParams.shipmentType, objParams.shipmentNbr);
                if (currentshipment != null)
                {
                    SOShipmentAmazonExt currentshipmentext = currentshipment.GetExtension <SOShipmentAmazonExt>();
                    if (currentshipmentext != null)
                    {
                        objParams.objPartialMaint.Shipment.SetValueExt <SOShipmentAmazonExt.usrSubmitFeedupdate>(currentshipment, true);
                        objParams.objPartialMaint.Shipment.Cache.Update(currentshipment);
                    }
                }
            }
            SOSubmitProcessLog processUpdateCount = null;

            if (objParams != null && objParams.objSOAmazonSetup != null && objParams.processID != null)
            {
                processUpdateCount = objParams.objPartialMaint.UpdateFeedProcessLog.Select(objParams.objSOAmazonSetup.IntegrationID, objParams.processID);
            }
            if (processUpdateCount == null)
            {
                return;
            }
            processUpdateCount.SubmitRecordsCount       = objParams.importOrderStatus ? processUpdateCount.SubmitRecordsCount + 1 : processUpdateCount.SubmitRecordsCount;
            processUpdateCount.SubmitFailedRecordsCount = objParams.importOrderStatus == false ? processUpdateCount.SubmitFailedRecordsCount + 1 : processUpdateCount.SubmitFailedRecordsCount;
            objParams.objPartialMaint.UpdateFeedProcessLog.Update(processUpdateCount);
        }
        private SubmitFeedResponse InvokeSubmitFeed(SubmitFeedParamaters objParams, string xmlFeedContent)
        {
            SubmitFeedResponse resSubmitFeed = new SubmitFeedResponse();

            try
            {
                UTF8Encoding      encoding   = new UTF8Encoding();
                Stream            streamData = new MemoryStream(encoding.GetBytes(xmlFeedContent));
                SubmitFeedRequest request    = new SubmitFeedRequest();
                request.Merchant             = objParams.objSOAmazonSetup.SellerId;
                request.FeedContent          = streamData;
                request.ContentMD5           = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
                request.FeedContent.Position = 0;
                request.PurgeAndReplace      = false;
                request.FeedType             = SOConstants.feedTypePostOrderFulfillment;
                request.MWSAuthToken         = objParams.objSOAmazonSetup.AuthToken;
                resSubmitFeed = clientFeed.SubmitFeed(request);
            }
            catch (Exception ex)
            {
                if (ex is MarketplaceWebServiceException)
                {
                    MarketplaceWebServiceException exception = ex as MarketplaceWebServiceException;
                    if (!string.IsNullOrEmpty(exception.ErrorCode) && exception.ErrorCode.ToLower().Trim() == SOMessages.requestThrottled)
                    {
                        Thread.Sleep(SOHelper.DelayProcess(objParams.objPartialMaint, SOConstants.apiSubmitFeed));
                        resSubmitFeed = InvokeSubmitFeed(objParams, xmlFeedContent);
                    }
                    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(resSubmitFeed);
        }
        public AmazonEnvelope InvokeServicesCalls(SubmitFeedParamaters objParams, string xmlFeedContent)
        {
            AmazonEnvelope resultEnvelope = null;

            try
            {
                MarketplaceWebService.MarketplaceWebService serviceConfig = this.Configurations(objParams.objSOAmazonSetup.IntegrationType.Trim(), objParams.objSOAmazonSetup.AccessKey, objParams.objSOAmazonSetup.SecretKey);
                if (serviceConfig != null)
                {
                    SubmitFeedResponse feedresponse = null;
                    feedresponse = new AMSubmitFeedServiceCall(serviceConfig).InvokeSubmitFeed(objParams, xmlFeedContent);
                    if (feedresponse != null && feedresponse.SubmitFeedResult != null && feedresponse.SubmitFeedResult.FeedSubmissionInfo != null &&
                        !string.IsNullOrEmpty(feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedProcessingStatus) &&
                        feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedProcessingStatus.ToUpper().Trim('_') == SOConstants.Submitted)
                    {
                        string submissionFeedId = feedresponse.SubmitFeedResult.FeedSubmissionInfo.FeedSubmissionId;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            new AMSubmitFeedServiceCall(serviceConfig).GetSubmitFeedResult(objParams, submissionFeedId, ms);
                            XmlDocument xDocument = new XmlDocument();
                            xDocument.Load(ms);
                            string        xmlResultContent = SOHelper.ObjectToXMLConversion(xDocument, string.Empty, true);
                            XmlSerializer deserializer     = new XmlSerializer(typeof(AmazonEnvelope), new XmlRootAttribute(SOConstants.amazonEnvelope));
                            using (TextReader reader = new StringReader(xmlResultContent))
                            {
                                resultEnvelope = (AmazonEnvelope)deserializer.Deserialize(reader);
                            }
                            return(resultEnvelope);
                        }
                    }
                }
                else
                {
                    throw new PXException(SOConstants.credentialsinvalid);
                }
            }
            catch (Exception ex)
            {
                throw new PXException(ex.Message);
            }
            return(resultEnvelope);
        }
 public static void LogSubmitStatus(SubmitFeedParamaters objParams)
 {
     if (objParams != null && objParams.objSOAmazonSetup != null && objParams.objPartialMaint != null)
     {
         objParams.objPartialMaint.Clear();
         UpdateFeedStatus(objParams);
         SOSubmitDetailedProcessLog logRecord = new SOSubmitDetailedProcessLog();
         logRecord.ProcessID             = objParams.processID;
         logRecord.IntegrationID         = objParams.objSOAmazonSetup.IntegrationID;
         logRecord.AmazonOrderID         = objParams.amazonOrderID;
         logRecord.AcumaticaOrderType    = objParams.soType;
         logRecord.AcumaticaOrderNbr     = objParams.acmOrderNbr;
         logRecord.AcumaticaShipmentType = objParams.shipmentType;
         logRecord.AcumaticaShipmentNbr  = objParams.shipmentNbr;
         logRecord.ImportStatus          = objParams.importOrderStatus;
         logRecord.ErrorDesc             = objParams.feedMessage;
         logRecord.XMLResponse           = objParams.xmlMessage;
         objParams.objPartialMaint.SubmitDetailedProcesLog.Insert(logRecord);
         objParams.objPartialMaint.Actions.PressSave();
     }
 }
 private void GetSubmitFeedResult(SubmitFeedParamaters objParams, string submissionFeedId, MemoryStream ms)
 {
     try
     {
         GetFeedSubmissionResultRequest request = new GetFeedSubmissionResultRequest();
         request.FeedSubmissionId     = submissionFeedId;
         request.Merchant             = objParams.objSOAmazonSetup.SellerId;
         request.MWSAuthToken         = objParams.objSOAmazonSetup.AuthToken;
         request.FeedSubmissionResult = ms;
         clientFeed.GetFeedSubmissionResult(request);
     }
     catch (Exception ex)
     {
         if (ex is MarketplaceWebServiceException)
         {
             MarketplaceWebServiceException exception = ex as MarketplaceWebServiceException;
             if (!string.IsNullOrEmpty(exception.ErrorCode) && exception.ErrorCode.ToLower().Trim() == SOConstants.feedProcessingResultNotReady)
             {
                 Thread.Sleep(SOHelper.DelayProcess(objParams.objPartialMaint, SOConstants.apiFeedResultWaiting));
                 GetSubmitFeedResult(objParams, submissionFeedId, ms);
             }
             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);
         }
     }
 }
        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);
        }
        public virtual void AmazonSubmitFeed(List <ProjectionShipmentDAC> list, SubmitFeedFilter currentFilter)
        {
            SOPartialMaint logGraph  = PXGraph.CreateInstance <SOPartialMaint>();
            int?           processId = list.Count > 0 ? SOLogService.LogSubmitCount(logGraph, currentFilter.IntegrationID, list.Count) : null;

            if (!(processId > 0))
            {
                return;
            }
            SubmitFeedParamaters objSubmitFeedParams = null;
            StringBuilder        sbXmlFeedData       = new StringBuilder();

            objEnvelope = new AmazonEnvelope();
            objHeader   = new Header();
            objHeader.DocumentVersion = SOConstants.documentVersion;
            objEnvelope.MessageType   = SOConstants.orderFulfillment;
            objEnvelope.Header        = objHeader;
            List <Message> liMsgContent       = new List <Message>();
            UTF8Encoding   encoding           = new UTF8Encoding();
            double         megaBytesLength    = 0.0d;
            bool           isErrorOccured     = false;
            Regex          xmlEmptytagsRemove = new Regex(@"(\s)*<(\w:\w|\w)*(\s)*/>");

            AMSubmitFeedServiceCall.AmazonEnvelope resAMEnv = null;
            List <Item> listItems = null;

            foreach (ProjectionShipmentDAC currentRecord in list)
            {
                SOAmazonSetup objSOAmazonSetup = null;
                Item          objitem          = null;
                SOHelper.MarketplaceConfigurations(logGraph, currentFilter.IntegrationID, out objSOAmazonSetup);
                objHeader.MerchantIdentifier = objSOAmazonSetup.SellerId;
                objSubmitFeedParams          = new SubmitFeedParamaters();
                listItems = new List <Item>();
                try
                {
                    logGraph.Clear();
                    foreach (PXResult <SOShipment, SOShipLine, Carrier, SOPackageDetail> result in PXSelectJoin <SOShipment, InnerJoin <SOShipLine, On <SOShipment.shipmentType, Equal <SOShipLine.shipmentType>,
                                                                                                                                                        And <SOShipment.shipmentNbr, Equal <SOShipLine.shipmentNbr> > >,
                                                                                                                                        InnerJoin <Carrier, On <SOShipment.shipVia, Equal <Carrier.carrierID> >,
                                                                                                                                                   LeftJoin <SOPackageDetail, On <SOPackageDetail.shipmentNbr, Equal <SOShipLine.shipmentNbr> > > > >,
                                                                                                                 Where <SOShipLine.shipmentNbr, Equal <Required <SOShipLine.shipmentNbr> > >,
                                                                                                                 OrderBy <Desc <SOPackageDetail.lineNbr> > > .Select(logGraph, currentRecord.ShipmentNbr))
                    {
                        SOShipment      objShipment       = (SOShipment)result;
                        SOShipLine      objShipLine       = (SOShipLine)result;
                        Carrier         objCarrier        = (Carrier)result;
                        SOPackageDetail objPackageDetails = (SOPackageDetail)result;
                        objitem = null;
                        if (objShipment != null && objShipLine != null && objPackageDetails != null && objPackageDetails.Confirmed != null && objPackageDetails.Confirmed == true && !string.IsNullOrEmpty(objPackageDetails.TrackNumber))
                        {
                            SOShipmentAmazonExt objShipmentExt = PXCache <SOShipment> .GetExtension <SOShipmentAmazonExt>(objShipment);

                            objSubmitFeedParams.soType       = objShipLine.OrigOrderType;
                            objSubmitFeedParams.acmOrderNbr  = objShipLine.OrigOrderNbr;
                            objSubmitFeedParams.shipmentType = objShipment.ShipmentType;
                            objSubmitFeedParams.shipmentNbr  = objShipment.ShipmentNbr;
                            objSubmitFeedParams.shipmentDate = objShipment.ShipDate;
                            objSubmitFeedParams.carrierCode  = !String.IsNullOrEmpty(objShipmentExt.UsrAmazonCarrierCode) ?
                                                               objShipmentExt.UsrAmazonCarrierCode : objShipment.ShipVia;
                            objSubmitFeedParams.shipVia = (objCarrier == null || String.IsNullOrEmpty(objCarrier.PluginMethod)) ?
                                                          objShipment.ShipVia : objCarrier.PluginMethod;
                            objSubmitFeedParams.trackingNbr = objPackageDetails.TrackNumber;
                            SOShipLineAmazonExt objShLineExt = objShipLine.GetExtension <SOShipLineAmazonExt>();
                            objSubmitFeedParams.amazonOrderID = objShLineExt != null && !string.IsNullOrEmpty(objShLineExt.UsrAmazonOrderID) ?
                                                                objShLineExt.UsrAmazonOrderID : string.Empty;
                            objitem = new Item();
                            objitem.AmazonOrderItemCode = objShLineExt != null && !string.IsNullOrEmpty(objShLineExt.UsrAMOrderItemID) ?
                                                          objShLineExt.UsrAMOrderItemID : string.Empty;
                            objitem.Quantity = objShipLine != null?Convert.ToInt32(objShipLine.ShippedQty) : 0;

                            listItems.Add(objitem);
                        }
                        else
                        {
                            throw new PXException(SOMessages.shipmentDetailsMissing);
                        }
                    }
                    objSubmitFeedParams.objPartialMaint     = logGraph;
                    objSubmitFeedParams.indexOfCurrentOrder = list.IndexOf(currentRecord);
                    objSubmitFeedParams.objSOAmazonSetup    = objSOAmazonSetup;
                    objSubmitFeedParams.processID           = processId;
                    if (listItems != null && listItems.Count > 0)
                    {
                        objSubmitFeedParams.liShipItem = listItems;
                    }
                    Message objMessage = GetListOfMessagesContent(objSubmitFeedParams);
                    if (objMessage.MessageID != null)
                    {
                        liMsgContent.Add(objMessage);
                    }
                }
                catch (Exception ex)
                {
                    isErrorOccured = true;
                    objSubmitFeedParams.feedMessage       = ex.Message;
                    objSubmitFeedParams.importOrderStatus = false;
                    objSubmitFeedParams.xmlMessage        = string.Empty;
                    SOLogService.LogSubmitStatus(objSubmitFeedParams);
                    PXProcessing <ProjectionShipmentDAC> .SetError(list.IndexOf(currentRecord), ex.Message);
                }
            }
            objEnvelope.MessageBody = SOConstants.messagebody;
            string resultFeed = SOHelper.ObjectToXMLConversion(objEnvelope, SOConstants.amazonEnvelope, false);

            if (liMsgContent.Count > 0)
            {
                foreach (Message listobj in liMsgContent)
                {
                    if (megaBytesLength >= SOConstants.feedSize)
                    {
                        break;
                    }
                    sbXmlFeedData.Append(SOHelper.ObjectToXMLConversion(listobj, SOConstants.messageBody, true) + SOConstants.getNewLine);
                    var byteData = encoding.GetBytes(sbXmlFeedData.ToString());
                    megaBytesLength = (byteData.Length / 1024f) / 1024f;
                }
                string xmlFeedContent = xmlEmptytagsRemove.Replace(resultFeed.Replace(SOConstants.msgbodyTag, Convert.ToString(sbXmlFeedData)), string.Empty);
                PXTrace.WriteInformation(xmlFeedContent);
                resAMEnv = new AMSubmitFeedServiceCall(clientFeed).InvokeServicesCalls(objSubmitFeedParams, xmlFeedContent);
            }
            if (resAMEnv != null && resAMEnv.Message != null && resAMEnv.Message.ProcessingReport != null && resAMEnv.Message.ProcessingReport.ProcessingSummary != null &&
                resAMEnv.Message.ProcessingReport.ProcessingSummary.MessagesProcessed == resAMEnv.Message.ProcessingReport.ProcessingSummary.MessagesSuccessful &&
                resAMEnv.Message.ProcessingReport.ProcessingSummary.MessagesWithError == 0)
            {
                foreach (ProjectionShipmentDAC currentRecord in list)
                {
                    UpdateSubmitLogDetails(list, objSubmitFeedParams, currentRecord, null);
                }
            }
            else if (resAMEnv != null && resAMEnv.Message != null && resAMEnv.Message.ProcessingReport != null &&
                     (resAMEnv.Message.ProcessingReport.ProcessingSummary.MessagesWithError > 0 ||
                      resAMEnv.Message.ProcessingReport.ProcessingSummary.MessagesSuccessful > 0))
            {
                bool isSubmitted;
                foreach (ProjectionShipmentDAC currentRecord in list)
                {
                    isSubmitted = false;
                    foreach (var item in resAMEnv.Message.ProcessingReport.Result.AsEnumerable().Where(x => x.MessageID == currentRecord.ShipmentNbr))
                    {
                        isSubmitted    = true;
                        isErrorOccured = true;
                        UpdateSubmitLogDetails(list, objSubmitFeedParams, currentRecord, item);
                    }
                    if (!isSubmitted)
                    {
                        UpdateSubmitLogDetails(list, objSubmitFeedParams, currentRecord, null);
                    }
                }
            }
            if (isErrorOccured)
            {
                throw new PXException(SOMessages.showErrorMsgFeeds);
            }
        }