public void ModelFactory_Merchant_IsConverted()
        {
            Merchant merchantModel = TestData.MerchantModelWithAddressesContactsDevicesAndOperators;

            ModelFactory modelFactory = new ModelFactory();

            MerchantResponse merchantResponse = modelFactory.ConvertFrom(merchantModel);

            merchantResponse.ShouldNotBeNull();
            merchantResponse.MerchantId.ShouldBe(merchantModel.MerchantId);
            merchantResponse.MerchantName.ShouldBe(merchantModel.MerchantName);
            merchantResponse.EstateId.ShouldBe(merchantModel.EstateId);
            merchantResponse.Addresses.ShouldHaveSingleItem();
            
            AddressResponse addressResponse = merchantResponse.Addresses.Single();
            addressResponse.AddressId.ShouldBe(merchantModel.Addresses.Single().AddressId);
            addressResponse.AddressLine1.ShouldBe(merchantModel.Addresses.Single().AddressLine1);
            addressResponse.AddressLine2.ShouldBe(merchantModel.Addresses.Single().AddressLine2);
            addressResponse.AddressLine3.ShouldBe(merchantModel.Addresses.Single().AddressLine3);
            addressResponse.AddressLine4.ShouldBe(merchantModel.Addresses.Single().AddressLine4);
            addressResponse.Town.ShouldBe(merchantModel.Addresses.Single().Town);
            addressResponse.Region.ShouldBe(merchantModel.Addresses.Single().Region);
            addressResponse.Country.ShouldBe(merchantModel.Addresses.Single().Country);
            addressResponse.PostalCode.ShouldBe(merchantModel.Addresses.Single().PostalCode);

            merchantResponse.Contacts.ShouldHaveSingleItem();
            ContactResponse contactResponse = merchantResponse.Contacts.Single();
            contactResponse.ContactId.ShouldBe(merchantModel.Contacts.Single().ContactId);
            contactResponse.ContactEmailAddress.ShouldBe(merchantModel.Contacts.Single().ContactEmailAddress);
            contactResponse.ContactName.ShouldBe(merchantModel.Contacts.Single().ContactName);
            contactResponse.ContactPhoneNumber.ShouldBe(merchantModel.Contacts.Single().ContactPhoneNumber);
        }
        public void ModelFactory_Merchant_NullAddresses_IsConverted()
        {
            Merchant merchantModel = TestData.MerchantModelWithNullAddresses;

            ModelFactory modelFactory = new ModelFactory();

            MerchantResponse merchantResponse = modelFactory.ConvertFrom(merchantModel);

            merchantResponse.ShouldNotBeNull();
            merchantResponse.MerchantId.ShouldBe(merchantModel.MerchantId);
            merchantResponse.MerchantName.ShouldBe(merchantModel.MerchantName);
            merchantResponse.EstateId.ShouldBe(merchantModel.EstateId);

            merchantResponse.Addresses.ShouldBeNull();
            
            merchantResponse.Contacts.ShouldHaveSingleItem();
            ContactResponse contactResponse = merchantResponse.Contacts.Single();
            contactResponse.ContactId.ShouldBe(merchantModel.Contacts.Single().ContactId);
            contactResponse.ContactEmailAddress.ShouldBe(merchantModel.Contacts.Single().ContactEmailAddress);
            contactResponse.ContactName.ShouldBe(merchantModel.Contacts.Single().ContactName);
            contactResponse.ContactPhoneNumber.ShouldBe(merchantModel.Contacts.Single().ContactPhoneNumber);

            merchantResponse.Devices.ShouldHaveSingleItem();
            KeyValuePair<Guid, String> device = merchantResponse.Devices.Single();
            device.Key.ShouldBe(merchantModel.Devices.Single().Key);
            device.Value.ShouldBe(merchantModel.Devices.Single().Value);

            merchantResponse.Operators.ShouldHaveSingleItem();
            MerchantOperatorResponse operatorDetails = merchantResponse.Operators.Single();
            operatorDetails.Name.ShouldBe(merchantModel.Operators.Single().Name);
            operatorDetails.OperatorId.ShouldBe(merchantModel.Operators.Single().OperatorId);
            operatorDetails.MerchantNumber.ShouldBe(merchantModel.Operators.Single().MerchantNumber);
            operatorDetails.TerminalNumber.ShouldBe(merchantModel.Operators.Single().TerminalNumber);
        }
Exemplo n.º 3
0
        public void CanFetchAndDeserializeCorrectly()
        {
            var expected = new MerchantResponse
            {
                CreatedAt        = DateTimeOffset.Parse("2011-11-18T17:07:09Z"),
                Description      = null,
                Id               = "WOQRUJU9OH2HH1",
                Name             = "Tom's Delicious Chicken Shop",
                FirstName        = "Tom",
                LastName         = "Blomfield",
                Email            = "*****@*****.**",
                Uri              = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1",
                Balance          = 12.00m,
                PendingBalance   = 0.00m,
                NextPayoutDate   = DateTimeOffset.Parse("2011-11-25T17: 07: 09Z"),
                NextPayoutAmount = 12.00m,
                SubResourceUris  =
                {
                    Users             = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/users",
                    Bills             = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/bills",
                    PreAuthorizations = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/pre_authorizations",
                    Subscriptions     = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/subscriptions",
                }
            };

            DeepAssertHelper.AssertDeepEquality(expected, new ApiClient("asdf").GetMerchant("WOQRUJU9OH2HH1"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets the merchant.
        /// </summary>
        /// <param name="accessToken">The access token.</param>
        /// <param name="estateId">The estate identifier.</param>
        /// <param name="merchantId">The merchant identifier.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        public async Task <MerchantResponse> GetMerchant(String accessToken,
                                                         Guid estateId,
                                                         Guid merchantId,
                                                         CancellationToken cancellationToken)
        {
            MerchantResponse response = null;

            String requestUri = this.BuildRequestUrl($"/api/estates/{estateId}/merchants/{merchantId}");

            try
            {
                // Add the access token to the client headers
                this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // Make the Http Call here
                HttpResponseMessage httpResponse = await this.HttpClient.GetAsync(requestUri, cancellationToken);

                // Process the response
                String content = await this.HandleResponse(httpResponse, cancellationToken);

                // call was successful so now deserialise the body to the response object
                response = JsonConvert.DeserializeObject <MerchantResponse>(content);
            }
            catch (Exception ex)
            {
                // An exception has occurred, add some additional information to the message
                Exception exception = new Exception($"Error getting merchant Id {merchantId} in estate {estateId}.", ex);

                throw exception;
            }

            return(response);
        }
Exemplo n.º 5
0
        public void CanFetchAndDeserializeCorrectly()
        {
            GoCardless.Environment = GoCardless.Environments.Sandbox;

            var expected = new MerchantResponse
            {
                CreatedAt        = DateTimeOffset.Parse("2011-11-18T17:07:09Z"),
                Description      = null,
                Id               = "WOQRUJU9OH2HH1",
                Name             = "Tom's Delicious Chicken Shop",
                FirstName        = "Tom",
                LastName         = "Blomfield",
                Email            = "*****@*****.**",
                Uri              = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1",
                Balance          = 12.00m,
                PendingBalance   = 0.00m,
                NextPayoutDate   = DateTimeOffset.Parse("2011-11-25T17: 07: 09Z"),
                NextPayoutAmount = 12.00m,
                SubResourceUris  =
                {
                    Users             = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/users",
                    Bills             = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/bills",
                    PreAuthorizations = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/pre_authorizations",
                    Subscriptions     = "https://gocardless.com/api/v1/merchants/WOQRUJU9OH2HH1/subscriptions",
                }
            };
            var client   = new ApiClient("3MMVNZERVE7X8FN8AGYZM3EBANVTD3NZENEVPN62BAVHY3FCEVQJ9JA6RZEDGTEF");
            var response = client.GetMerchant("0NP016PZPT");

            DeepAssertHelper.AssertDeepEquality(expected, response);
        }
        public void ModelFactory_Merchant_NullInput_IsConverted()
        {
            Merchant merchantModel = null;

            ModelFactory modelFactory = new ModelFactory();

            MerchantResponse merchantResponse = modelFactory.ConvertFrom(merchantModel);

            merchantResponse.ShouldBeNull();
        }
        public async Task <IActionResult> GetMerchantByEmailAsync(EmailRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var merchant = await _dataContext.Merchants
                           .Include(o => o.User)
                           .Include(o => o.Products)
                           .ThenInclude(p => p.BusinessType)
                           .Include(o => o.Products)
                           .ThenInclude(p => p.ProductImages)
                           .FirstOrDefaultAsync(o => o.User.Email.ToLower() == request.Email.ToLower());

            if (merchant == null)
            {
                return(NotFound());
            }

            var response = new MerchantResponse
            {
                Id          = merchant.Id,
                FirstName   = merchant.User.FirstName,
                LastName    = merchant.User.LastName,
                Address     = merchant.User.Address,
                Document    = merchant.User.Document,
                Email       = merchant.User.Email,
                PhoneNumber = merchant.User.PhoneNumber,
                Products    = merchant.Products?.Select(p => new ProductResponse
                {
                    Id            = p.Id,
                    ProductName   = p.ProductName,
                    IsAvailable   = p.IsAvailable,
                    Price         = p.Price,
                    Remarks       = p.Remarks,
                    ProductImages = p.ProductImages?.Select(pi => new ProductImageResponse
                    {
                        Id       = pi.Id,
                        ImageUrl = pi.ImageFullPath
                    }).ToList(),
                    BusinessType = p.BusinessType.Name,
                }).ToList()
            };

            return(Ok(response));
        }
 public MerchantResponse ProcessMerchantTransaction(MerchantRequest objRequest)
 {
     try
     {
         objMerchantResponse.MerchantGrid = objclsDashboard.GetMerchantData(objRequest.MerchantTab, objRequest.Sdattime, objRequest.Edattime, objRequest.UserID);
         return(objMerchantResponse);
     }
     catch (Exception)
     {
         return(objMerchantResponse);
     }
     finally
     {
         objMerchantResponse = null;
         objclsDashboard     = null;
     }
 }
        public static MerchantResponse ConvertToMerchantResponse(this Merchant merchant)
        {
            if (merchant == null)
            {
                return(null);
            }

            var merchantRespone = new MerchantResponse
            {
                MerchantId    = merchant.MerchantId,
                FirstName     = merchant.FirstName,
                LastName      = merchant.LastName,
                AccountNumber = merchant.AccountNumber
            };

            return(merchantRespone);
        }
        public Result <Merchant> GetMerchant(long merchantId)
        {
            List <string> validationErrs = ValidateId(merchantId, "parameterMerchantIdInvalid");

            if (validationErrs.Count > 0)
            {
                return(new Result <Merchant>(validationErrs));
            }
            RestRequest request = new RestRequest(GET_MERCHANT_URL, Method.GET);

            request.AddUrlSegment("merchantId", merchantId);
            var responseContent = Execute(request);
            MerchantResponse  merchantResponse = JsonConvert.DeserializeObject <MerchantResponse>(responseContent);
            Result <Merchant> result           = new Result <Merchant>(merchantResponse);

            return(result);
        }
        public Result <Merchant> CreateMerchant(MerchantCreateRequest merchantCreateRequest)
        {
            List <string> validationErrs = ValidateCreate(merchantCreateRequest, new MerchantCreateValidator(), "merchantCreateRequestIsNull");

            if (validationErrs.Count > 0)
            {
                return(new Result <Merchant>(validationErrs));
            }
            RestRequest request      = new RestRequest(CREATE_MERCHANT_URL, Method.POST);
            var         merchantJson = JsonConvert.SerializeObject(merchantCreateRequest);

            request.AddParameter(Constants.CONTENT_TYPE_JSON, merchantJson, ParameterType.RequestBody);
            var responseContent = Execute(request);
            MerchantResponse  merchantResponse = JsonConvert.DeserializeObject <MerchantResponse>(responseContent);
            Result <Merchant> result           = new Result <Merchant>(merchantResponse);

            return(result);
        }
        public void ModelFactory_Merchant_NullContacts_IsConverted()
        {
            Merchant merchantModel = TestData.MerchantModelWithNullContacts;

            ModelFactory modelFactory = new ModelFactory();

            MerchantResponse merchantResponse = modelFactory.ConvertFrom(merchantModel);

            merchantResponse.ShouldNotBeNull();
            merchantResponse.MerchantId.ShouldBe(merchantModel.MerchantId);
            merchantResponse.MerchantName.ShouldBe(merchantModel.MerchantName);
            merchantResponse.EstateId.ShouldBe(merchantModel.EstateId);
            merchantResponse.Addresses.ShouldHaveSingleItem();

            AddressResponse addressResponse = merchantResponse.Addresses.Single();
            addressResponse.AddressId.ShouldBe(merchantModel.Addresses.Single().AddressId);
            addressResponse.AddressLine1.ShouldBe(merchantModel.Addresses.Single().AddressLine1);
            addressResponse.AddressLine2.ShouldBe(merchantModel.Addresses.Single().AddressLine2);
            addressResponse.AddressLine3.ShouldBe(merchantModel.Addresses.Single().AddressLine3);
            addressResponse.AddressLine4.ShouldBe(merchantModel.Addresses.Single().AddressLine4);
            addressResponse.Town.ShouldBe(merchantModel.Addresses.Single().Town);
            addressResponse.Region.ShouldBe(merchantModel.Addresses.Single().Region);
            addressResponse.Country.ShouldBe(merchantModel.Addresses.Single().Country);
            addressResponse.PostalCode.ShouldBe(merchantModel.Addresses.Single().PostalCode);

            merchantResponse.Contacts.ShouldBeNull();

            merchantResponse.Devices.ShouldHaveSingleItem();
            KeyValuePair<Guid, String> device = merchantResponse.Devices.Single();
            device.Key.ShouldBe(merchantModel.Devices.Single().Key);
            device.Value.ShouldBe(merchantModel.Devices.Single().Value);

            merchantResponse.Operators.ShouldHaveSingleItem();
            MerchantOperatorResponse operatorDetails = merchantResponse.Operators.Single();
            operatorDetails.Name.ShouldBe(merchantModel.Operators.Single().Name);
            operatorDetails.OperatorId.ShouldBe(merchantModel.Operators.Single().OperatorId);
            operatorDetails.MerchantNumber.ShouldBe(merchantModel.Operators.Single().MerchantNumber);
            operatorDetails.TerminalNumber.ShouldBe(merchantModel.Operators.Single().TerminalNumber);
        }
        public async Task WhenICreateTheFollowingMerchants(Table table)
        {
            foreach (TableRow tableRow in table.Rows)
            {
                // lookup the estate id based on the name in the table
                EstateDetails estateDetails = this.TestingContext.GetEstateDetails(tableRow);
                String        token         = this.TestingContext.AccessToken;
                if (String.IsNullOrEmpty(estateDetails.AccessToken) == false)
                {
                    token = estateDetails.AccessToken;
                }

                String merchantName = SpecflowTableHelper.GetStringRowValue(tableRow, "MerchantName");
                CreateMerchantRequest createMerchantRequest = new CreateMerchantRequest
                {
                    Name    = merchantName,
                    Contact = new Contact
                    {
                        ContactName  = SpecflowTableHelper.GetStringRowValue(tableRow, "ContactName"),
                        EmailAddress = SpecflowTableHelper.GetStringRowValue(tableRow, "EmailAddress")
                    },
                    Address = new Address
                    {
                        AddressLine1 = SpecflowTableHelper.GetStringRowValue(tableRow, "AddressLine1"),
                        Town         = SpecflowTableHelper.GetStringRowValue(tableRow, "Town"),
                        Region       = SpecflowTableHelper.GetStringRowValue(tableRow, "Region"),
                        Country      = SpecflowTableHelper.GetStringRowValue(tableRow, "Country")
                    }
                };

                CreateMerchantResponse response = await this.TestingContext.DockerHelper.EstateClient
                                                  .CreateMerchant(token, estateDetails.EstateId, createMerchantRequest, CancellationToken.None).ConfigureAwait(false);

                response.ShouldNotBeNull();
                response.EstateId.ShouldBe(estateDetails.EstateId);
                response.MerchantId.ShouldNotBe(Guid.Empty);

                // Cache the merchant id
                estateDetails.AddMerchant(response.MerchantId, merchantName);

                this.TestingContext.Logger.LogInformation($"Merchant {merchantName} created with Id {response.MerchantId} for Estate {estateDetails.EstateName}");
            }

            foreach (TableRow tableRow in table.Rows)
            {
                EstateDetails estateDetails = this.TestingContext.GetEstateDetails(tableRow);

                String merchantName = SpecflowTableHelper.GetStringRowValue(tableRow, "MerchantName");

                Guid merchantId = estateDetails.GetMerchantId(merchantName);

                String token = this.TestingContext.AccessToken;
                if (String.IsNullOrEmpty(estateDetails.AccessToken) == false)
                {
                    token = estateDetails.AccessToken;
                }

                await Retry.For(async() =>
                {
                    MerchantResponse merchant = await this.TestingContext.DockerHelper.EstateClient
                                                .GetMerchant(token, estateDetails.EstateId, merchantId, CancellationToken.None)
                                                .ConfigureAwait(false);

                    merchant.MerchantName.ShouldBe(merchantName);
                });
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="System.NotSupportedException">File Id [{request.FileId}] has no lines added</exception>
        /// <exception cref="NotFoundException">
        /// File Line Number {request.LineNumber} not found in File Id {request.FileId}
        /// or
        /// No file profile found with Id {fileDetails.FileProfileId}
        /// or
        /// Merchant not found with Id {fileDetails.MerchantId} on estate Id {fileDetails.EstateId}
        /// or
        /// No contracts found for Merchant Id {fileDetails.MerchantId} on estate Id {fileDetails.EstateId}
        /// or
        /// No merchant contract for operator Id {fileProfile.OperatorName} found for Merchant Id {merchant.MerchantId}
        /// or
        /// No variable value product found on the merchant contract for operator Id {fileProfile.OperatorName} and Merchant Id {merchant.MerchantId}
        /// </exception>
        public async Task <Unit> Handle(ProcessTransactionForFileLineRequest request,
                                        CancellationToken cancellationToken)
        {
            // Get the file aggregate, this tells us the file profile information
            FileAggregate fileAggregate = await this.FileAggregateRepository.GetLatestVersion(request.FileId, cancellationToken);

            FileDetails fileDetails = fileAggregate.GetFile();

            if (fileDetails.FileLines.Any() == false)
            {
                throw new NotSupportedException($"File Id [{request.FileId}] has no lines added");
            }

            FileLine fileLine = fileDetails.FileLines.SingleOrDefault(f => f.LineNumber == request.LineNumber);

            if (fileLine == null)
            {
                throw new NotFoundException($"File Line Number {request.LineNumber} not found in File Id {request.FileId}");
            }

            if (fileLine.ProcessingResult != ProcessingResult.NotProcessed)
            {
                // Line already processed
                return(new Unit());
            }

            FileProfile fileProfile = await this.FileProcessorManager.GetFileProfile(fileDetails.FileProfileId, cancellationToken);

            if (fileProfile == null)
            {
                throw new NotFoundException($"No file profile found with Id {fileDetails.FileProfileId}");
            }

            // Determine if we need to actually process this file line
            if (this.FileLineCanBeIgnored(fileLine.LineData, fileProfile.FileFormatHandler))
            {
                // Write something to aggregate to say line was explicity ignored
                fileAggregate.RecordFileLineAsIgnored(fileLine.LineNumber);
                await this.FileAggregateRepository.SaveChanges(fileAggregate, cancellationToken);

                return(new Unit());
            }

            // need to now parse the line (based on the file format), this builds the metadata
            Dictionary <String, String> transactionMetadata = this.ParseFileLine(fileLine.LineData, fileProfile.FileFormatHandler);

            if (transactionMetadata == null)
            {
                // Line failed to parse so record this
                fileAggregate.RecordFileLineAsRejected(fileLine.LineNumber, "Invalid Format");
                await this.FileAggregateRepository.SaveChanges(fileAggregate, cancellationToken);

                return(new Unit());
            }

            // Add the file data to the request metadata
            transactionMetadata.Add("FileId", request.FileId.ToString());
            transactionMetadata.Add("FileLineNumber", fileLine.LineNumber.ToString());

            String operatorName = fileProfile.OperatorName;

            if (transactionMetadata.ContainsKey("OperatorName"))
            {
                // extract the value
                operatorName        = transactionMetadata["OperatorName"];
                transactionMetadata = transactionMetadata.Where(x => x.Key != "OperatorName").ToDictionary(x => x.Key, x => x.Value);
            }

            this.TokenResponse = await this.GetToken(cancellationToken);

            Interlocked.Increment(ref FileRequestHandler.TransactionNumber);

            // Get the merchant details
            MerchantResponse merchant = await this.EstateClient.GetMerchant(this.TokenResponse.AccessToken, fileDetails.EstateId, fileDetails.MerchantId, cancellationToken);

            if (merchant == null)
            {
                throw new NotFoundException($"Merchant not found with Id {fileDetails.MerchantId} on estate Id {fileDetails.EstateId}");
            }
            List <ContractResponse> contracts = await this.EstateClient.GetMerchantContracts(this.TokenResponse.AccessToken, fileDetails.EstateId, fileDetails.MerchantId, cancellationToken);

            if (contracts.Any() == false)
            {
                throw new NotFoundException($"No contracts found for Merchant Id {fileDetails.MerchantId} on estate Id {fileDetails.EstateId}");
            }

            ContractResponse?contract = null;

            if (fileProfile.OperatorName == "Voucher")
            {
                contract = contracts.SingleOrDefault(c => c.Description.Contains(operatorName));
            }
            else
            {
                contract = contracts.SingleOrDefault(c => c.OperatorName == operatorName);
            }


            if (contract == null)
            {
                throw new NotFoundException($"No merchant contract for operator Id {operatorName} found for Merchant Id {merchant.MerchantId}");
            }

            ContractProduct?product = contract.Products.SingleOrDefault(p => p.Value == null);  // TODO: Is this enough or should the name be used and stored in file profile??

            if (product == null)
            {
                throw new NotFoundException($"No variable value product found on the merchant contract for operator Id {fileProfile.OperatorName} and Merchant Id {merchant.MerchantId}");
            }

            // Build a transaction request message
            SaleTransactionRequest saleTransactionRequest = new SaleTransactionRequest
            {
                EstateId                      = fileDetails.EstateId,
                MerchantId                    = fileDetails.MerchantId,
                TransactionDateTime           = fileDetails.FileReceivedDateTime,
                TransactionNumber             = FileRequestHandler.TransactionNumber.ToString(),
                TransactionType               = "Sale",
                ContractId                    = contract.ContractId,
                DeviceIdentifier              = merchant.Devices.First().Value,
                OperatorIdentifier            = contract.OperatorName,
                ProductId                     = product.ProductId,
                AdditionalTransactionMetadata = transactionMetadata,
            };

            SerialisedMessage serialisedRequestMessage = new SerialisedMessage
            {
                Metadata = new Dictionary <String, String>
                {
                    { "estate_id", fileDetails.EstateId.ToString() },
                    { "merchant_id", fileDetails.MerchantId.ToString() }
                },
                SerialisedData = JsonConvert.SerializeObject(saleTransactionRequest, new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.All
                })
            };

            Logger.LogInformation(serialisedRequestMessage.SerialisedData);

            // Send request to transaction processor
            SerialisedMessage serialisedResponseMessage = await this.TransactionProcessorClient.PerformTransaction(this.TokenResponse.AccessToken, serialisedRequestMessage, cancellationToken);

            // Get the sale transaction response
            SaleTransactionResponse saleTransactionResponse = JsonConvert.DeserializeObject <SaleTransactionResponse>(serialisedResponseMessage.SerialisedData);

            if (saleTransactionResponse.ResponseCode == "0000")
            {
                // record response against file line in file aggregate
                fileAggregate.RecordFileLineAsSuccessful(request.LineNumber, saleTransactionResponse.TransactionId);
            }
            else
            {
                fileAggregate.RecordFileLineAsFailed(request.LineNumber, saleTransactionResponse.TransactionId, saleTransactionResponse.ResponseCode, saleTransactionResponse.ResponseMessage);
            }

            // Save changes to file aggregate
            // TODO: Add retry round this save (maybe 3 retries)
            await this.FileAggregateRepository.SaveChanges(fileAggregate, cancellationToken);

            return(new Unit());
        }
Exemplo n.º 15
0
        /// <summary>
        /// Converts from.
        /// </summary>
        /// <param name="merchant">The merchant.</param>
        /// <returns></returns>
        public MerchantResponse ConvertFrom(Merchant merchant,
                                            MerchantBalance merchantBalance = null)
        {
            if (merchant == null)
            {
                return(null);
            }

            MerchantResponse merchantResponse = new MerchantResponse
            {
                EstateId     = merchant.EstateId,
                MerchantId   = merchant.MerchantId,
                MerchantName = merchant.MerchantName,
            };

            if (merchant.Addresses != null && merchant.Addresses.Any())
            {
                merchantResponse.Addresses = new List <AddressResponse>();

                merchant.Addresses.ForEach(a => merchantResponse.Addresses.Add(new AddressResponse
                {
                    AddressId    = a.AddressId,
                    Town         = a.Town,
                    Region       = a.Region,
                    PostalCode   = a.PostalCode,
                    Country      = a.Country,
                    AddressLine1 = a.AddressLine1,
                    AddressLine2 = a.AddressLine2,
                    AddressLine3 = a.AddressLine3,
                    AddressLine4 = a.AddressLine4
                }));
            }

            if (merchant.Contacts != null && merchant.Contacts.Any())
            {
                merchantResponse.Contacts = new List <ContactResponse>();

                merchant.Contacts.ForEach(c => merchantResponse.Contacts.Add(new ContactResponse
                {
                    ContactId           = c.ContactId,
                    ContactPhoneNumber  = c.ContactPhoneNumber,
                    ContactEmailAddress = c.ContactEmailAddress,
                    ContactName         = c.ContactName
                }));
            }

            if (merchant.Devices != null && merchant.Devices.Any())
            {
                merchantResponse.Devices = new Dictionary <Guid, String>();

                foreach ((Guid key, String value) in merchant.Devices)
                {
                    merchantResponse.Devices.Add(key, value);
                }
            }

            if (merchant.Operators != null && merchant.Operators.Any())
            {
                merchantResponse.Operators = new List <MerchantOperatorResponse>();

                merchant.Operators.ForEach(a => merchantResponse.Operators.Add(new MerchantOperatorResponse
                {
                    Name           = a.Name,
                    MerchantNumber = a.MerchantNumber,
                    OperatorId     = a.OperatorId,
                    TerminalNumber = a.TerminalNumber
                }));
            }

            // Only include the balance if the dto fed in is not null
            if (merchantBalance != null)
            {
                merchantResponse.AvailableBalance = merchantBalance.AvailableBalance;
                merchantResponse.Balance          = merchantBalance.Balance;
            }

            return(merchantResponse);
        }