예제 #1
0
        public IActionResult GetCustomer(int customerId, int pageIndex = DefaultPageIndex)
        {
            Customer customer = NGContext.Customers.Include(c => c.Accounts).ThenInclude(a => a.Currency).FirstOrDefault(c => c.Id == customerId);

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

            Currency          localCurrency = NGContext.Currencies.Where(c => MathF.Abs((float)(c.Multiplier - 1m)) < 0.0001f).SingleOrDefault();
            CustomerDetailDto customerDto   = AutoMapper.Mapper.Map <CustomerDetailDto>(customer);

            decimal totalBalance = customer.Accounts.Sum(a => a.Balance / a.Currency.Multiplier);

            customerDto.TotalBalance = totalBalance.ToString("c", CultureInfo.CreateSpecificCulture(localCurrency.Culture));

            customerDto.AccountLength = customer.Accounts.Count();

            int lastPage = (int)MathF.Ceiling((float)customerDto.AccountLength / DefaultPageSize);

            if (pageIndex > lastPage)
            {
                pageIndex = lastPage;
            }

            customerDto.Accounts  = PickAccounts(customerId, pageIndex).ToArray();
            customerDto.PageIndex = pageIndex;
            customerDto.PageSize  = DefaultPageSize;
            return(Ok(customerDto));
        }
예제 #2
0
        public async Task <IDataResult <CustomerDetailDto> > GetCustomerDetailByEmailAsync(string email)
        {
            var userResult = await _userService.GetByMailAsync(email);

            if (!userResult.Success)
            {
                return(new ErrorDataResult <CustomerDetailDto>(null, userResult.Message));
            }

            var customer = await _customerDal.GetAsync(p => p.UserId == userResult.Data.Id);

            if (customer == null)
            {
                return(new ErrorDataResult <CustomerDetailDto>(null, Messages.CustomerNotFound));
            }

            CustomerDetailDto customerDetailDto = new CustomerDetailDto()
            {
                Id          = userResult.Data.Id,
                CompanyName = customer.CompanyName,
                Email       = userResult.Data.Email,
                FirstName   = userResult.Data.FirstName,
                LastName    = userResult.Data.LastName,
                Status      = userResult.Data.Status ? "Aktif" : "Pasif"
            };

            return(new SuccessDataResult <CustomerDetailDto>(customerDetailDto, Messages.CustomerDetailBroughth));
        }
예제 #3
0
        public void ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel_EmptyOrderList_ReturnsValidModel()
        {
            // Arrange
            var apiModelConverter = new ApiModelConverter();
            var orderItems        = new List <OrderItem>();
            var customerDetail    = new CustomerDetailDto
            {
                CustomerId   = "ABC123",
                Email        = "*****@*****.**",
                FirstName    = "Mr",
                LastName     = "Blue",
                LastLoggedIn = DateTime.UtcNow.ToString(),
                HouseNumber  = "1",
                Street       = "Street",
                Town         = "Big Town",
                Postcode     = "PO5T C0D3"
            };

            // Act
            var result = apiModelConverter.ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel(orderItems, customerDetail);

            // Assert
            Assert.AreEqual("Mr", result.Customer.FirstName);
            Assert.AreEqual("Blue", result.Customer.LastName);
            Assert.IsNull(result.Order);
        }
예제 #4
0
        public async Task <CustomerDetailDto> GetUserDetailsAsync(string emailAddress)
        {
            CustomerDetailDto customerDetail = null;

            try
            {
                using (var client = new HttpClient())
                {
                    var baseUrl    = _configurationManager.CustomerDetailApiBaseUrl;
                    var uriBuilder = new UriBuilder($"{baseUrl}/GetUserDetails")
                    {
                        Query = $"email={emailAddress}"
                    };

                    // Add API Key to header
                    client.DefaultRequestHeaders.Add(_configurationManager.CustomerDetailApiKeyName,
                                                     _configurationManager.CustomerDetailApiKeyValue);

                    var response = await client.GetAsync(uriBuilder.Uri);

                    customerDetail = await response.Content.ReadAsAsync <CustomerDetailDto>();
                }
            }
            catch (Exception e)
            {
                Trace.TraceError($"Failed to call GetUserDetails. Exception: {e}");
            }

            return(customerDetail);
        }
        public async Task Get_GetByIdCustomerWithOrders_ReturnsOK()
        {
            // ARRANGE
            CustomerDetailDto customer = TestHelpers.CreateCustomerDetailDto();

            _customerReadService.Stub(x => x.GetByIdAsync(customer.Id)).Return(Task.FromResult(customer));
            _subject.MockRequest(HttpMethod.Get, new HttpRouteValueDictionary {
                { "controller", "Customer" }
            });

            // ACT
            HttpResponseMessage result = await _subject.Get(customer.Id);

            // ASSERT
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));

            CustomerDetailModel customerResponse = await result.Content.ReadAsAsync <CustomerDetailModel>();

            Assert.That(customerResponse, Is.Not.Null);
            Assert.That(customerResponse.Id, Is.EqualTo(customer.Id));
            Assert.That(customerResponse.Name, Is.EqualTo(customer.Name));
            Assert.That(customerResponse.Email, Is.EqualTo(customer.Email));
            Assert.That(customerResponse.Orders.Any(), Is.True);

            _customerReadService.AssertWasCalled(x => x.GetByIdAsync(customer.Id));
        }
        public async Task <HttpResponseMessage> Get(string id)
        {
            CustomerDetailDto customer = await _customerReadService.GetByIdAsync(id);

            return(customer != null
                ? Request.CreateResponse(HttpStatusCode.OK, new CustomerDetailModel(customer))
                : Request.CreateResponse(HttpStatusCode.NotFound, new ErrorEnvelope(ErrorResponseConstants.ERROR_CUSTOMER_NOT_FOUND, ErrorResponseConstants.ERROR_CUSTOMER_NOT_FOUND_DESCRIPTION)));
        }
예제 #7
0
 private static void Print(CustomerDetailDto customerDetailDto)
 {
     Console.WriteLine(hyphen);
     Console.WriteLine($"Company Name: {customerDetailDto.CompanyName}");
     Console.WriteLine($"First Name: {customerDetailDto.FirstName}");
     Console.WriteLine($"Last Name: {customerDetailDto.LastName}");
     Console.WriteLine($"Email: {customerDetailDto.Email}");
 }
 public CustomerDetailModel(CustomerDetailDto customerDto)
 {
     Id     = customerDto.Id;
     Name   = customerDto.Name;
     Email  = customerDto.Email;
     Orders = customerDto.Orders.Any()
        ? customerDto.Orders.Select(x => new OrderDetailModel(x)).ToList()
        : new List <OrderDetailModel>();
 }
예제 #9
0
        public void ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel_InvalidCustomerDetailDto()
        {
            // Arrange
            var apiModelConverter            = new ApiModelConverter();
            var orderItems                   = new List <OrderItem>();
            CustomerDetailDto customerDetail = null;

            // Assert
            Assert.ThrowsException <ArgumentNullException>(() => apiModelConverter.ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel(orderItems, customerDetail));
        }
        public IActionResult AddCustomer(CustomerDetailDto customerDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var customerBl = _mapper.Map <CustomerBl>(customerDto);

            customerBl = _customers.AddCustomer(customerBl);

            return(Created(new Uri(Request.GetDisplayUrl() + customerBl.CustomerId),
                           _mapper.Map <CustomerDetailDto>(customerBl)));
        }
예제 #11
0
        public async Task GetByIdAsync_CustomerNotFound_ReturnsNull()
        {
            // ARRANGE
            string customerId = CommonFunctions.GenerateId();

            _customerRepository.Stub(x => x.GetByIdAsync(customerId)).Return(Task.FromResult(null as Customer));

            // ACT
            CustomerDetailDto result = await _subject.GetByIdAsync(customerId);

            // ASSERT
            Assert.That(result, Is.Null);

            _customerRepository.AssertWasCalled(x => x.GetByIdAsync(customerId));
        }
예제 #12
0
        public void ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel_OrderIsAGift_ReturnsProductNameAsGift()
        {
            // Arrange
            var apiModelConverter = new ApiModelConverter();
            var orderItems        = new List <OrderItem>()
            {
                new OrderItem()
                {
                    Order = new Order()
                    {
                        OrderId          = 1,
                        DeliveryExpected = DateTime.Today,
                        OrderDate        = DateTime.Today,
                        ContainsGift     = true
                    },
                    Price    = 1,
                    Quantity = 1,
                    Product  = new Product()
                    {
                        ProductName = "Best product"
                    }
                }
            };

            var customerDetail = new CustomerDetailDto
            {
                CustomerId   = "ABC123",
                Email        = "*****@*****.**",
                FirstName    = "Mr",
                LastName     = "Blue",
                LastLoggedIn = DateTime.UtcNow.ToString(),
                HouseNumber  = "1",
                Street       = "Street",
                Town         = "Big Town",
                Postcode     = "PO5T C0D3"
            };

            // Act
            var result = apiModelConverter.ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel(orderItems, customerDetail);

            // Assert
            Assert.AreEqual("Mr", result.Customer.FirstName);
            Assert.AreEqual("Blue", result.Customer.LastName);
            Assert.IsTrue(result.Order.OrderItems.All(x => x.Product == "Gift"));
        }
예제 #13
0
        public void ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel_DatesAreFormattedCorrectly()
        {
            // Arrange
            var apiModelConverter = new ApiModelConverter();
            var orderItems        = new List <OrderItem>()
            {
                new OrderItem()
                {
                    Order = new Order()
                    {
                        OrderId          = 1,
                        DeliveryExpected = DateTime.Today,
                        OrderDate        = DateTime.Today
                    },
                    Price    = 1,
                    Quantity = 1,
                    Product  = new Product()
                    {
                        ProductName = "Best product"
                    }
                }
            };

            var customerDetail = new CustomerDetailDto
            {
                CustomerId   = "ABC123",
                Email        = "*****@*****.**",
                FirstName    = "Mr",
                LastName     = "Blue",
                LastLoggedIn = DateTime.UtcNow.ToString(),
                HouseNumber  = "1",
                Street       = "Street",
                Town         = "Big Town",
                Postcode     = "PO5T C0D3"
            };

            // Act
            var result = apiModelConverter.ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel(orderItems, customerDetail);

            // Assert
            Assert.AreEqual("Mr", result.Customer.FirstName);
            Assert.AreEqual("Blue", result.Customer.LastName);
            Assert.AreEqual(DateTime.Today.ToString("dd-MMM-yyyy"), result.Order.DeliveryExpected);
            Assert.AreEqual(DateTime.Today.ToString("dd-MMM-yyyy"), result.Order.OrderDate);
        }
예제 #14
0
        public async Task <IActionResult> EditCustomer(CustomerDetailDto customer)
        {
            if (ModelState.IsValid)
            {
                var command = new UpdateCustomerCommand()
                {
                    customer = customer
                };
                var result = await _mediator.Send(command);

                if (result)
                {
                    TempData["changed"] = "Kunden är uppdaterad";
                    return(View(customer));
                }
            }
            return(View(customer));
        }
예제 #15
0
        public async Task GetByIdAsync_CustomerFoundNoOrders_ReturnsCustomer()
        {
            // ARRANGE
            Customer customer = TestHelpers.CreateCustomerWithoutOrders();

            _customerRepository.Stub(x => x.GetByIdAsync(customer.Id)).Return(Task.FromResult(customer));

            // ACT
            CustomerDetailDto result = await _subject.GetByIdAsync(customer.Id);

            // ASSERT
            Assert.That(result, Is.Not.Null);
            Assert.That(result.Id, Is.EqualTo(result.Id));
            Assert.That(result.Email, Is.EqualTo(result.Email));
            Assert.That(result.Name, Is.EqualTo(result.Name));
            Assert.That(result.Orders.Any, Is.False);

            _customerRepository.AssertWasCalled(x => x.GetByIdAsync(customer.Id));
        }
        public IActionResult UpdateCustomer(int id, CustomerDetailDto customerDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var customerBl = _customers.GetCustomer(id);

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

            _mapper.Map(customerDto, customerBl);

            customerBl = _customers.UpdateCustomer(customerBl);

            return(Ok(_mapper.Map <CustomerDetailDto>(customerBl)));
        }
예제 #17
0
 public IDataResult <CustomerDetailDto> GetCustomerDetail(int id)
 {
     using (CarRentalContext context = new CarRentalContext())
     {
         var result = from c in context.Customers
                      join u in context.Users
                      on c.UserId equals u.Id
                      where c.Id == id
                      select new CustomerDetailDto
         {
             Id          = c.Id,
             User        = u.FirstName + " " + u.LastName,
             CompanyName = c.CompanyName
         };
         CustomerDetailDto customer = result.FirstOrDefault();
         if (customer == null)
         {
             return(new ErrorDataResult <CustomerDetailDto>("İstenilen müşteri ögesi bulunamadığı için müşteri detayları listelenemedi."));
         }
         return(new SuccessDataResult <CustomerDetailDto>(customer, "İstenilen müşteri ögesi bulunamadığı için müşteri detayları listelenemedi."));
     }
 }
예제 #18
0
        public void GetCustomerByIdReturnsACustomer()
        {
            // Arrange
            Customer          moqCustomer          = TestHelpers.Entities.GetTestCustomer();
            CustomerDetailDto moqCustomerDetailDto = null;//TestHelpers.Entities.GetTestCustomerDetailDto();
            var customerId = 1;

            var mockCustomerManager = new Mock <ICustomerManager>();

            mockCustomerManager.Setup(x => x.GetCustomerById(It.IsAny <int>())).Returns(moqCustomer);
            var mockILogger = new Mock <ILogger <CustomersController> >();
            var mockIMapper = new Mock <IMapper>();

            var customerControllerTest = new CustomersController(mockCustomerManager.Object, mockILogger.Object, mockIMapper.Object);

            moqCustomer.Id = customerId;

            // Act
            IActionResult result   = customerControllerTest.Get(customerId);
            var           okResult = Assert.IsType <OkObjectResult>(result);

            // Assert - FluentAssertions
            moqCustomerDetailDto.Should().BeEquivalentTo(okResult.Value, options => options.ExcludingNestedObjects());
        }
        public OrderDeliveryModel ConvertOrderItemsAndCustomerInfoToOrderDeliveryModel(List <OrderItem> orderItems, CustomerDetailDto customerDetail)
        {
            if (customerDetail == null)
            {
                throw new ArgumentNullException(nameof(CustomerDetailDto));
            }

            var orderDeliveryModel = new OrderDeliveryModel();

            // Build Delivery Address
            var deliveryAddressArr = new [] { $"{customerDetail.HouseNumber.ToUpper()} {customerDetail.Street}", customerDetail.Town, customerDetail.Postcode };
            var deliveryAddress    = string.Join(", ", deliveryAddressArr.Where(s => !string.IsNullOrEmpty(s)));

            // Build Order Model
            var orderModel = new OrderModel();

            if (orderItems != null && orderItems.Count > 0)
            {
                orderModel.OrderNumber      = orderItems.First().Order.OrderId;
                orderModel.OrderDate        = orderItems.First().Order.OrderDate.ToString("dd-MMM-yyyy");
                orderModel.DeliveryAddress  = deliveryAddress;
                orderModel.DeliveryExpected = orderItems.First().Order.DeliveryExpected.ToString("dd-MMM-yyyy");
                orderModel.OrderItems       = orderItems.Select(orderItem => new OrderItemModel
                {
                    Product   = orderItem.Order.ContainsGift ? "Gift" : orderItem.Product.ProductName,
                    Quantity  = orderItem.Quantity,
                    PriceEach = orderItem.Price
                })
                                              .ToList();

                orderDeliveryModel.Order = orderModel;
            }

            // Add CustomerModel to OrderDeliveryModel and Return
            orderDeliveryModel.Customer = new CustomerModel
            {
                FirstName = customerDetail.FirstName,
                LastName  = customerDetail.LastName
            };

            return(orderDeliveryModel);
        }