Example #1
0
        public ActionResult Create(PurchaseDto dto)
        {
            var result = _purchaseContract.Insert(dto);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="cartItemModel"></param>
        /// <param name="contentItem"></param>
        /// <param name="repository"></param>
        /// <param name="purchase"></param>
        /// <param name="existingPurchase"></param>
        /// <returns>update shopping cart</returns>
        private Purchase AddToCartInternal(ShoppoingCartItemModel cartItemModel, ParseObject contentItem, ParseRepository repository, Purchase existingPurchase, string previosDemoId)
        {
            var currentUser = Session.GetLoggedInUser();
            var isLessson = cartItemModel.ContentItemType.Contains("lesson");
            var isDemo = cartItemModel.ContentItemType.Contains("demo");

            var includingSupport = cartItemModel.ContentItemType.Contains("support");
            var defaultCurrency = repository.FindDefaultCurrency();
            var worldRetriever = new WorldContentTypeRetriver(HttpContext, repository);

            CurrencyDto contentItemCurrency = null;
            CurrencyDto userCurrency = null;
            userCurrency = Task.Run(() => currentUser.GetPointerObject<Currency>("currency")).Result.ConvertToCurrencyDto();

            float contentItemPrice;
            float contentItemSupportPrice;
            string purchaseStatusCode;
            var clips = new List<string>();
            string clipId = "1";
            string bundleId = "";
            string objectId = "";

            if (isLessson)
            {
                var clip = (Clip)contentItem;
                var isAdminOrCurrenctUser = clip.Teacher.ObjectId == currentUser.ObjectId || Session.GetLoggedInUserRoleName() == RoleNames.ADMINISTRATORS;
                clipId = clip.ObjectId;
                contentItemCurrency = clip.Currency.ConvertToCurrencyDto();
                contentItemPrice = clip.Price;
                contentItemSupportPrice = includingSupport ? clip.SupportPrice : 0;
                purchaseStatusCode = isAdminOrCurrenctUser ? PurchaseStatusCodes.LessonIsActive : PurchaseStatusCodes.LessonIsInBaskert;
            }
            else
            {
                var bundle = (Bundle)contentItem;
                bundleId = bundle.ObjectId;
                contentItemCurrency = bundle.Currency.ConvertToCurrencyDto();
                contentItemPrice = bundle.Price;
                contentItemSupportPrice = includingSupport ? bundle.SupportPrice : 0;
                purchaseStatusCode = PurchaseStatusCodes.PackageIsInBasket;
                clips = bundle.ClipsInBundle.Select(x => x.ObjectId).ToList();
            }
            PurchaseDto purchaseDto = null;

            if (isDemo)
            {
                purchaseDto = new PurchaseDto
                {
                    ObjectId = existingPurchase != null ? existingPurchase.ObjectId : null,
                    ClipId = clipId,
                    BundleId = bundleId,
                    ClipKind = ClipPurchaseTypes.Demo,
                    PurchaseStatusCode = PurchaseStatusCodes.DemoOrdered,
                    PurchaseStatusDate = DateTime.Now,
                    UserKey = currentUser.ObjectId,
                    WorldId = worldRetriever.GetWorldContentTypeId()
                };
            }
            else
            {
                if (!string.IsNullOrEmpty(previosDemoId))
                {
                    objectId = previosDemoId;
                }
                if (existingPurchase != null)
                {
                    objectId = existingPurchase.ObjectId;
                }

                purchaseDto = new PurchaseDto
                {
                    ObjectId = objectId,
                    ClipId = clipId,
                    BundleId = bundleId,
                    ClipKind = isLessson ? ClipPurchaseTypes.Lesson : ClipPurchaseTypes.Bundle,
                    UserCurrencyId = currentUser.GetPointerObjectId("currency"),
                    Price = CurrencyConverter.Convert(contentItemPrice, contentItemCurrency, userCurrency),
                    PriceNIS = CurrencyConverter.Convert(contentItemPrice, contentItemCurrency, defaultCurrency),
                    OriginalItemPrice = contentItemPrice,
                    OriginalItemCurrency = contentItemCurrency.ObjectId,
                    PurchaseStatusCode = purchaseStatusCode,
                    PurchaseStatusDate = DateTime.Now,
                    SupportPrice = CurrencyConverter.Convert(contentItemSupportPrice, contentItemCurrency, userCurrency),
                    SupportPriceNIS = CurrencyConverter.Convert(contentItemSupportPrice, contentItemCurrency, defaultCurrency),
                    OriginalSupportPrice = contentItemSupportPrice,
                    UserKey = currentUser.ObjectId,
                    WorldId = worldRetriever.GetWorldContentTypeId(),
                    ClipIds = clips.ToArray(),
                    IncludingSupport = includingSupport
                };
            }

               // repository.AddPurchase(purchaseDto);

            return purchaseDto.ConvertToDomain();
        }
Example #3
0
 public async Task <ActionResult <Purchase> > PostPurchase(PurchaseDto purchase)
 {
     return(await _purchaseServices.PostPurchase(purchase));
 }
        public async Task <PaymentSessionViewModel> PreparePaymentSession(string clientUserName, PurchaseDto purchaseDto)
        {
            var client         = _context.Users.Single(c => c.Username == clientUserName);
            var availableKeys  = LoadAvailableKeys(clientUserName, purchaseDto);
            var paymentSession = new PaymentSession
            {
                Date     = DateTime.Now,
                GameKeys = new List <GameKey>(),
                Client   = client
            };

            for (int i = 0; i < purchaseDto.GameCount; i++)
            {
                AttachKeyToSession(paymentSession, availableKeys[i]);
            }
            _context.PaymentSessions.Add(paymentSession);
            await _context.SaveChangesAsync();

            return(_mapper.Map <PaymentSessionViewModel>(paymentSession));
        }
Example #5
0
        public static string ImportPurchases(VaporStoreDbContext context, string xmlString)
        {
            XDocument document   = XDocument.Parse(xmlString);
            string    dateFormat = @"dd/MM/yyyy HH:mm";

            var elements = document.Root.Elements().ToList();

            StringBuilder builder = new StringBuilder();

            foreach (var element in elements)
            {
                var currentPurchaseDto = new PurchaseDto()
                {
                    Title      = element.Attribute("title").Value,
                    Type       = element.Element("Type").Value,
                    ProductKey = element.Element("Key").Value,
                    Date       = DateTime.ParseExact(element.Element("Date").Value, dateFormat, CultureInfo.InvariantCulture),
                    Card       = element.Element("Card").Value
                };

                PurchaseType currentPurchaseType;

                bool isTypeParseSuccessfull = Enum.TryParse <PurchaseType>(currentPurchaseDto.Type, out currentPurchaseType);

                if (IsValid(currentPurchaseDto) == false || isTypeParseSuccessfull == false)
                {
                    continue;
                }

                Purchase currentPurchase = new Purchase()
                {
                    Date = currentPurchaseDto.Date,
                    Type = currentPurchaseType
                };

                var currentGame = GetObjectFromSet <Game>(x => x.Name == currentPurchaseDto.Title, context);

                if (currentGame == null)
                {
                    continue;
                }

                var currentCard = GetObjectFromSet <Card>(x => x.Number == currentPurchaseDto.Card, context);

                if (currentCard == null)
                {
                    continue;
                }

                currentPurchase.Game       = currentGame;
                currentPurchase.Card       = currentCard;
                currentPurchase.ProductKey = currentPurchaseDto.ProductKey;

                string currentUsernameOfBuyer =
                    GetObjectFromSet <User>(x => x.Cards.Any(z => z.Number == currentCard.Number), context).Username;

                context.Purchases.Add(currentPurchase);
                builder.AppendLine($"Imported {currentGame.Name} for {currentUsernameOfBuyer}");
            }

            context.SaveChanges();

            return(builder.ToString().TrimEnd());
        }
 private void createLinks(PurchaseDto dto)
 {
     dto.Thing  = new LinkDto(rel: "thing", href: $"api/Things/{dto.ThingId}", method: "GET");
     dto.MadeBy = new LinkDto(rel: "user", href: $"api/Users/{dto.MadeById}", method: "GET");
 }
Example #7
0
        public async Task <ActionResult <Purchase> > PurchaseCurrency(PurchaseDto purchaseDto)
        {
            try
            {
                double exchange            = 0;
                double totalAmountPurchase = 0;

                if (purchaseDto == null)
                {
                    _logger.LogError("Purchase object sent from client is null.");
                    return(BadRequest("Purchase object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid purchase object sent from client.");

                    return(BadRequest("Invalid model object"));
                }

                var purchase = new Purchase
                {
                    UserId   = purchaseDto.userId,
                    Amount   = double.Parse(purchaseDto.amount),
                    Currency = purchaseDto.currency.ToLower(),
                    Month    = DateTime.Today.Month,
                    Year     = DateTime.Today.Year
                };

                // valid amount
                if (purchase.Amount <= 0)
                {
                    _logger.LogError("Invalid purchase amount sent from client.");

                    return(NotFound(new NotFoundError("Invalid amount")));
                }

                // check if is a valid currency.
                if (purchase.Currency != "dolar" && purchase.Currency != "real")
                {
                    _logger.LogError("Invalid purchase currency sent from client.");

                    return(NotFound(new NotFoundError("The currency was not found")));
                }

                // get all purchase for this user in this month with this currency.
                var purchaseByMonthList = _purchaseService.GetByUserIdAndMonthAndCurrency(purchase);

                foreach (var purchaseByMonth in purchaseByMonthList)
                {
                    totalAmountPurchase = totalAmountPurchase + purchaseByMonth.Amount;
                }

                // check if exceeds the minimal amount.
                if ((totalAmountPurchase >= 200 && purchase.Currency == "dolar") || (totalAmountPurchase >= 300 && purchase.Currency == "real"))
                {
                    _logger.LogError("Invalid purchase because the user exceeds monthly purchase limit.");

                    return(NotFound(new NotFoundError("The user exceeds monthly purchase limit")));
                }

                var exchangeResponse = await _exchangeController.ExchangeRate(purchase.Currency);

                if (exchangeResponse is OkObjectResult exchangeRate && exchangeRate.Value != null)
                {
                    // get the exchange rate sold.
                    var sold = exchangeRate.Value.GetType().GetProperty("sold").GetValue(exchangeRate.Value).ToString();

                    exchange            = double.Parse(sold);
                    purchase.Amount     = purchase.Amount / exchange;
                    totalAmountPurchase = totalAmountPurchase + purchase.Amount;

                    if ((totalAmountPurchase >= 200 && purchase.Currency == "dolar") || (totalAmountPurchase >= 300 && purchase.Currency == "real"))
                    {
                        _logger.LogError("Invalid purchase because the user exceeds monthly purchase limit.");

                        return(NotFound(new NotFoundError("The user exceeds monthly purchase limit")));
                    }

                    _purchaseService.Create(purchase);

                    _logger.LogInformation($"The creation of a purchase was successfully.");

                    return(CreatedAtRoute("GetPurchase", new { id = purchase.Id }, purchase));
                }

                return(BadRequest(new InternalServerError("The external service don't response")));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Faild Create purchase. Message: {ex.Message}");

                return(BadRequest(new InternalServerError()));
            }
        }