示例#1
0
        //Method serves two
        public ActionResult ConfirmBuy(string symbol)
        {
            BuyModel        model    = null;
            List <Listings> listings = null;

            string[] temp = symbol.Split(',');

            if (temp.Count() < 2) // means it has come from navbar request
            {
                DataSerializer <string> .GetSingleListings(ref listings, symbol);

                foreach (var company in listings)
                {
                    model               = new BuyModel();
                    model.Symbol        = company.Symbol;
                    model.Open          = company.Open;
                    model.PurchasePrice = company.Close;
                    model.CompanyName   = company.CompanyName;
                    model.Change        = company.Close - company.Open;
                }
            }
            else // Has come from a Portfolio request
            {
                model               = new BuyModel();
                model.Symbol        = temp[0];
                model.Open          = Convert.ToDecimal(temp[1]);
                model.PurchasePrice = Convert.ToDecimal(temp[2]);
                model.Change        = Convert.ToDecimal(temp[3]);
                model.CompanyName   = temp[4];
            }
            return(View(model));
        }
示例#2
0
        public BuyModel GetInvestment(int stockId, int gameId, string username)
        {
            BuyModel buyModel = new BuyModel();

            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    SqlCommand cmd = new SqlCommand(@"SELECT buy_table.id AS id, users_id, ticker, stock_at_buy_id, game_id, initial_shares_purchased, shares_currently_owned, amount_per_share, time_purchased FROM buy_table 
JOIN users ON users.id = buy_table.users_id
JOIN company ON stock_at_buy_id = company.stock_id
WHERE stock_at_buy_id = @stockId AND buy_table.game_id = @gameId AND users.username = @username", conn);
                    cmd.Parameters.AddWithValue("@stockId", stockId);
                    cmd.Parameters.AddWithValue("@gameId", gameId);
                    cmd.Parameters.AddWithValue("@username", username);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    if (rdr.Read())
                    {
                        buyModel = BuyModelHelper(rdr);
                    }
                }
            }
            catch
            {
                throw;
            }
            return(buyModel);
        }
示例#3
0
        // Buy product with productid
        public ActionResult Buy(string ProductID, int Count, bool FromBasket)
        {
            // If haven't login => login and come back
            if (Session["UserID"] == null)
            {
                return(RedirectToAction("Login", "Users", new { @returnUrl = Request.Url.OriginalString }));
            }

            string  userid  = Session["UserID"].ToString();
            User    user    = DataProvider.Instance.DataBase.Users.First(x => x.Id == userid);
            Product product = DataProvider.Instance.DataBase.Products.Where(x => x.Id == ProductID).SingleOrDefault();

            if (product == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            BuyModel model = new BuyModel()
            {
                ProductID          = ProductID,
                Count              = Count,
                FullName           = user.FullName,
                ProductDisplayName = product.DisplayName,
                ProductPrice       = product.Price.Value,
                FromBasket         = FromBasket,
            };

            ViewBag.Bought = null;
            return(View(model));
        }
示例#4
0
        public async Task <ActionResult> Buy(BuyModel model)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    client.BaseAddress = new Uri("https://cloud-sse.iexapis.com");
                    var response = await client.GetAsync($"/stable/stock/{model.Symbol}/quote?token=pk_f7b30f305a8c4aef8eaec49711a8344e");

                    response.EnsureSuccessStatusCode();

                    var stringResult = await response.Content.ReadAsStringAsync();

                    var    rawShare = JsonConvert.DeserializeObject <Bought>(stringResult);
                    string userId   = User.Claims.First(c => c.Type == "Id").Value;
                    var    user     = db.ApplicationUsers.Where(au => au.Id == userId).ToList();

                    double        total  = 0;
                    List <Bought> shares = db.Boughts.Where(s => s.AspNetUserId == userId).Where(s => s.IsOwned == true).ToList();
                    foreach (Bought item in shares)
                    {
                        total += (item.latestPrice * item.NumOfShare);
                    }

                    double cash = user[0].Fund - total;

                    double cost = rawShare.latestPrice * model.Share;

                    if (cash >= cost)
                    {
                        DateTime date = DateTime.Now;

                        Bought share = new Bought
                        {
                            TransactionType = "Buy",
                            DateAndTime     = date,
                            Symbol          = model.Symbol.ToUpper(),
                            companyName     = rawShare.companyName,
                            latestPrice     = rawShare.latestPrice,
                            NumOfShare      = model.Share,
                            IsOwned         = true,
                            AspNetUserId    = userId
                        };


                        db.Boughts.Add(share);
                        await db.SaveChangesAsync();

                        string message = "Bought";
                        return(Ok(new { message }));
                    }
                    string errorMessage = "Failed. Total cost exceeds your available cash.";
                    return(BadRequest(new { errorMessage }));
                }
                catch (HttpRequestException httpRequestException)
                {
                    return(BadRequest(new { httpRequestException.Message }));
                }
            }
        }
示例#5
0
        public List <BuyModel> GetCurrentInvestments(string username, int gameId)
        {
            try
            {
                List <BuyModel> investments = new List <BuyModel>();
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();
                    const string QUERY = @"SELECT * FROM buy_table
JOIN users ON buy_table.users_id = users.id
JOIN company ON buy_table.stock_at_buy_id = company.stock_id
WHERE game_id = @gameId AND username = @username";
                    SqlCommand   cmd   = new SqlCommand(QUERY, conn);
                    cmd.Parameters.AddWithValue("@gameId", gameId);
                    cmd.Parameters.AddWithValue("@username", username);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    while (rdr.Read())
                    {
                        BuyModel investment = ReadToBuyModel(rdr);
                        investments.Add(investment);
                    }
                }
                return(investments);
            }
            catch
            {
                throw;
            }
        }
示例#6
0
        public BuyPage()
        {
            var vm = new BuyModel();

            this.BindingContext = vm;
            InitializeComponent();
        }
示例#7
0
        private static List <BuyModel> ToModel(List <BuyEntity> buyEntityList)
        {
            List <BuyModel> buyModelList = new List <BuyModel>();

            foreach (var buyEntity in buyEntityList)
            {
                if (string.IsNullOrEmpty(buyEntity.Id))
                {
                    continue;
                }

                BuyModel buyModel = new BuyModel();

                buyModel.Id                 = buyEntity.Id;
                buyModel.ProductNo          = buyEntity.ProductNo;
                buyModel.BuyContractNo      = buyEntity.BuyContractNo;
                buyModel.BianHao            = buyEntity.BianHao;
                buyModel.XiaoFangMinCheng   = buyEntity.XiaoFangMinCheng;
                buyModel.ProductName        = buyEntity.ProductName;
                buyModel.ZuBie              = buyEntity.ZuBie;
                buyModel.ShouPiaoHaoMa      = buyEntity.BillNo;
                buyModel.FaPiaoJinE         = buyEntity.BillMoney;
                buyModel.BuHanShuiJinE      = buyEntity.WithoutTaxMoney;
                buyModel.TaxMoney           = buyEntity.TaxMoney;
                buyModel.ReceiveTicketCount = buyEntity.ReceiveTicketCount;

                buyModelList.Add(buyModel);
            }

            return(buyModelList);
        }
示例#8
0
        public ActionResult Buy(BuyModel model)
        {
            if (model.Quantity < 1)
            {
                TempData["BuyException"] = "Buying 0 stocks... Please try again";
                return(RedirectToAction("ConfirmBuy", new { symbol = model.Symbol }));
            }

            decimal transactionCost = (decimal)TransactionCost.BuyCost * (model.Quantity * model.PurchasePrice);

            string[]        temp       = model.Symbol.Split(',');
            SailiRepository repository = new SailiRepository();
            Buy             buy        = new Buy();

            buy.TradeDate         = DateTime.Now;
            buy.TickerSymbol      = temp[0];
            buy.Quantity          = model.Quantity;
            buy.PurchasePrice     = model.PurchasePrice;
            buy.TransactionAmount = model.Quantity * model.PurchasePrice + transactionCost;
            buy.TransactionCost   = transactionCost;
            buy = repository.Finalizebuy(buy, User.Identity.GetUserId());

            Owner owner = repository.GetOwner(User.Identity.GetUserId());

            TraderAccount trader = repository.GetTrader(owner.OwnerID);

            return(RedirectToAction("Details", "TraderAccount", new
            {
                TradingAccountID = trader.TradingAccountID
            }));
        }
示例#9
0
        public IActionResult ChangeOwnership([FromBody] BuyModel buyModel)
        {
            if (buyModel.BuyerId == 0 || buyModel.Quantity == 0 || buyModel.SellerId == 0 || string.IsNullOrWhiteSpace(buyModel.TickerSymbol))
            {
                Response.StatusCode = 400;
                var insufficientParametersGiven = "Insufficient parameters given";
                Console.Out.WriteLine(insufficientParametersGiven);
                return(Json(new { errorMessage = insufficientParametersGiven }));
            }

            var shares = _context.Shares.Where(share => share.Owner == buyModel.SellerId && share.TickerSymbol == buyModel.TickerSymbol);

            if (shares.Count() < buyModel.Quantity)
            {
                var insufficientSharesOwned = "Insufficient shares owned";
                Console.Out.WriteLine(insufficientSharesOwned);
                return(Json(new { errorMessage = insufficientSharesOwned }));
            }

            var sharesToBeSold = shares.Take(buyModel.Quantity);

            foreach (var share in sharesToBeSold)
            {
                share.Owner = buyModel.BuyerId;
            }

            _context.Shares.UpdateRange(sharesToBeSold);
            _context.SaveChanges();

            var sharesSold = "Shares sold";

            Console.Out.WriteLine(sharesSold);
            return(Json(new { Message = sharesSold }));
        }
示例#10
0
        public ActionResult Buy()
        {
            if (ısLogon())
            {
                var currentId = CurrentUserId();
                IQueryable <DB.Orders> orders;
                if (((int)CurrentUser().MemberType) > 8)
                {
                    orders = context.Orders.Where(x => x.Status == "OB");
                }
                else
                {
                    orders = context.Orders.Where(x => x.Member_Id == currentId);
                }

                List <Models.i.BuyModel> model = new List <BuyModel>();
                foreach (var item in orders)
                {
                    var byModel = new BuyModel();
                    byModel.TotelPrice  = item.OrderDetails.Sum(y => y.Price);
                    byModel.OrderName   = string.Join(", ", item.OrderDetails.Select(y => y.Products.Name + "(" + y.Quantity + ")"));
                    byModel.OrderStatus = item.Status;
                    byModel.OrderId     = item.Id.ToString();
                    byModel.Member      = item.Members;
                    model.Add(byModel);
                }

                return(View(model));
            }
            else
            {
                return(RedirectToAction("Login", "Account"));
            }
        }
示例#11
0
        public async Task <IActionResult> PutBuyModel([FromRoute] int id, [FromBody] BuyModel buyModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != buyModel.BuyId)
            {
                return(BadRequest());
            }

            _context.Entry(buyModel).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BuyModelExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
示例#12
0
        public IActionResult TakeOffer([FromBody] BuyModel buyModel)
        {
            var results = DataContext.GetTable <FilesAndOffers>()
                          .Where(offer => offer.DecryptedFileHash == buyModel.DecryptedFileHash)
                          .Set(offer => offer.BuyerAddressHash, buyModel.BuyerAddressHash)
                          .Set(offer => offer.Open, false)
                          .Update();

            return(Ok("OK"));
        }
示例#13
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public virtual ActionResult Index(BuyModel model)
 {
     model.IsGenerate = false;
     FillBuyModel(model);
     Ioc.Resolve <IOrderApplicationService>().Create(model);
     if (model.PayTypes != null)
     {
         model.PayTypes = model.PayTypes.Where(it => it.Tag == "All" || it.Tag == "Mobile").ToList();
     }
     return(View("Index", model));
 }
        public Task <BinaryOptionsResult> BuyBinaryAsync(BuyModel buyModel)
        {
            OnBuy?.Invoke(buyModel);

            return(WsClient?.BuyBinaryAsync(
                       buyModel.Pair,
                       buyModel.Size,
                       buyModel.Direction,
                       buyModel.Expiration,
                       Profile.BalanceId));
        }
示例#15
0
        public async Task <IActionResult> PostBuyModel([FromBody] BuyModel buyModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.BuyListings.Add(buyModel);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetBuyModel", new { id = buyModel.BuyId }, buyModel));
        }
示例#16
0
        public ActionResult Homes(BuyModel Buy)
        {
            if (ModelState.IsValid)
            {
                BuyManager obj = new BuyManager();
                int        a   = obj.Homes(Buy);
                return(RedirectToAction("ViewBuy", "Buy"));
            }

            else
            {
                ViewBag.Message = "ChooSe FiLters properLy";
                return(View());
            }
        }
示例#17
0
        private BuyModel BuyModelHelper(SqlDataReader rdr)
        {
            BuyModel newBuy = new BuyModel();

            newBuy.BuyId                  = Convert.ToInt32(rdr["id"]);
            newBuy.UsersId                = Convert.ToInt32(rdr["users_id"]);
            newBuy.GameId                 = Convert.ToInt32(rdr["game_id"]);
            newBuy.StockId                = Convert.ToInt32(rdr["stock_at_buy_id"]);
            newBuy.CompanyTicker          = Convert.ToString(rdr["ticker"]);
            newBuy.InitialSharesPurchased = Convert.ToDouble(rdr["initial_shares_purchased"]);
            newBuy.SharesCurrentlyOwned   = Convert.ToDouble(rdr["shares_currently_owned"]);
            newBuy.AmountPerShare         = Convert.ToDecimal(rdr["amount_per_share"]);
            newBuy.BuyTimeTicks           = Convert.ToInt64(rdr["time_purchased"]);
            return(newBuy);
        }
        public ActionResult <RealEstate> BuyHouse([FromRoute] int id, [FromBody] BuyModel buy)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var house = _context.RealEstate.Find(id);

            if (house == null)
            {
                return(BadRequest());
            }
            house.BuyDate = DateTime.Now;
            _context.SaveChanges();
            return(Ok(house));
        }
示例#19
0
        /// <summary>
        /// Step 2. 在商务报表中查找符合条件的"抵消前期暂估"
        /// </summary>
        /// <param name="buyModel"></param>
        /// <param name="mappingModelList"></param>
        private static void Step2_PromotionDiXiaoQianQiZanGu(BuyModel buyModel, List <MappingModel> mappingModelList)
        {
            //在商务报表中查找货号
            var mappingModelList_Buy  = mappingModelList.Where(v => v.ProductNo.Equals(buyModel.ProductNo) && v.MaiMai == 2).ToList();
            var mappingModelList_Sell = mappingModelList.Where(v => v.ProductNo.Equals(buyModel.ProductNo) && v.MaiMai == 1 && v.FaPiaoShiJian != DateTime.MinValue && !string.IsNullOrEmpty(v.FaPiaoHaoMa)).ToList();

            var buyTotalCount  = mappingModelList_Buy.Sum(v => v.KaiChuShouDaoFaPiaoDunShu);
            var sellTotalCount = mappingModelList_Sell.Sum(v => v.KaiChuShouDaoFaPiaoDunShu);

            if (buyTotalCount == sellTotalCount)
            {
                buyModel.SetSellMode(BuyModelSaleMode.DiXiaoQianQiZanGu);
                buyModel.RelativeBusinessIds.AddRange(mappingModelList_Buy.Select(v => v.Id));
                buyModel.RelativeBusinessIds.AddRange(mappingModelList_Sell.Select(v => v.Id));
                buyModel.RelativeBusinessIds.RemoveAll(v => v == buyModel.Id);
            }
        }
        private async Task FollowerBuyAsync(BuyModel buyModel)
        {
            if (Followers is null)
            {
                return;
            }

            foreach (var follower in Followers.Values)
            {
                if (!follower.IsConnected)
                {
                    continue;
                }

                await follower.BuyBinaryAsync(buyModel);
            }
        }
示例#21
0
        /*public static bool [] array1 = new bool[4];*/

        /*public int Homes(BuyModel Buy)
         * {
         *  string Query = "insert into dbo.Practice(City, [Location], PropertyType, PriceRange, AreaInSqYd, Bedrooms, TVLounge, OutsideGarden, WestOpen, Corner) values ('" + Buy.City + "','" + Buy.Location + "','" + Buy.PropertyType + "','" + Buy.PriceRange + "','" + Buy.AreaInSqYd + "','" + Buy.Bedrooms + "','" + Buy.TVLounge + "','" + Buy.OutsideGarden + "','" + Buy.WestOpen + "','" + Buy.Corner + "')";
         *  SqlCommand cmd = new SqlCommand(Query, Con);
         *  Con.Open();
         *  int a = cmd.ExecuteNonQuery();
         *  Con.Close();
         *  return a;
         * }*/
        public int Homes(BuyModel Buy)
        {
            int a = 0;

            array[0]  = Buy.City;
            array[1]  = Buy.Location;
            array[2]  = Buy.PropertyType;
            array[3]  = Convert.ToString(Buy.MinPriceRange);
            array[4]  = Convert.ToString(Buy.MaxPriceRange);
            array[5]  = Buy.AreaInSqYd;
            array[6]  = Buy.Bedrooms;
            array[7]  = Convert.ToString(Buy.TVLounge);
            array[8]  = Convert.ToString(Buy.OutsideGarden);
            array[9]  = Convert.ToString(Buy.WestOpen);
            array[10] = Convert.ToString(Buy.Corner);
            return(a);
        }
    private void Awake()
    {
        if (Instance != null)
        {
            Debug.LogWarning("More than one instance of ShopView found.");
            return;
        }

        Instance = this;

        MoneyCount = _money;

        shopModel      = new BuyModel(_priceModifier, _weaponCountShop, _armorCountShop, _potionCountShop);
        inventoryModel = new SellModel(_priceModifierInventory, _weaponCountInventory, _armorCountInventory, _potionCountInventory);

        shopController      = gameObject.AddComponent <MouseController>().Initialize(shopModel);//Set the default controller to be the mouse controller
        inventoryController = gameObject.AddComponent <MouseController>().Initialize(inventoryModel);
    }
        public HttpResponseMessage SellProduct([FromBody] BuyModel buy)
        {
            if (RequestContext.Principal.IsAdmin())
            {
                return(Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, "Sell is not allowed to admin"));
            }

            int userId = RequestContext.Principal.Identity.GetUserId <int>();

            try
            {
                _goodsService.SellCharacterProduct(userId, buy.CharId, buy.ProdId);
                return(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
            }
            catch (System.Exception exc)
            {
                return(Request.CreateResponse(System.Net.HttpStatusCode.BadRequest, exc.Message));
            }
        }
示例#24
0
        public ActionResult RandomGame(BuyModel model)
        {
            Game game = null;

            using (var context = new ApplicationContext())
            {
                var user = context.Users.FirstOrDefault(u => u._Login == model.UserName);
                var rnd  = new Random();
                do
                {
                    var id = rnd.Next(1, context.Games.Count());
                    game = context.Games.FirstOrDefault(g => g._Id == id);
                } while (game == null);

                if (!user._Games.Contains(game))
                {
                    user._Games.Add(game);
                    context.SaveChanges();
                }
            }

            var message = new MailMessage();

            message.To.Add(model.Email);
            message.Subject = "MongoKeys.com";
            var key = GenerateKey();

            message.Body = "Спасибо за покупку " + model.UserName + ", вы выйграли " + game._Name + ", вот ваш ключ " +
                           key + ".";
            var smtp = new SmtpClient();

            try
            {
                smtp.Send(message);
            }
            catch (Exception)
            {
                return(RedirectToAction("ThankForPurchase", "Home"));
            }

            return(RedirectToAction("ThankForPurchase", "Home"));
        }
示例#25
0
        public ActionResult BuyGame(BuyModel model)
        {
            Game game = null;

            using (var context = new ApplicationContext())
            {
                var user = context.Users.FirstOrDefault(u => u._Login == model.UserName);
                game = context.Games.FirstOrDefault(g => g._Id == model.GameId);
                if (!user._Games.Contains(game))
                {
                    user._Games.Add(game);
                }
                if (!game._Users.Contains(user))
                {
                    game._Users.Add(user);
                }
                context.SaveChanges();
            }

            var message = new MailMessage();

            message.To.Add(model.Email);
            message.Subject = "MongoKeys.com";
            var key = GenerateKey();

            message.Body = "Благодарим за приобретение игры " + game._Name + " " + model.UserName + ", вот ваш ключ " +
                           key + ".";
            var smtp = new SmtpClient();

            try
            {
                smtp.Send(message);
            }
            catch (Exception)
            {
                return(RedirectToAction("ThankForPurchase", "Home"));
            }

            return(RedirectToAction("ThankForPurchase", "Home"));
        }
示例#26
0
 public ActionResult <BuyModel> BuyStock(BuyModel buyModel)
 {
     try
     {
         if (buyModel.InitialSharesPurchased < 0)
         {
             return(Forbid());
         }
         int id = buySellDAO.GetUserId(Username);
         buyModel.UsersId = id;
         BuyModel returnModel = buySellDAO.BuyStock(buyModel);
         if (returnModel == null)
         {
             return(Forbid());
         }
         return(Created($"api/stocks/buy/{returnModel.CompanyTicker}", returnModel));
     }
     catch (Exception ex)
     {
         return(StatusCode(500, ex.Message));
     }
 }
示例#27
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual ActionResult Buy(BuyModel model)
        {
            if (model == null)
            {
                return(Content("false"));
            }
            model.IsGenerate = true;
            FillBuyModel(model);
            Ioc.Resolve <IOrderApplicationService>().Create(model);
            var result = new Dictionary <string, object>
            {
                { "Status", model.IsSaveSuccess.ToString().ToLower() }
            };

            if (model.IsSaveSuccess)
            {
                result.Add("Message", string.Join(",", model.Orders.Select(it => it.Order.Id).ToArray()));
            }
            else
            {
                result.Add("Message", model.Errors?.FirstOrDefault()?.Message);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
示例#28
0
        public IActionResult SetBuy([FromBody] BuyModel purchaseOrder)
        {
            var             email = HttpContext.User.Claims.ElementAt(0).Value;
            var             id    = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var             stock = _context.UserStocks.Where(u => u.Id == id).FirstOrDefault(u => u.Symbol == purchaseOrder.Symbol);
            ApplicationUser user  = _context.Users.Where(u => u.Id == id).FirstOrDefault(u => u.Cash >= 0);

            if (user.Cash >= purchaseOrder.CurrentPrice * purchaseOrder.Count)
            {
                if (stock == null)
                {
                    try
                    {
                        _context.UserStocks.Add(new Models.UserStock
                        {
                            Id             = id,
                            Symbol         = purchaseOrder.Symbol,
                            IsWatched      = true,
                            PurchasedCount = purchaseOrder.Count
                        });
                        user.Cash -= (purchaseOrder.Count * purchaseOrder.CurrentPrice);
                        _context.SaveChanges();

                        return(Ok(new
                        {
                            CurrentCash = user.Cash,
                            Symbol = purchaseOrder.Symbol,
                            Purchased = purchaseOrder.Count,
                            TotalPurchased = purchaseOrder.Count,
                            status = 200,
                            detail = "Your purchase order has been processed"
                        }));
                    }
                    catch (Exception)
                    {
                        return(BadRequest(new
                        {
                            status = 400,
                            detail = "Failed to purchase stock."
                        }));
                    }
                }
                else
                {
                    try
                    {
                        stock.PurchasedCount += purchaseOrder.Count;
                        user.Cash            -= (purchaseOrder.Count * purchaseOrder.CurrentPrice);
                        _context.SaveChanges();

                        return(Ok(new
                        {
                            CurrentCash = user.Cash,
                            Symbol = purchaseOrder.Symbol,
                            Purchased = purchaseOrder.Count,
                            TotalPurchased = stock.PurchasedCount,
                            status = 200,
                            detail = "Your purchase order has been processed"
                        }));
                    }
                    catch (Exception)
                    {
                        return(BadRequest(new
                        {
                            status = 400,
                            detail = "Failed to purchase stock."
                        }));
                    }
                }
            }
            else
            {
                return(BadRequest(new
                {
                    status = 400,
                    detail = "You don't have enough cash to process this purchase order."
                }));
            }
        }
示例#29
0
 public BuyController(ILogger <BuyController> logger)
 {
     _logger   = logger;
     _buyModel = new BuyModel();
 }
        public async Task <Response <NoContent> > BuyAsync(BuyModel buyModel)
        {
            Response <NoContent> response = null;

            DTO.Product.ProductTradeDto productTradeDto = await productService.GetProductByIdAsync(buyModel.ProductId);

            if (productTradeDto.Amount < buyModel.Amount)
            {
                response = Response <NoContent> .Fail(
                    statusCode : StatusCodes.Status400BadRequest,
                    isShow : true,
                    path : "[post] api/trade",
                    errors : "Piyasada bu miktarda ürün bulunmamaktadır"
                    );

                return(response);
            }

            List <MarketItemDto> marketItems = productTradeDto.MarketItems.Where(x => x.WalletId != buyModel.WalletId).OrderBy(x => x.UnitPrice).ToList();

            double count = 0;

            if (marketItems != null && marketItems.Any())
            {
                foreach (MarketItemDto marketItem in marketItems)
                {
                    if (count == buyModel.Amount)
                    {
                        break;
                    }
                    double buyToCount = buyModel.Amount - count;
                    double satinalinabilecekitemsayisi = buyModel.WalletDto.Money / (marketItem.UnitPrice * (1 + ComissionRate));
                    double satinalinacaksayisi         = 0;
                    if (buyToCount <= satinalinabilecekitemsayisi)
                    {
                        if (buyToCount >= marketItem.Amount)
                        {
                            satinalinacaksayisi = marketItem.Amount;
                        }
                        else if (marketItem.Amount > buyToCount)
                        {
                            satinalinacaksayisi = buyToCount;
                        }
                    }
                    else
                    {
                        satinalinacaksayisi = satinalinabilecekitemsayisi;
                    }

                    try
                    {
                        count += satinalinacaksayisi;
                        //Kullanicinin hesabindan satin alinacak urunun parasini dus
                        buyModel.WalletDto.Money -= satinalinacaksayisi * (marketItem.UnitPrice * (1 + ComissionRate));
                        await genericWalletService.UpdateAsync(new WalletUpdateDto()
                        {
                            Id           = buyModel.WalletDto.Id,
                            Money        = buyModel.WalletDto.Money,
                            UpdateUserId = Guid.Parse(UserStringInfo.SystemUserId)
                        });

                        //satan kullaniciya parayi ver
                        WalletUpdateDto sellerWallet = await genericWalletService.GetByIdAsync <WalletUpdateDto>(marketItem.WalletId);

                        sellerWallet.Money       += satinalinacaksayisi * marketItem.UnitPrice;
                        sellerWallet.UpdateUserId = Guid.Parse(UserStringInfo.SystemUserId);
                        await genericWalletService.UpdateAsync(sellerWallet);

                        //Accounting UPDATE
                        WalletUpdateDto accountingWallet = await genericWalletService.GetByIdAsync <WalletUpdateDto>(AccountingState.AccountingWalletId);

                        accountingWallet.Money       += satinalinacaksayisi * marketItem.UnitPrice * ComissionRate;
                        accountingWallet.UpdateUserId = Guid.Parse(UserStringInfo.SystemUserId);
                        await genericWalletService.UpdateAsync(accountingWallet);

                        await genericWalletService.Commit();

                        //kullanicinin hesabindaki urun adedini guncelle
                        buyModel.ProductItem.Amount      += satinalinacaksayisi;
                        buyModel.ProductItem.UpdateUserId = Guid.Parse(UserStringInfo.SystemUserId);
                        await genericProductItemRepository.UpdateAsync(buyModel.ProductItem);

                        await genericProductItemRepository.Commit();

                        //marketItem urun adedini guncelle
                        marketItem.Amount -= satinalinacaksayisi;
                        if (marketItem.Amount == 0)
                        {
                            marketItem.InProgress = false;
                        }
                        MarketItemUpdateDto marketItemUpdateDto = mapper.Map <MarketItemUpdateDto>(marketItem);
                        marketItemUpdateDto.UpdateUserId = Guid.Parse(UserStringInfo.SystemUserId);
                        await genericMarketItemService.UpdateAsync(marketItemUpdateDto);

                        await genericMarketItemService.Commit();

                        //islem gecmisi olustur
                        TransactionCreateDto transaction = new()
                        {
                            Amount         = satinalinacaksayisi,
                            CreatedUserId  = Guid.Parse(UserStringInfo.SystemUserId),
                            ProductId      = buyModel.ProductId,
                            UnitPrice      = marketItem.UnitPrice,
                            WalletIdBuyer  = buyModel.WalletId,
                            WalletIdSeller = sellerWallet.Id
                        };
                        await genericTransactionService.AddAsync(transaction);

                        await genericTransactionService.Commit();

                        response = Response <NoContent> .Success(StatusCodes.Status201Created);
                    }
                    catch
                    {
                        await genericWalletService.Commit(false);

                        await genericProductItemRepository.Commit(false);

                        await genericMarketItemService.Commit(false);

                        await genericTransactionService.Commit(false);

                        response = Response <NoContent> .Fail(
                            statusCode : StatusCodes.Status500InternalServerError,
                            isShow : true,
                            path : "[post] api/trade",
                            errors : "Satin alim gerceklesirken bir hata meydana geldi"
                            );
                    }
                }
            }

            if (response == null)
            {
                response = Response <NoContent> .Success(StatusCodes.Status201Created);
            }
            return(response);
        }