Пример #1
0
        public object CreateBet(BetEntity pInput)
        {
            try
            {
                var vUserId = Request.Headers["UserId"].ToString();
                if (string.IsNullOrWhiteSpace(vUserId))
                {
                    return(Constant.Denied);
                }
                var vRoulette = _rouletteDal.Get(pInput.RouletteId);
                if (!Constant.Opened.Equals(vRoulette.State, Constant.IgnoreCase))
                {
                    return(Constant.Denied);
                }
                if (!(pInput.Number >= Constant.MinValue && pInput.Number <= Constant.MaxNumber || Constant.LstColor.Contains(pInput.Color)))
                {
                    return(Constant.Denied);
                }
                if (!(pInput.Amount > Constant.MinValue && pInput.Amount <= Constant.MaxAmount))
                {
                    return(Constant.Denied);
                }
                pInput.UserId = vUserId;
                _betDal.Create(pInput);

                return(Constant.Successful);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(Constant.Denied);
            }
        }
Пример #2
0
        public void PlaceBet(string teams, string formula, double coefficient, int id, double price, DateTime date)
        {
            using (UserDataContext db = new UserDataContext())
            {
                BetEntity bet = new BetEntity();

                bet.Holder = db.Users.Find(id);

                if (bet.Holder.Cash >= price)
                {
                    db.Users.Find(id).Cash -= price;
                }
                else
                {
                    throw new NotEnoughMoneyUserClientException("Недостаточно средств!");
                }


                bet.Date     = date;
                bet.Coeff    = coefficient;
                bet.Teams    = teams;
                bet.Formula  = formula;
                bet.BetPrice = price;


                db.Bets.Add(bet);
                db.SaveChanges();
            }

            MessageBox.Show("Готово!");
        }
Пример #3
0
        public async Task MakeBet(BetEntity bet, decimal balance, int winningNumber)
        {
            var db = _dbProvider.GetDBInstance();

            try
            {
                db.Open();
                db.BeginTransaction();

                await UpdateSpin(bet.SpinId, winningNumber, db);

                await UpdateBalance(bet.UserId, balance, db);

                await CreateBet(bet, db);

                await UpdateJackpot(bet.JackpotAmount, db);

                db.CommitTransaction();
            }
            catch
            {
                db.RollBackTransaction();
            }
            finally
            {
                db.Close();
                db.Dispose();
            }
        }
Пример #4
0
        public async Task <BetEntity> Bet(string idRoulette, string userId, BetModel betRquest)
        {
            string         message  = string.Empty;
            RouletteEntity roulette = await _rouletteRepository.GetById(idRoulette);

            message = _utilities.ValidateRoulette(roulette, isbetting: true);
            if (message != "")
            {
                throw new Exception(message);
            }
            message = _utilities.ValidateBetRequest(betRquest);
            if (message != "")
            {
                throw new Exception(message);
            }
            BetEntity bet = new BetEntity()
            {
                BetDate     = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"),
                UserId      = userId,
                BetModel    = betRquest,
                Winner      = false,
                EarnedMoney = 0,
                Roulette    = roulette
            };
            await _betRepository.InsertDocument(bet);

            return(bet);
        }
Пример #5
0
        private Tuple <bool, string> BetValidation(BetEntity rouletteBet)
        {
            bool   validations = false;
            string msg         = "";

            if (RouletteExistsOrOpen(rouletteBet.RouletteId))
            {
                if (rouletteBet.Color.Trim().ToLower().Equals("rojo") || rouletteBet.Color.Trim().ToLower().Equals("negro"))
                {
                    if (rouletteBet.Number < 0 || rouletteBet.Number > 36)
                    {
                        msg = "Debes apostar del 0 al 36";
                    }
                    else if (rouletteBet.Value <= 0 || rouletteBet.Value > 10000)
                    {
                        msg = "El valor mínimo de la apuesta es de US$1 y el valor máximo de la apuesta es de US$10.000";
                    }
                    else
                    {
                        validations = true;
                    }
                }
                else
                {
                    msg = "Debe agregar color rojo o negro a la apuesta";
                }
            }
            else
            {
                msg = "La ruleta ha apostar no existe o la ruleta no esta abierta para apuestas";
            }

            return(Tuple.Create(validations, msg));
        }
Пример #6
0
        public ServiceMessage Update(BetEditDTO betEditDTO)
        {
            string message = "";
            bool   success = true;

            string   sportName      = betEditDTO.SportName;
            string   tournamentName = betEditDTO.TournamentName;
            DateTime dateOfEvent    = betEditDTO.DateOfEvent;
            List <ParticipantBaseDTO> participants = betEditDTO.EventParticipants;
            string  coefficientDescription         = betEditDTO.CoefficientDescription;
            decimal sum = betEditDTO.Sum;
            string  clientPhoneNumber = betEditDTO.ClientPhoneNumber;

            if (success = ValidateBase(betEditDTO, ref message) && Validate(betEditDTO, ref message))
            {
                try
                {
                    IEnumerable <ParticipantEntity> participantEntities = participants
                                                                          .Select(p => unitOfWork.Participants.Get(p.Name, p.SportName, p.CountryName));

                    EventEntity eventEntity = unitOfWork
                                              .Events
                                              .Get(sportName, tournamentName, dateOfEvent, participantEntities);

                    CoefficientEntity coefficientEntity = unitOfWork
                                                          .Coefficients
                                                          .Get(eventEntity.Id, coefficientDescription);

                    if (coefficientEntity != null)
                    {
                        BetEntity betEntity = unitOfWork.Bets.Get(coefficientEntity.Id, clientPhoneNumber);
                        if (betEntity != null)
                        {
                            betEntity.Sum = sum;

                            unitOfWork.Commit();

                            message = "Edited bet";
                        }
                        else
                        {
                            message = "Such bet not found";
                            success = true;
                        }
                    }
                    else
                    {
                        message = "Such coefficient was not found";
                        success = false;
                    }
                }
                catch (Exception ex)
                {
                    message = ExceptionMessageBuilder.BuildMessage(ex);
                    success = false;
                }
            }

            return(new ServiceMessage(message, success));
        }
Пример #7
0
        /// <summary>
        /// 删除投注订单
        /// </summary>
        /// <param name="aintBetID">投注编号</param>
        /// <param name="astrAccountName">用户账号</param>
        /// <returns></returns>
        public bool DeleteBet(int aintBetID, string astrAccountName)
        {
            BetEntity objBetDelete = mobjBetDAL.GetEntityByID(aintBetID);
            decimal   decIntegral  = objBetDelete.WinIntegral;

            if (decIntegral > 0)
            {
                mobjUserDAL.UpdateIntegral(astrAccountName, decIntegral);
            }

            return(mobjBetDAL.Delete(aintBetID));
        }
Пример #8
0
        /// <summary>
        /// 新增一条用户投注记录
        /// </summary>
        /// <param name="aAddBet"></param>
        /// <returns></returns>
        public bool InsertBet(BetEntity aAddBet)
        {
            bool isSuccess = mobjBetDAL.Insert(aAddBet);

            if (isSuccess)
            {
                mobjUserDAL.UpdateIntegral(aAddBet.AccountName, aAddBet.Integral);
                SuperSocketHandler objSocket = new SuperSocketHandler();
                objSocket.SendBetData(aAddBet.CompetitionID.ToString(), aAddBet);
            }
            return(isSuccess);
        }
Пример #9
0
 private void UpdateEntity(Bet bet, BetEntity entity)
 {
     entity.Answers = bet.State.Answers.Select(x => new AnswerEntity
     {
         BetId      = entity.BetId,
         DateAnswer = x.DateAnswer,
         MemberId   = x.Member.Id.Value,
         IsAccepted = x.IsAccepted
     }).ToList();
     entity.CloseDate = bet.State.CloseDate;
     entity.IsSuccess = bet.State.IsSuccess;
     _dbContext.Set <BetEntity>().Update(entity);
     _domainEventsAccessor.AddDomainEvents(bet.DomainEvents);
 }
Пример #10
0
        private async Task CreateEntity(Bet bet)
        {
            var entity = new BetEntity
            {
                BetId        = bet.State.BetId,
                CreationDate = bet.State.CreationDate,
                Description  = bet.State.Description,
                EndDate      = bet.State.EndDate,
                Coins        = bet.State.Coins,
                CreatorId    = bet.State.Creator.Id.Value
            };
            await _dbContext.Set <BetEntity>().AddAsync(entity);

            _domainEventsAccessor.AddDomainEvents(bet.DomainEvents);
        }
Пример #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="astrRoomID"></param>
        /// <param name="objBet"></param>
        public void  SendBetData(string astrRoomID, BetEntity objBet)
        {
            if (!gobjGameRoom.ContainsKey(astrRoomID))
            {
                return;
            }
            SocketEntity objSocketMessage = new SocketEntity()
            {
                Tag     = "n",
                ToUser  = gobjGameRoom[astrRoomID],
                Message = JsonConvert.SerializeObject(objBet)
            };

            handlerSendMessage(objSocketMessage);
        }
Пример #12
0
        public async Task <IActionResult> BetRulette([FromHeader(Name = "userId")] string UserId, [FromRoute(Name = "idRoulette")] string idRoulette, [FromBody] BetModel request)
        {
            try
            {
                BetEntity betRoulette = await _rouletteService.Bet(idRoulette, UserId, request);

                return(Ok(betRoulette));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                return(Ok(new { state = "Error.", errorMessge = e.Message }));
            }
        }
Пример #13
0
        public bool ValidBetWithRouletteExist(int RouletteId)
        {
            try
            {
                BetEntity objBet = betModel.GetBets().Where(b => b.RouletteId == RouletteId && b.Status == true).FirstOrDefault();
                if (objBet == null)
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #14
0
        public async Task <GenericResponseEntity <string> > StartBet(BetEntity rouletteBet)
        {
            GenericResponseEntity <string> response    = new GenericResponseEntity <string>();
            Tuple <bool, string>           validations = BetValidation(rouletteBet);

            if (validations.Item1)
            {
                rouletteBet.Id = "";
                await _betRepository.InsertDocument(rouletteBet);

                response.Result = "Apuesta realizada con éxito";
            }
            else
            {
                response.Result = validations.Item2;
            }

            return(response);
        }
Пример #15
0
        internal static Bet ToBet(this BetEntity entity)
        {
            var betState = new BetState(entity.BetId,
                                        entity.Creator.ToMember(),
                                        entity.EndDate,
                                        entity.Description,
                                        entity.Coins,
                                        entity.CreationDate,
                                        entity.Answers?.Select(x =>
                                                               new AnswerState(x.Member.ToMember(),
                                                                               x.IsAccepted,
                                                                               x.DateAnswer))
                                        .ToList(),
                                        entity.CloseDate,
                                        entity.IsSuccess);
            var bet = Bet.FromState(betState);

            return(bet);
        }
Пример #16
0
 public void InsertGambling(BetEntity objBet, BetRequest betRequest, string gamblerId)
 {
     try
     {
         List <GamblingEntity> objGamblings = GetGamblings();
         objGamblings.Add(new GamblingEntity
         {
             BetId      = objBet.Id,
             GamblerId  = gamblerId,
             CreditsBet = betRequest.CreditsBet,
             BetType    = betRequest.BetType,
             BetNumber  = betRequest.BetNumber,
             BetColor   = betRequest.BetColor,
             WonBet     = null
         });
         redisCache.SetGamblingToRedis(objGamblings);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #17
0
        public async Task CreateBet(BetEntity bet, Database db)
        {
            var createBetSqlCmd = @"INSERT INTO bets(SpinId,
                                       UserId, BetString, BetAmount,JackpotAmount,
                                       WonAmount, BetStatus, IpAddress, CreatedAt)
                                       VALUES(@SpinId, @UserId, @BetString, @BetAmount, 
                                       @JackpotAmount, @WonAmount, @BetStatus,
                                       @IpAddress, @CreatedAt)";

            await db.ExecuteAsync(createBetSqlCmd, new
            {
                bet.SpinId,
                bet.UserId,
                bet.BetString,
                bet.BetAmount,
                bet.JackpotAmount,
                bet.WonAmount,
                BetStatus = (byte)bet.BetStatus,
                bet.IpAddress,
                CreatedAt = DateTime.Now
            });
        }
Пример #18
0
        public async Task <BetDto> Handle(MakeBetCommand request, CancellationToken cancellationToken)
        {
            var user = await _queryRepository.FindUserById(_currentUserService.CurrentUserId)
                       ?? throw new UserNotFoundException();

            string betString = Convert.ToString(request.BetString);

            CheckBet(betString, request.BetAmount, user.Balance);

            int winningNumber = new Random().Next(0, 36);

            var wonAmount = CheckBets.EstimateWin(betString, winningNumber);

            BetStatus betStatus = wonAmount > 0 ? BetStatus.Won : BetStatus.Lost;

            var jackpotAmount = await _queryRepository.GetCurrentJackpot();

            jackpotAmount += request.BetAmount * 0.01M;
            user.Balance  -= request.BetAmount;

            var bet = new BetEntity
            {
                SpinId        = request.SpinId,
                BetAmount     = request.BetAmount,
                BetString     = betString,
                IpAddress     = _currentUserService.IpAddress,
                JackpotAmount = jackpotAmount,
                UserId        = _currentUserService.CurrentUserId,
                WonAmount     = wonAmount,
                BetStatus     = betStatus,
                CreatedAt     = DateTime.Now
            };
            await _commandRepository.MakeBet(bet, user.Balance, winningNumber);

            return(new BetDto {
                SpinId = bet.SpinId, BetStatus = bet.BetStatus, WonAmount = bet.WonAmount, WinningNumber = winningNumber
            });
        }
Пример #19
0
        public int CloseBet(int rouletteId, CloseBetRequest closeBetRequest)
        {
            try
            {
                if (!rouletteModel.UpdateRoulette(rouletteId, status: false))
                {
                    return(0);
                }
                BetEntity objBet = betModel.GetBets().Where(b => b.RouletteId == rouletteId && b.Status == true).FirstOrDefault();
                betModel.UpdateStatusBet(objBet.Id, status: false);
                betResultModel.InsertBetResult(objBet.Id, closeBetRequest);
                gamblingModel.UpdateGamblingsToSaveResult(objBet.Id, closeBetRequest);
                foreach (GamblingEntity gambling in gamblingModel.GetGamblings().Where(g => g.BetId == objBet.Id && g.WonBet == true).ToList())
                {
                    gamblerModel.UpdateGamblerCredits(gambling.GamblerId, gamblerModel.GetOneGambler(gambling.GamblerId).Credits + (gambling.CreditsBet * 2));
                }

                return(objBet.Id);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #20
0
 public void Remove(BetEntity objIn) => _bet.DeleteOne(x => x.Id == objIn.Id);
Пример #21
0
 public void Update(string id, BetEntity objIn) => _bet.ReplaceOne(x => x.Id == id, objIn);
Пример #22
0
 public BetEntity Create(BetEntity pObject)
 {
     _bet.InsertOne(pObject);
     return(pObject);
 }
Пример #23
0
        public async Task <ActionResult <Bet> > CreateBet([FromHeader(Name = "IdUser")] string UserId, [FromBody] BetEntity betEntity)
        {
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                try
                {
                    Bet bet = new Bet
                    {
                        IdRoulette = betEntity.IdRoulette,
                        Money      = betEntity.Money,
                        Position   = betEntity.Position,
                        Color      = betEntity.Color
                    };
                    await _betrepository.CreateBet(bet, UserId);

                    return(Ok(bet));
                }
                catch (Exception ex)
                {
                    return(BadRequest(new { error = ex.Message, code = "Error al crear la apuesta" }));
                }
            }
        }
Пример #24
0
 public async Task <ActionResult <GenericResponseEntity <string> > > StartBet(BetEntity rouletteBet)
 {
     return(Ok(await _betsBL.StartBet(rouletteBet)));
 }
Пример #25
0
        public ServiceMessage Create(BetCreateDTO betCreateDTO)
        {
            string message = "";
            bool   success = true;

            string   sportName      = betCreateDTO.SportName;
            string   tournamentName = betCreateDTO.TournamentName;
            DateTime dateOfEvent    = betCreateDTO.DateOfEvent;
            List <ParticipantBaseDTO> participants = betCreateDTO.EventParticipants;
            string  coefficientDescription         = betCreateDTO.CoefficientDescription;
            decimal sum = betCreateDTO.Sum;
            string  clientPhoneNumber    = betCreateDTO.ClientPhoneNumber;
            string  bookmakerPhoneNumber = betCreateDTO.BookmakerPhoneNumber;

            if (success = ValidateBase(betCreateDTO, ref message) && Validate(betCreateDTO, ref message))
            {
                try
                {
                    IEnumerable <ParticipantEntity> participantEntities = participants
                                                                          .Select(p => unitOfWork.Participants.Get(p.Name, p.SportName, p.CountryName));

                    EventEntity eventEntity = unitOfWork
                                              .Events
                                              .Get(sportName, tournamentName, dateOfEvent, participantEntities);

                    CoefficientEntity coefficientEntity = unitOfWork
                                                          .Coefficients
                                                          .Get(eventEntity.Id, coefficientDescription);

                    if (coefficientEntity != null)
                    {
                        bool exists = unitOfWork.Bets.Exists(coefficientEntity.Id, clientPhoneNumber);
                        if (!exists)
                        {
                            ClientEntity clientEntity = unitOfWork
                                                        .Clients
                                                        .Get(clientPhoneNumber);

                            BookmakerEntity bookmakerEntity = unitOfWork
                                                              .Bookmakers
                                                              .Get(bookmakerPhoneNumber);

                            BetEntity betEntity = new BetEntity
                            {
                                ClientId         = clientEntity.Id,
                                BookmakerId      = bookmakerEntity.Id,
                                CoefficientId    = coefficientEntity.Id,
                                RegistrationDate = DateTime.Now,
                                Sum = sum
                            };

                            unitOfWork.Bets.Add(betEntity);
                            unitOfWork.Commit();

                            message = "Created new bet";
                        }
                        else
                        {
                            message = "Such bet already exists";
                            success = false;
                        }
                    }
                    else
                    {
                        message = "Such coefficient was not found";
                        success = false;
                    }
                }
                catch (Exception ex)
                {
                    message = ExceptionMessageBuilder.BuildMessage(ex);
                    success = false;
                }
            }

            return(new ServiceMessage(message, success));
        }