protected void SetupMockHttp(string apiEndPoing, string jsonResponseFile)
 {
     mockHttp
     .When(ApiEndPoints.ApiBaseUrl + apiEndPoing)
     .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse(jsonResponseFile))
     ;
 }
Exemplo n.º 2
0
        public ActionResult ChangeVisibility(int idImage, bool visible)
        {
            var response = new JsonResponseHelper();

            var image = unitOfWork.RepositoryImage.Get(idImage);

            if (image != null)
            {
                var thumbnails = unitOfWork.RepositoryImage.GetThumbnailsFor(idImage);

                image.Visible = visible;
                unitOfWork.RepositoryImage.Update(image);

                if (thumbnails != null)
                {
                    foreach (var thumbnail in thumbnails)
                    {
                        thumbnail.Visible = visible;
                        unitOfWork.RepositoryImage.Update(thumbnail);
                    }
                }

                unitOfWork.Save();

                response.AddNotySuccess($"Obrázek {image.Name} (id: {image.Id}) je nyní {(image.Visible ? "viditelný" : "neviditelný") }");
            }

            return(Json(response.Sections.ToArray()));
        }
Exemplo n.º 3
0
        public ActionResult ChangeState(int idOrder, Order.ORDER_STATE orderState)
        {
            var order = unitOfWork.RepositoryOrder.Get(idOrder);
            var user  = (Administrator)unitOfWork.RepositoryUser.GetUserByEmail(User.Identity.Name);

            order.OrderState = orderState;

            if (orderState == Order.ORDER_STATE.Completed)
            {
                order.Completed = DateTime.Now;
            }

            unitOfWork.RepositoryOrder.Update(order);

            var orderHistory = new OrderHistory()
            {
                Order      = order,
                OrderState = orderState,
                Date       = DateTime.Now,
                ChangedBy  = user,
                Type       = OrderHistory.OrderHistoryTypes.OrderStateChange,
                Message    = $"Objednávka je nyní ve stavu {orderState.ToDescription()}"
            };

            unitOfWork.RepositoryOrderHistory.Add(orderHistory);
            unitOfWork.Save();

            var response = new JsonResponseHelper();

            response.AddNotySuccess($"Objednávka č. {order.Id} je nyní ve stavu '{orderState.ToDescription()}'");

            return(Json(response.Sections.ToArray()));
        }
Exemplo n.º 4
0
        public ActionResult Recount(int id, int amount)
        {
            var response = new JsonResponseHelper();

            var cart = new SessionCart();

            if (amount == 0)
            {
                response.AddNotySuccess($"Položka {cart.Items[id].Product.Name} byla z košíku odstraněn.");
                response.AddJs($"removeProductFromCart({id})");
                cart.Items.RemoveAt(id);
            }
            else if (amount > 0)
            {
                cart.Items[id].Amount = Math.Min(amount, OrderItem.MAX_AMOUNT_OF_PRODUCT);
            }

            response.AddJs($"cartSetAmount({id},{cart.Items[id].Amount})");
            response.AddJs("recountCart()");

            if (!cart.Items.Any())
            {
                response.AddRefresh();
            }

            return(Json(response.Sections.ToArray()));
        }
Exemplo n.º 5
0
        public JsonResult AddDeliveryPayment(string type, string name, int price)
        {
            DeliveryPayment way;

            if (type == nameof(Delivery))
            {
                way = new Delivery();
            }
            else
            {
                way = new Payment();
            }

            way.Price = price;
            way.Name  = name;

            unitOfWork.RepositoryDeliveryPayment.Add(way);
            unitOfWork.Save();

            var result = new JsonResponseHelper();

            result.AddNotySuccess($"Metoda {name} byla vytvořena");
            result.AddJs($"addDeliveryPayment('{type.ToLower()}','{name}','{price:C0}');");
            result.AddJs($"clearForm('{type.ToLower()}');");

            return(Json(result.Sections.ToArray()));
        }
Exemplo n.º 6
0
        public ActionResult ChangeHighlight(int idProduct, bool highlight)
        {
            var product = unitOfWork.RepositoryProduct.Get(idProduct);

            product.Highlighted = highlight;
            unitOfWork.RepositoryProduct.Update(product);

            unitOfWork.Save();

            var response = new JsonResponseHelper();

            response.AddNotySuccess($"Produkt {product.Name} (id: {product.Id}) {(product.Highlighted ? "je" : "není") } zvýrazněn");

            return(Json(response.Sections.ToArray()));
        }
Exemplo n.º 7
0
        public ActionResult ChangeVisibility(int idProduct, bool visible)
        {
            var product = unitOfWork.RepositoryProduct.Get(idProduct);

            product.Visible = visible;
            unitOfWork.RepositoryProduct.Update(product);

            unitOfWork.Save();

            var response = new JsonResponseHelper();

            response.AddNotySuccess($"Produkt {product.Name} (id: {product.Id}) je nyní {(product.Visible ? "viditelný" : "neviditelný") }");

            return(Json(response.Sections.ToArray()));
        }
        public async Task GetLatestAsyncGzipShouldReturnTicketArray()
        {
            mockHttp
            .When(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Latest)
            .Respond("application/gzip", JsonResponseHelper.GetStreamResponse("LatestSuccess.gzip"))
            ;
            var apiClient = new TicketsCacheApiClient(GetTokenFixture(), mockHttp.ToHttpClient(), true, false);

            var tickets = await apiClient.GetLatestAsync();

            tickets.Length.ShouldBe(1);
            var ticket = tickets[0];

            ticket.Value.ShouldBe(1183);
        }
Exemplo n.º 9
0
        public ActionResult ChangeVisibility(int idFile, bool visible)
        {
            var file = unitOfWork.RepositoryFile.Get(idFile);

            file.Visible = visible;
            unitOfWork.RepositoryFile.Update(file);

            unitOfWork.Save();

            var response = new JsonResponseHelper();

            response.AddNotySuccess($"Soubor {file.Name} (id: {file.Id}) je nyní {(file.Visible ? "viditelný" : "neviditelný") }");

            return(Json(response.Sections.ToArray()));
        }
        public async Task GetLatestAsyncShouldContainAllQueryStrings()
        {
            DateTime beginningOfPeriod = new DateTime(2017, 12, 21);
            var      mockHttp          = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Latest)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Currency, "Usd" },
                { QueryParams.Origin, "KBP" },
                { QueryParams.Destination, "BKK" },
                { QueryParams.BeginningOfPeriod, beginningOfPeriod.ToString("yyyy-MM-dd") },
                { QueryParams.PeriodType, "month" },
                { QueryParams.OneWay, "true" },
                { QueryParams.Page, "1" },
                { QueryParams.Limit, "10" },
                { QueryParams.ShowToAffiliates, "false" },
                { QueryParams.Sorting, "route" },
                { QueryParams.TripDuration, "2" },
            })
            .WithHeaders(new Dictionary <string, string>
            {
                { RequestStrings.AccessToken, ApiToken },
                { "Accept", RequestStrings.ApplicationJson }
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("LatestSuccess"))
            ;
            var httpClient = mockHttp.ToHttpClient();
            var apiClient  = new TicketsCacheApiClient(ApiToken, httpClient, false, false);

            var tickets = await apiClient.GetLatestAsync(
                currency : Enums.Currency.Usd,
                originIata : "KBP",
                destinationIata : "BKK",
                beginningOfPeriod : beginningOfPeriod,
                periodTypeMonth : true,
                oneWay : true,
                page : 1,
                limit : 10,
                showToAffiliates : false,
                sorting : Enums.Sorting.Route,
                tripDurationInWeeks : 2
                );

            tickets.ShouldNotBeNull();
            mockHttp.VerifyNoOutstandingExpectation();
        }
Exemplo n.º 11
0
        public async Task GetNearestPlacesMatrixAsyncShouldContainAllQueryStrings()
        {
            DateTime departDate = new DateTime(2017, 12, 21);
            DateTime returnDate = new DateTime(2018, 1, 21);
            var      mockHttp   = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.NearestPlacesMatrix)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Currency, "Usd" },
                { QueryParams.Origin, "KBP" },
                { QueryParams.Destination, "BKK" },
                { QueryParams.ShowToAffiliates, "false" },
                { QueryParams.DepartDate, departDate.ToString("yyyy-MM-dd") },
                { QueryParams.ReturnDate, returnDate.ToString("yyyy-MM-dd") },
                { QueryParams.Distance, "100" },
                { QueryParams.Limit, "10" },
                { QueryParams.Flexibilty, "7" },
            })
            .WithHeaders(new Dictionary <string, string>
            {
                { "X-Access-Token", ApiToken },
                { "Accept", RequestStrings.ApplicationJson }
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("NearestPlacesMatrixSuccess"))
            ;
            var httpClient = mockHttp.ToHttpClient();
            var apiClient  = new TicketsCacheApiClient(ApiToken, httpClient, false, false);

            var tickets = await apiClient.GetNearestPlacesMatrixAsync(
                currency : Enums.Currency.Usd,
                originIata : "KBP",
                destinationIata : "BKK",
                showToAffiliates : false,
                departDate : departDate,
                returnDate : returnDate,
                distance : 100,
                limit : 10,
                flexibility : 7
                );

            tickets.ShouldNotBeNull();
            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task GetLatestAsyncShouldContainTokenQueryString()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Latest)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Token, ApiToken },
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("LatestSuccess"))
            ;
            var apiClient = new TicketsCacheApiClient(ApiToken, mockHttp.ToHttpClient(), false, true);

            await apiClient.GetLatestAsync();

            mockHttp.VerifyNoOutstandingExpectation();
        }
Exemplo n.º 13
0
 public HttpResponseMessage GetConfig()
 {
     try
     {
         UploadFilesExtensionConfiguration cfg = UploadFilesExtensionConfiguration.Current;
         JsonResponseHelper  jsonResp          = new JsonResponseHelper(cfg.Guid, cfg.Folder, cfg.Filedef);
         HttpResponseMessage MsgResponse       = new HttpResponseMessage(HttpStatusCode.OK);
         MsgResponse.Content = new StringContent(JsonConvert.SerializeObject(jsonResp), Encoding.UTF8, "application/json");
         return(MsgResponse);
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
         HttpResponseMessage ErrResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
         ErrResponse.Content = new StringContent(JsonConvert.SerializeObject(ex), Encoding.UTF8, "application/json");
         return(ErrResponse);
     }
 }
Exemplo n.º 14
0
        public async Task GetNearestPlacesMatrixAsyncShouldNotContainQueryStrings()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.NearestPlacesMatrix)
            .WithHeaders(new Dictionary <string, string>
            {
                { "X-Access-Token", ApiToken },
                { "Accept", RequestStrings.ApplicationJson }
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("NearestPlacesMatrixSuccess"))
            ;
            var apiClient = new TicketsCacheApiClient(ApiToken, mockHttp.ToHttpClient(), false, false);

            await apiClient.GetNearestPlacesMatrixAsync();

            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task GetCheapAsyncShouldContainOriginAndDestinationQueryStrings()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Cheap)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Origin, "KBP" },
                { QueryParams.Destination, "BKK" },
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("CheapSuccess"))
            ;
            var httpClient = mockHttp.ToHttpClient();
            var apiClient  = new TicketsCacheApiClient(ApiToken, httpClient, false, false);

            var tickets = await apiClient.GetCheapAsync(originIata : "KBP", destinationIata : "BKK");

            tickets.ShouldNotBeNull();
            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task GetCheapAsyncShouldContainAllQueryStrings()
        {
            DateTime departDate = new DateTime(2017, 12, 21);
            DateTime returnDate = new DateTime(2017, 12, 25);
            var      mockHttp   = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Cheap)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Currency, "Usd" },
                { QueryParams.Origin, "KBP" },
                { QueryParams.Destination, "BKK" },
                { QueryParams.DepartDate, departDate.ToString("yyyy-MM-dd") },
                { QueryParams.ReturnDate, returnDate.ToString("yyyy-MM-dd") },
                { QueryParams.Page, "1" },
            })
            .WithHeaders(new Dictionary <string, string>
            {
                { RequestStrings.AccessToken, ApiToken },
                { "Accept", RequestStrings.ApplicationJson }
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("CheapSuccess"))
            ;
            var httpClient = mockHttp.ToHttpClient();
            var apiClient  = new TicketsCacheApiClient(ApiToken, httpClient, false, false);

            var tickets = await apiClient.GetCheapAsync(
                currency : Enums.Currency.Usd,
                originIata : "KBP",
                destinationIata : "BKK",
                departDate : departDate,
                returnDate : returnDate,
                page : 1
                );

            tickets.ShouldNotBeNull();
            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task GetCheapAsyncShouldContainOriginQueryStrings()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp
            .Expect(ApiEndPoints.ApiBaseUrl + ApiEndPoints.Cheap)
            .WithExactQueryString(new Dictionary <string, string>()
            {
                { QueryParams.Origin, Origin },
            })
            .WithHeaders(new Dictionary <string, string>
            {
                { RequestStrings.AccessToken, ApiToken },
                { "Accept", RequestStrings.ApplicationJson }
            })
            .Respond(RequestStrings.ApplicationJson, JsonResponseHelper.GetJsonResponse("CheapSuccess"))
            ;
            var apiClient = new TicketsCacheApiClient(ApiToken, mockHttp.ToHttpClient(), false, false);

            await apiClient.GetCheapAsync(originIata : Origin);

            mockHttp.VerifyNoOutstandingExpectation();
        }
        public async Task <IActionResult> PurchaseItem(string businessId, string purchasableId, string purchaseAmount)
        {
            _logger.LogTrace($"{businessId} buying {purchasableId}");

            var business = await _context.Business
                           .Include(s => s.BusinessPurchases)
                           .ThenInclude(s => s.Purchase)
                           .SingleOrDefaultAsync(s => s.Id == Convert.ToInt32(businessId));

            var purchasable = (await _context.Purchasables
                               .Include(s => s.Type)
                               .AsNoTracking()
                               .SingleOrDefaultAsync(s => s.Id == Convert.ToInt32(purchasableId) && s.UnlocksAtTotalEarnings <= business.LifeTimeEarnings));

            if (purchasable == null)
            {
                return(NotFound());
            }
            if (Convert.ToInt32(purchaseAmount) == 0)
            {
                Ok(JsonResponseHelper.PurchaseResponseWithPurchase(business, business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null));
            }
            purchasable = PurchasableHelper.AdjustPurchasableCostWithSectorBonus(purchasable, business);

            try
            {
                await _businessHelper.UpdateGainsSinceLastCheckIn(business.Id);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogError(ex, "Concurrency issue while trying to update gains");
                return(StatusCode(500, JsonResponseHelper.PurchaseResponseWithPurchase(business, business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null)));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }

            if (!PurchasableHelper.EnsurePurchaseIsValid(purchasable, business, Convert.ToInt32(purchaseAmount)))
            {
                return(Ok(JsonResponseHelper.PurchaseResponseWithPurchase(business, business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null)));
            }

            business = await _purchasableHelper.ApplyItemStatsToBussiness(purchasable, business, Convert.ToInt32(purchaseAmount));

            business.LastCheckIn = DateTime.UtcNow;

            _context.Business.Update(business);

            var purchaseJson = await _purchasableHelper.PerformSpecialOnPurchaseActions(purchasable, business);

            if (purchasable.IsGlobalPurchase)
            {
                await _purchasableHelper.ApplyGlobalPurchaseBonus(purchasable, business);
            }

            try
            {
                await _context.SaveChangesAsync();

                return(Ok(JsonResponseHelper.PurchaseResponseWithPurchase(business, business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), purchaseJson)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogError(ex, "Concurrency issue while trying to buy item");
                return(StatusCode(500, JsonResponseHelper.PurchaseResponseWithPurchase(business, business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null)));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 19
0
        public async Task <IActionResult> PurchaseItem(int purchasableId, int purchaseCount)
        {
            var user = await GetCurrentEntrepreneur();

            var purchasable = (await _context.Purchasables
                               .Include(s => s.Type)
                               .AsNoTracking()
                               .SingleOrDefaultAsync(s => s.Id == purchasableId && s.UnlocksAtTotalEarnings <= user.Business.LifeTimeEarnings));

            if (purchasableId == 0 || purchaseCount == 0)
            {
                return(StatusCode(500));
            }
            if (purchasable == null)
            {
                return(Ok());
            }
            purchasable = PurchasableHelper.AdjustPurchasableCostWithSectorBonus(purchasable, user.Business);

            try
            {
                await _businessHelper.UpdateGainsSinceLastCheckIn(user.Business.Id);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogError(ex, "Concurrency issue while trying to update gains");
                return(StatusCode(500, JsonResponseHelper.PurchaseResponse(user.Business, user.Business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null)));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }

            if (!PurchasableHelper.EnsurePurchaseIsValid(purchasable, user.Business, purchaseCount))
            {
                return(Ok());
            }

            user.Business = await _purchasableHelper.ApplyItemStatsToBussiness(purchasable, user.Business, purchaseCount);

            user.Business.LastCheckIn = DateTime.UtcNow;

            _context.Entrepreneurs.Update(user);

            var purchaseJson = await _purchasableHelper.PerformSpecialOnPurchaseActions(purchasable, user.Business);

            if (purchasable.IsGlobalPurchase)
            {
                await _purchasableHelper.ApplyGlobalPurchaseBonus(purchasable, user.Business);
            }

            try
            {
                await _context.SaveChangesAsync();

                return(Ok(JsonResponseHelper.PurchaseResponse(user.Business, user.Business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), purchaseJson)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                _logger.LogError(ex, "Concurrency issue while trying to buy item");
                return(StatusCode(500, JsonResponseHelper.PurchaseResponse(user.Business, user.Business.BusinessPurchases.SingleOrDefault(s => s.PurchaseId == purchasable.Id), null)));
            }
            catch (Exception ex)
            {
                return(StatusCode(500));
            }
        }