Ejemplo n.º 1
0
        public async Task BuyLotteryTicketAsync(BuyLotteryTicketDto lotteryTicketDto, UserAndOrganizationDto userOrg)
        {
            var applicationUser = await _userService.GetApplicationUserAsync(userOrg.UserId);

            var lotteryDetails = await GetLotteryDetailsAsync(lotteryTicketDto.LotteryId, userOrg);

            if (lotteryDetails is null || applicationUser is null)
            {
                return;
            }

            if (lotteryTicketDto.Tickets <= 0)
            {
                await AddKudosLogForCheatingAsync(userOrg, lotteryDetails.EntryFee, applicationUser);

                throw new LotteryException("Thanks for trying - you were charged double Kudos for this without getting a ticket.");
            }

            if (applicationUser.RemainingKudos < lotteryDetails.EntryFee * lotteryTicketDto.Tickets)
            {
                throw new LotteryException("User does not have enough kudos for the purchase.");
            }

            if (DateTime.UtcNow > lotteryDetails.EndDate)
            {
                throw new LotteryException("Lottery has already ended.");
            }

            var kudosLog = new AddKudosLogDto
            {
                ReceivingUserIds = new List <string> {
                    userOrg.UserId
                },
                PointsTypeId   = await _kudosService.GetKudosTypeIdAsync(KudosTypeEnum.Minus),
                MultiplyBy     = lotteryTicketDto.Tickets * lotteryDetails.EntryFee,
                Comment        = $"{lotteryTicketDto.Tickets} ticket(s) for lottery {lotteryDetails.Title}",
                UserId         = userOrg.UserId,
                OrganizationId = userOrg.OrganizationId
            };

            await _kudosService.AddLotteryKudosLogAsync(kudosLog, userOrg);

            if (applicationUser.RemainingKudos < 0)
            {
                kudosLog.PointsTypeId = await _kudosService.GetKudosTypeIdAsync(KudosTypeEnum.Refund);

                await _kudosService.AddRefundKudosLogsAsync(new List <AddKudosLogDto> {
                    kudosLog
                });
            }
            else
            {
                for (var i = 0; i < lotteryTicketDto.Tickets; i++)
                {
                    _participantsDbSet.Add(MapNewLotteryParticipant(lotteryTicketDto, userOrg));
                }
            }

            await _uow.SaveChangesAsync(applicationUser.Id);

            await _kudosService.UpdateProfileKudosAsync(applicationUser, userOrg);
        }