public ActionResult SubmitProposal(SetProposalViewModel viewModel) { var existingEmployee = DB.StockHistories .Where(x => x.UserId == viewModel.EmployeeId && x.EndDate == null) .OrderByDescending(x => x.StockHistoryId) .FirstOrDefault(); if (existingEmployee != null) { // Update Stock History if material is already in existingEmployee.EndDate = DateTime.Today; existingEmployee.UpdatedDate = DateTime.Today; existingEmployee.UpdatedById = LoggedUser.EmployeeId; StockHistory stockHistory = new StockHistory(); stockHistory.StockId = existingEmployee.StockId; stockHistory.UserId = viewModel.EmployeeId; stockHistory.StartDate = DateTime.Today; stockHistory.EndDate = null; stockHistory.CreatedDate = DateTime.Today; stockHistory.CreatedById = LoggedUser.EmployeeId; stockHistory.UpdatedDate = null; stockHistory.UpdatedById = null; DB.StockHistories.Add(stockHistory); // Update GATE_ComponentRequest var componentRequest = DB.GATE_ComponentRequest.Find(viewModel.ComponentId); componentRequest.StockHistoryId = existingEmployee.StockHistoryId; DB.SaveChanges(); } else { if (viewModel.EmployeeId != 0) { // Add material into Stock Stock stock = new Stock(); StockHelper stockService = new StockHelper(DB, LoggedUser); string companyCodeName = stockService.FindCompanyCodeNameFromEmployee(viewModel.EmployeeId); string materialCode = stockService.FindMaterialCodeFromComponentId(viewModel.ComponentId); int companyId = DB.Companies.Where(x => x.CompanyCodeName == companyCodeName).Select(x => x.ID).FirstOrDefault(); int materialId = DB.GenericMaterials .Where(x => x.MaterialCode == materialCode) .Select(x => x.GenericMaterialId) .FirstOrDefault(); int seqnember = stockService.GetNextSeqNumber(companyId, materialId); string productCode = stockService.GenerateProductCode(companyCodeName, materialCode, seqnember); stock.ProductCode = productCode; stock.CompanyId = companyId; stock.GenericMaterialId = materialId; stock.SeqNumber = seqnember; stock.Note = null; stock.StockStatusId = StockStatus.InStock; DB.Stocks.Add(stock); DB.SaveChanges(); // Update Stock History for previous employee StockHistory previousEmployee = new StockHistory(); previousEmployee.StockId = stock.StockId; previousEmployee.UserId = viewModel.EmployeeId; previousEmployee.StartDate = DateTime.Today; previousEmployee.EndDate = DateTime.Today; previousEmployee.CreatedById = LoggedUser.EmployeeId; previousEmployee.CreatedDate = DateTime.Today; previousEmployee.UpdatedDate = DateTime.Today; previousEmployee.UpdatedById = LoggedUser.EmployeeId; DB.StockHistories.Add(previousEmployee); DB.SaveChanges(); // Update GATE_ComponentRequest var componentRequest = DB.GATE_ComponentRequest.Find(viewModel.ComponentId); componentRequest.StockHistoryId = previousEmployee.StockHistoryId; // Update Stock History for new employee StockHistory newEmployee = new StockHistory(); newEmployee.StockId = stock.StockId; newEmployee.UserId = DB.GATE_MaterialRequest .Where(x => x.MaterialRequestId == viewModel.MaterialRequestId) .Select(x => x.ConcernedEmployeeId) .FirstOrDefault(); newEmployee.StartDate = DateTime.Today; newEmployee.EndDate = null; newEmployee.CreatedDate = DateTime.Today; newEmployee.CreatedById = LoggedUser.EmployeeId; newEmployee.UpdatedDate = null; newEmployee.UpdatedById = null; DB.StockHistories.Add(newEmployee); DB.SaveChanges(); } // User select a material from Stock, not from an employee else { // Add material into Stock Stock stock = new Stock(); StockHelper stockService = new StockHelper(DB, LoggedUser); string companyCodeName = DB.GATE_MaterialRequest .Where(x => x.MaterialRequestId == viewModel.MaterialRequestId) .Select(x => x.ConcernedEmployee.Company.CompanyCodeName) .FirstOrDefault(); string materialCode = stockService.FindMaterialCodeFromComponentId(viewModel.ComponentId); int companyId = DB.Companies.Where(x => x.CompanyCodeName == companyCodeName).Select(x => x.ID).FirstOrDefault(); int materialId = DB.GenericMaterials .Where(x => x.MaterialCode == materialCode) .Select(x => x.GenericMaterialId) .FirstOrDefault(); int seqnember = stockService.GetNextSeqNumber(companyId, materialId); string productCode = stockService.GenerateProductCode(companyCodeName, materialCode, seqnember); stock.ProductCode = productCode; stock.CompanyId = companyId; stock.GenericMaterialId = materialId; stock.SeqNumber = seqnember; stock.Note = null; stock.StockStatusId = StockStatus.InStock; DB.Stocks.Add(stock); DB.SaveChanges(); // Update Stock History. It is same to indicate the material from Stock StockHistory previousEmployee = new StockHistory(); previousEmployee.StockId = stock.StockId; previousEmployee.UserId = DB.GATE_MaterialRequest .Where(x => x.MaterialRequestId == viewModel.MaterialRequestId) .Select(x => x.ConcernedEmployeeId) .FirstOrDefault(); previousEmployee.StartDate = DateTime.Today; previousEmployee.EndDate = DateTime.Today; previousEmployee.CreatedById = LoggedUser.EmployeeId; previousEmployee.CreatedDate = DateTime.Today; previousEmployee.UpdatedDate = DateTime.Today; previousEmployee.UpdatedById = LoggedUser.EmployeeId; DB.StockHistories.Add(previousEmployee); DB.SaveChanges(); // Update GATE_ComponentRequest var componentRequest = DB.GATE_ComponentRequest.Find(viewModel.ComponentId); componentRequest.StockHistoryId = previousEmployee.StockHistoryId; // Update Stock History for new employee StockHistory newEmployee = new StockHistory(); newEmployee.StockId = stock.StockId; newEmployee.UserId = DB.GATE_MaterialRequest .Where(x => x.MaterialRequestId == viewModel.MaterialRequestId) .Select(x => x.ConcernedEmployeeId) .FirstOrDefault(); newEmployee.StartDate = DateTime.Today; newEmployee.EndDate = null; newEmployee.CreatedDate = DateTime.Today; newEmployee.CreatedById = LoggedUser.EmployeeId; newEmployee.UpdatedDate = null; newEmployee.UpdatedById = null; DB.StockHistories.Add(newEmployee); DB.SaveChanges(); } } Session["SelectedEmployeeId"] = viewModel.EmployeeId; return ConfirmDelivery(viewModel.ComponentId); }
private void SyncSymbolHistory(int id) { OPIMsysContext stockquotes = new OPIMsysContext(); var stock = stockquotes.StockSymbols.FirstOrDefault((s) => s.StockSymbolId == id); if (stock != null) { var market = (from s in stockquotes.Markets where s.MarketId == stock.MarketId select s).FirstOrDefault(); switch (market.MarketName) { case "NYSE": { int i = 1; int errorcnt = 0; int skipcnt = 0; while (i >= 0) { int skip = 0; DateTime today = DateTime.Today; today = today.AddDays(-1 * i); if (today.DayOfWeek == DayOfWeek.Sunday || today.DayOfWeek == DayOfWeek.Saturday) skip++; //Check to see if the history exists int daycnt = (from s in stockquotes.StockHistories where s.HistoryDate == today && s.StockSymbolId == stock.StockSymbolId select s).Count(); if (daycnt > 0) skip++; skipcnt += skip; if (skipcnt > 2) i = -3; //It does then go to the next if (skip == 0) { string url = "http://ichart.finance.yahoo.com/table.csv?s=" + stock.Symbol + ""; url = url + "&a=" + String.Format("{0:00}", (today.Month - 1)) + "&b=" + today.Day.ToString("D2") + "&c=" + today.Year + "&d=" + String.Format("{0:00}", (today.Month - 1)) + "&e=" + today.Day.ToString("D2") + "&f=" + today.Year + "&g=d&ignore=.csv"; try { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); //Is the data valid if (returnVal.Count == 7) { StockHistory stockHistory = new StockHistory(); stockHistory.HistoryDate = DateTime.Parse(returnVal[0]); stockHistory.Open = Decimal.Parse(returnVal[1]); stockHistory.High = Decimal.Parse(returnVal[2]); stockHistory.Low = Decimal.Parse(returnVal[3]); stockHistory.Close = Decimal.Parse(returnVal[4]); stockHistory.Volume = long.Parse(returnVal[5]); if (returnVal.Count > 6) stockHistory.AdjClose = Decimal.Parse(returnVal[6]); stockHistory.StockSymbolId = stock.StockSymbolId; if (stockquotes.StockHistories.Count((c) => c.StockSymbolId == stock.StockSymbolId && c.HistoryDate == stockHistory.HistoryDate) == 0) stockquotes.StockHistories.Add(stockHistory); stockquotes.SaveChanges(); errorcnt = 0; } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { errorcnt++; if (errorcnt > 7) i = -3; } } } } i++; } break; } case "TSX": { int i = 1; int errorcnt = 0; int skipcnt = 0; while (i >= 0) { int skip = 0; DateTime today = DateTime.Today; today = today.AddDays(-1 * i); if (today.DayOfWeek == DayOfWeek.Sunday || today.DayOfWeek == DayOfWeek.Saturday) skip++; //Check to see if the history exists int daycnt = (from s in stockquotes.StockHistories where s.HistoryDate == today && s.StockSymbolId == stock.StockSymbolId select s).Count(); if(daycnt > 0) skip++; skipcnt += skip; if (skipcnt > 2) i = -3; //It does then go to the next if(skip == 0) { string symbol = stock.Symbol; List<string> protectSymbols = new List<string>(); protectSymbols.Add("EGL-UN"); protectSymbols.Add("AET-UN"); protectSymbols.Add("PLT-UN"); if(!protectSymbols.Contains(symbol)) symbol = symbol.Replace('-', '.'); string url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + ".TO"; url = url + "&a=" + String.Format("{0:00}", (today.Month - 1)) + "&b=" + today.Day.ToString("D2") + "&c=" + today.Year + "&d=" + String.Format("{0:00}", (today.Month - 1)) + "&e=" + today.Day.ToString("D2") + "&f=" + today.Year + "&g=d&ignore=.csv"; try { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); //Is the data valid if (returnVal.Count == 7) { StockHistory stockHistory = new StockHistory(); stockHistory.HistoryDate = DateTime.Parse(returnVal[0]); stockHistory.Open = Decimal.Parse(returnVal[1]); stockHistory.High = Decimal.Parse(returnVal[2]); stockHistory.Low = Decimal.Parse(returnVal[3]); stockHistory.Close = Decimal.Parse(returnVal[4]); stockHistory.Volume = long.Parse(returnVal[5]); if (returnVal.Count > 6) stockHistory.AdjClose = Decimal.Parse(returnVal[6]); stockHistory.StockSymbolId = stock.StockSymbolId; if (stockquotes.StockHistories.Count((c) => c.StockSymbolId == stock.StockSymbolId && c.HistoryDate == stockHistory.HistoryDate) == 0) stockquotes.StockHistories.Add(stockHistory); stockquotes.SaveChanges(); errorcnt = 0; } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { errorcnt++; if (errorcnt > 25) i = -3; } } } } i++; } break; } case "TSX.V": { int i = 1; int errorcnt = 0; int skipcnt = 0; while (i >= 0) { int skip = 0; DateTime today = DateTime.Today; today = today.AddDays(-1 * i); if (today.DayOfWeek == DayOfWeek.Sunday || today.DayOfWeek == DayOfWeek.Saturday) skip++; //Check to see if the history exists int daycnt = (from s in stockquotes.StockHistories where s.HistoryDate == today && s.StockSymbolId == stock.StockSymbolId select s).Count(); if (daycnt > 0) skip++; skipcnt += skip; if (skipcnt > 2) i = -3; //It does then go to the next if (skip == 0) { string url = "http://ichart.finance.yahoo.com/table.csv?s=" + stock.Symbol + ".V"; url = url + "&a=" + String.Format("{0:00}", (today.Month - 1)) + "&b=" + today.Day.ToString("D2") + "&c=" + today.Year + "&d=" + String.Format("{0:00}", (today.Month - 1)) + "&e=" + today.Day.ToString("D2") + "&f=" + today.Year + "&g=d&ignore=.csv"; try { WebRequest request = WebRequest.Create(url); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader sr = new StreamReader(dataStream); string line = sr.ReadLine(); line = sr.ReadLine(); List<string> returnVal = line.Split(',').ToList(); //Is the data valid if (returnVal.Count == 7) { StockHistory stockHistory = new StockHistory(); stockHistory.HistoryDate = DateTime.Parse(returnVal[0]); stockHistory.Open = Decimal.Parse(returnVal[1]); stockHistory.High = Decimal.Parse(returnVal[2]); stockHistory.Low = Decimal.Parse(returnVal[3]); stockHistory.Close = Decimal.Parse(returnVal[4]); stockHistory.Volume = long.Parse(returnVal[5]); if (returnVal.Count > 6) stockHistory.AdjClose = Decimal.Parse(returnVal[6]); stockHistory.StockSymbolId = stock.StockSymbolId; if (stockquotes.StockHistories.Count((c) => c.StockSymbolId == stock.StockSymbolId && c.HistoryDate == stockHistory.HistoryDate) == 0) stockquotes.StockHistories.Add(stockHistory); stockquotes.SaveChanges(); errorcnt = 0; } } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null) { var resp = (HttpWebResponse)ex.Response; if (resp.StatusCode == HttpStatusCode.NotFound) { errorcnt++; if (errorcnt > 7) i = -3; } } } } i++; } break; } } return; } throw new HttpResponseException(HttpStatusCode.NotFound); }
public FemaMetric(StockHistory data) : base(data) { m_Color = Color.RoyalBlue; }
public XemaMetric(StockHistory stock) { Analyse(stock); }
// //////////////////////////////////////////////////////////////////////////////////////////////////////// // HELP STRIPE ONLINE PAYMENT // //////////////////////////////////////////////////////////////////////////////////////////////////////// public async Task <IActionResult> Charge(string stripeEmail, string StripeToken, decimal amount) { // ___________________________________________________ // To get public key // Set your secret key. Remember to switch to your live secret key in production! // ___________________________________________________ string accessToken = await HttpContext.GetTokenAsync("access_token"); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); string idUser = await client.GetStringAsync(_configuration["URLApi"] + "api/AspNetUsers/UserId/"); string uriPkey = _configuration["URLApi"] + "api/stripePay/PKey/"; string pKey = null; List <string> stripePKeys; string content = await client.GetStringAsync(uriPkey); if (content != null) { stripePKeys = JsonConvert.DeserializeObject <List <string> >(content); } else { // View ERROR return(NotFound()); } // LineItems total amount foreach (var item in stripePKeys) { if (item != null) { pKey = item; } } string publickey = pKey; ViewBag.PUBLICKEY = publickey; // ___________________________________________________ // To get ApiKey // ___________________________________________________ string uriApiKey = _configuration["URLApi"] + "api/stripePay/ApiKey"; string apiKey = null; List <string> stripeApiKeys; string contentApikey = await client.GetStringAsync(uriApiKey); if (contentApikey != null) { stripeApiKeys = JsonConvert.DeserializeObject <List <string> >(contentApikey); } else { // View ERROR return(NotFound()); } // LineItems total amount foreach (var item in stripeApiKeys) { if (item != null) { apiKey = item; } } string returnedApiKey = apiKey; ViewBag.APIKEY = returnedApiKey; StripeConfiguration.ApiKey = returnedApiKey; // ___________________________________________________ // Calculate the total amount of charge // ___________________________________________________ // Tdodo Récupérer dans lineItems /* * if (_configuration["Environnement"] == "Prod") // Windows 10 ? * { * amount = amount * 100; * }*/ amount *= 100; // Windows 7 ? long chargeAmount = Convert.ToInt64(amount); decimal montant = amount / 100; ViewBag.MONTANT = montant; // ___________________________________________________ // Create Stripe Environnement // ___________________________________________________ var customers = new CustomerService(); var Charges = new ChargeService(); var customer = customers.Create( new CustomerCreateOptions { Email = stripeEmail, Source = StripeToken }); var charge = Charges.Create( new ChargeCreateOptions { Amount = chargeAmount, Description = "Test Payment", Currency = "chf", Customer = customer.Id, ReceiptEmail = stripeEmail, Metadata = new Dictionary <string, string>() { { "integration_check", "accept_a_payment" }, { "OrderId", "111" }, { "Postcode", "3100" } } }); // ___________________________________________________ // Verify the payment // ___________________________________________________ if (charge.Status == "succeeded") { // ___________________________________________________ // Récupération des livres pour y modifier la quantité // ___________________________________________________ string uriShopcart = _configuration["URLApi"] + "api/ShoppingCarts/" + "ShoppingCart/" + idUser; ShoppingCart shoppingcart; HttpResponseMessage responseShopcart = await client.GetAsync(uriShopcart); string resultShopcart = responseShopcart.Content.ReadAsStringAsync().Result; shoppingcart = JsonConvert.DeserializeObject <ShoppingCart>(resultShopcart); string contentLineItems = await client.GetStringAsync(_configuration["URLApi"] + "api/LineItems/Items/" + shoppingcart.Id); IEnumerable <Models.LineItem> lineItems = JsonConvert.DeserializeObject <IEnumerable <Models.LineItem> >(contentLineItems); HttpResponseMessage response; string details = "Livres achetés : "; string message = "Envoyé"; foreach (Models.LineItem lineItem in lineItems) { details += lineItem.IdBookNavigation.Title + " (" + lineItem.Quantity + "x " + lineItem.UnitPrice.ToString("F2") + ") / "; lineItem.IdBookNavigation.Stock -= lineItem.Quantity; // historique du stock StockHistory sh = new StockHistory { IdBook = lineItem.IdBook, TransactionDate = DateTime.Now, TransactionStock = lineItem.IdBookNavigation.Stock, TransactionType = 1 }; HttpResponseMessage responseStock = await _client.PostAsJsonAsync(_configuration["URLApi"] + "api/StockHistories", sh);// HTTP GET responseStock.EnsureSuccessStatusCode(); string jsonString = System.Text.Json.JsonSerializer.Serialize <Book>(lineItem.IdBookNavigation); StringContent httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json"); response = await client.PutAsync(_configuration["URLApi"] + "api/Books/" + lineItem.IdBookNavigation.Id, httpContent); if (response.StatusCode != HttpStatusCode.NoContent) { return(BadRequest()); } if (lineItem.IdBookNavigation.Stock < 0) { message = "En attente"; } } // ___________________________________________________ // Enregistrement de la commande dans la BD // ___________________________________________________ string contentCustomer = await client.GetStringAsync(_configuration["URLApi"] + "api/Customers/"); Models.Customer currentCustomer = JsonConvert.DeserializeObject <Models.Customer>(contentCustomer); Models.Order order = new Models.Order { UserId = idUser, OrderedDate = DateTime.Now, ShippedDate = DateTime.Now, ShippingAddress = currentCustomer.BillingAddress, Status = message, TotalPrice = montant }; response = await client.PostAsJsonAsync(_configuration["URLApi"] + "api/Orders/", order); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } // ___________________________________________________ // Enregistrement du paiement dans la BD // ___________________________________________________ string contentOrders = await client.GetStringAsync(_configuration["URLApi"] + "api/Orders/"); IEnumerable <Models.Order> listOrders = JsonConvert.DeserializeObject <IEnumerable <Models.Order> >(contentOrders); int orderId = listOrders.Max(i => i.Id); Payment payment = new Payment { UserId = idUser, IdOrder = orderId, PaidDate = DateTime.Now, PriceTotal = montant, Details = details }; response = await client.PostAsJsonAsync(_configuration["URLApi"] + "api/Payments/", payment); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } ViewBag.DETAILS = details; ViewBag.DATE = payment.PaidDate; // ___________________________________________________ // Récupération du Shoppingcart pour suppression des LineItems dans la BD après validation du paiement // ___________________________________________________ response = await client.GetAsync(_configuration["URLApi"] + "api/LineItems/DeleteItems/" + shoppingcart.Id); if (response.StatusCode != HttpStatusCode.OK) { return(BadRequest()); } return(View()); } else { return(View("Error")); } } // End
public SemaMetric(StockHistory data) : base(data) { m_Color = Color.SeaGreen; }
public Task <int> DeleteStockHistoryAsync(StockHistory stockHistory) { return(_database.DeleteAsync(stockHistory)); }
public BollingerBandsMetric(StockHistory stock) { Analyse(stock); }
public async Task <IActionResult> Create(HalakaBuyRecVm data) { if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User); var roles = await _userManager.GetRolesAsync(user); int PID = 1; if (roles.Contains("partner")) { PID = 2; } var FishesCookie = data.FishNames.TrimEnd(data.FishNames[data.FishNames.Length - 1]); var ProductionTypesCookie = data.ProductionTypes.TrimEnd(data.ProductionTypes[data.ProductionTypes.Length - 1]); var qtysCookie = data.qtys.TrimEnd(data.qtys[data.qtys.Length - 1]); var unitpricesCookie = data.unitprices.TrimEnd(data.unitprices[data.unitprices.Length - 1]); string[] Fishes = FishesCookie.Split(",").Select(c => Convert.ToString(c)).ToArray(); string[] Productions = ProductionTypesCookie.Split(",").Select(c => Convert.ToString(c)).ToArray(); string[] qtys = qtysCookie.Split(",").Select(c => Convert.ToString(c)).ToArray(); decimal[] unitPrices = unitpricesCookie.Split(",").Select(c => Convert.ToDecimal(c)).ToArray(); HalakaBuyReciept halakaBuyReciept = new HalakaBuyReciept() { Date = data.Date, PersonID = PID, SellerName = data.SellerName, TotalOfPrices = data.TotalOfReciept }; _context.HalakaBuyReciepts.Add(halakaBuyReciept); _context.SaveChanges(); for (int i = 0; i < Fishes.Length; i++) { string[] splitItem = Fishes[i].Split("/").Select(c => Convert.ToString(c)).ToArray(); if (splitItem.Length > 1) { Guid amountID = Guid.NewGuid(); double[] splitItemQty = qtys[i].Split("/").Select(c => Convert.ToDouble(c)).ToArray(); for (int j = 0; j < splitItem.Length; j++) { var fish = _context.Fishes.Single(x => x.FishName == splitItem[j]); var Produc = _context.ProductionTypes.Single(x => x.ProductionName == Productions[i]); HalakaBuyRecieptItem HalakaBuyRecieptItem = new HalakaBuyRecieptItem() { HalakaBuyRecieptID = halakaBuyReciept.HalakaBuyRecieptID, FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = splitItemQty[j], UnitPrice = unitPrices[i], AmountId = amountID }; _context.HalakaBuyRecieptItems.Add(HalakaBuyRecieptItem); _context.SaveChanges(); var s = _context.Stocks.Where(c => c.FishID == fish.FishID).FirstOrDefault(); if (s != null) { if (s.ProductionTypeID == Produc.ProductionTypeID) { if (s.ProductionTypeID == 3) { s.Qty += splitItemQty[j]; s.TotalWeight += splitItemQty[j]; } else { s.Qty += splitItemQty[j]; } } else { Stock stoc = new Stock() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = splitItemQty[j], Date = data.Date }; _context.Stocks.Add(stoc); } } else { Stock stock = new Stock() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = splitItemQty[j], }; _context.Stocks.Add(stock); } var stockHistory = _context.StockHistories.ToList().Where(c => c.Date.ToShortDateString() == TimeNow().ToShortDateString() && c.FishID == fish.FishID && c.ProductionTypeID == Produc.ProductionTypeID).FirstOrDefault(); if (stockHistory != null) { stockHistory.Total += splitItemQty[j]; } else { StockHistory history = new StockHistory() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Total = splitItemQty[j], Date = TimeNow() }; _context.StockHistories.Add(history); } } } else { var fish = _context.Fishes.Single(x => x.FishName == Fishes[i]); var Produc = _context.ProductionTypes.Single(x => x.ProductionName == Productions[i]); HalakaBuyRecieptItem NewIMerchantRecieptItems = new HalakaBuyRecieptItem() { HalakaBuyRecieptID = halakaBuyReciept.HalakaBuyRecieptID, FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = double.Parse(qtys[i]), UnitPrice = unitPrices[i], }; _context.HalakaBuyRecieptItems.Add(NewIMerchantRecieptItems); _context.SaveChanges(); var s = _context.Stocks.Where(c => c.FishID == fish.FishID).FirstOrDefault(); if (s != null) { if (s.ProductionTypeID == Produc.ProductionTypeID) { s.Qty += double.Parse(qtys[i]); _context.SaveChanges(); } else { Stock stoc = new Stock() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = double.Parse(qtys[i]), Date = data.Date }; _context.Stocks.Add(stoc); _context.SaveChanges(); } } else { Stock stock = new Stock() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Qty = double.Parse(qtys[i]) }; _context.Stocks.Add(stock); _context.SaveChanges(); } var stockHistory = _context.StockHistories.ToList().Where(c => c.Date.ToShortDateString() == TimeNow().ToShortDateString() && c.FishID == fish.FishID && c.ProductionTypeID == Produc.ProductionTypeID).FirstOrDefault(); if (stockHistory != null) { stockHistory.Total += double.Parse(qtys[i]); } else { StockHistory history = new StockHistory() { FishID = fish.FishID, ProductionTypeID = Produc.ProductionTypeID, Total = double.Parse(qtys[i]), Date = TimeNow() }; _context.StockHistories.Add(history); } } //_context.IMerchantRecieptItem.Add(IMerchantRecieptItems); } var stockrows = _context.Stocks.ToList(); foreach (var item in stockrows) { if (item.ProductionTypeID == 3)//ميزان { item.TotalWeight = item.Qty; } //else //{ // //الطوايل هتتم عن طريق التصنيف //} } _context.SaveChanges(); return(Json(new { message = "success" })); //return RedirectToAction(nameof(Details),new { id= ImerchantReciept.IMerchantRecieptID }); } else { return(Json(new { message = "fail" })); } // return View(); }
public ActionResult CreateStockSell([Bind(Include = "TradeType,TradeDate,UserName")] SummaryTable summaryTable, [Bind(Include = "stockID,stockPrice,stockAmount,stockFee,stockTax,stockNetincome,stockNote")] StockHistory stockHistory) { if (Session["User"] == null) { return(RedirectToRoute("Default", new { Controller = "Home", Action = "Index" })); } //([Bind(Include = "TradeType,date,userID")] //[Bind(Include = "stockID,stockPrice,stockAmount,stockFee,stockTax,stockNetincome,stockNote")] if (ModelState.IsValid) { //存入總表取得交易序號 db.SummaryTable.Add(summaryTable); db.SaveChanges(); var id = db.SummaryTable.Select(c => c.STId).ToList().LastOrDefault(); //存入現金帳戶 CashIncome cashincome = new CashIncome(); cashincome.OID = id; cashincome.UserName = summaryTable.UserName; cashincome.InCashType = summaryTable.TradeType; cashincome.InAmount = (stockHistory.stockNetincome); cashincome.InDate = summaryTable.TradeDate; cashincome.InNote = "賣出股票"; db.CashIncome.Add(cashincome); db.SaveChanges(); //存入股票交易記錄表 stockHistory.stockAmount = stockHistory.stockAmount * (-1000); AVGCalculator calculator = new AVGCalculator(); string _username = Session["User"].ToString(); string _searchid = stockHistory.stockID.ToString(); int _invchange = (int)stockHistory.stockAmount; int _cashflow = (int)stockHistory.stockNetincome; stockHistory.stockLastAVG = calculator.GetAvg(_username, _searchid, _invchange, _cashflow); stockHistory.STId = id; db.StockHistory.Add(stockHistory); db.SaveChanges(); return(RedirectToAction("Index")); } return(RedirectToAction("Index")); }
public ActionResult CreateEXS([Bind(Include = "TradeType,TradeDate,UserName")] SummaryTable summaryTable, [Bind(Include = "stockID,stockPrice,stockAmount,stockFee,stockTax,stockNetincome,stockNote")] StockHistory stockHistory) { if (Session["User"] == null) { return(RedirectToRoute("Default", new { Controller = "Home", Action = "Index" })); } //([Bind(Include = "TradeType,date,userID")] //[Bind(Include = "stockID,stockPrice,stockAmount,stockFee,stockTax,stockNetincome,stockNote") if (ModelState.IsValid) { db.SummaryTable.Add(summaryTable); db.SaveChanges(); var id = db.SummaryTable.Select(c => c.STId).ToList().LastOrDefault(); stockHistory.STId = id; AVGCalculator calculator = new AVGCalculator(); string _username = Session["User"].ToString(); string _searchid = stockHistory.stockID.ToString(); int _invchange = (int)stockHistory.stockAmount; int _cashflow = (int)stockHistory.stockNetincome; stockHistory.stockLastAVG = calculator.GetAvg(_username, _searchid, _invchange, _cashflow); db.StockHistory.Add(stockHistory); db.SaveChanges(); return(RedirectToAction("Index")); } return(RedirectToAction("Index")); }
public ActionResult CreateStockBuy([Bind(Include = "TradeType,TradeDate,UserName")] SummaryTable summaryTable, [Bind(Include = "stockID,stockPrice,stockAmount,stockFee,stockTax,stockNetincome,stockNote,CashAccount")] StockHistory stockHistory) { if (Session["User"] == null) { return(RedirectToRoute("Default", new { Controller = "Home", Action = "Index" })); } if (ModelState.IsValid) { //存入總表獲得交易序號 db.SummaryTable.Add(summaryTable); db.SaveChanges(); var id = db.SummaryTable.Select(c => c.STId).ToList().LastOrDefault(); if (stockHistory.CashAccount) { CashExpense expense = new CashExpense(); expense.OID = id; expense.UserName = summaryTable.UserName; expense.ExCashType = summaryTable.TradeType; expense.ExAmount = (stockHistory.stockNetincome) * (-1); expense.ExDate = summaryTable.TradeDate; expense.ExNote = "買進股票"; db.CashExpense.Add(expense); db.SaveChanges(); } //存入股票交易紀錄表 stockHistory.STId = id; stockHistory.stockAmount = stockHistory.stockAmount * 1000; AVGCalculator calculator = new AVGCalculator(); string _username = Session["User"].ToString(); string _searchid = stockHistory.stockID.ToString(); int _invchange = (int)stockHistory.stockAmount; int _cashflow = (int)stockHistory.stockNetincome; stockHistory.stockLastAVG = calculator.GetAvg(_username, _searchid, _invchange, _cashflow); db.StockHistory.Add(stockHistory); db.SaveChanges(); ViewBag.Alert = "alert('新增成功')"; return(RedirectToAction("Index")); } return(RedirectToAction("Index")); }
public string GetAliStockInfo(string aliAppKey, string aliAppSecret) { String result = string.Empty; try { if (!string.IsNullOrEmpty(aliAppKey) && !string.IsNullOrEmpty(aliAppSecret)) { AliStock.AliStock resp = new AliStock.AliStock(aliAppKey, aliAppSecret, "http://ali-stock.showapi.com/stockIndex"); result = resp.doGet(); if (!string.IsNullOrEmpty(result)) { ResponseModel respStockModel = JsonConvert.DeserializeObject <ResponseModel>(result); if (respStockModel.showapi_res_code == 0) { for (int i = 0; i < respStockModel.showapi_res_body.indexList.Count; i++) { if (string.IsNullOrWhiteSpace(respStockModel.showapi_res_body.indexList[i].nowPrice) || respStockModel.showapi_res_body.indexList[i].nowPrice == "0") { continue; } string currDateMinute = DateTime.Parse(respStockModel.showapi_res_body.indexList[i].time).ToString("yyyy-MM-dd HH:mm"); StockHistory stockModel = Get <StockHistory>(string.Format(" Code='{1}' and DateMinute='{0}' ", currDateMinute, respStockModel.showapi_res_body.indexList[i].code)); if (stockModel != null) { stockModel.Code = respStockModel.showapi_res_body.indexList[i].code; stockModel.MaxPrice = respStockModel.showapi_res_body.indexList[i].maxPrice; stockModel.MinPrice = respStockModel.showapi_res_body.indexList[i].minPrice; stockModel.Name = respStockModel.showapi_res_body.indexList[i].name; stockModel.NowPrice = respStockModel.showapi_res_body.indexList[i].nowPrice; stockModel.Time = respStockModel.showapi_res_body.indexList[i].time; stockModel.TradeAmount = respStockModel.showapi_res_body.indexList[i].tradeAmount; stockModel.TradeNum = respStockModel.showapi_res_body.indexList[i].tradeNum; stockModel.YestodayClosePrice = respStockModel.showapi_res_body.indexList[i].yestodayClosePrice; stockModel.TodayOpenPrice = respStockModel.showapi_res_body.indexList[i].todayOpenPrice; stockModel.DiffMoney = (Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].nowPrice) - Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice)).ToString(); stockModel.DiffRate = ((Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].nowPrice) - Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice)) / Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice) * 100).ToString(); stockModel.DateMinute = currDateMinute; stockModel.LastUpdateDate = DateTime.Now; Update(stockModel); } else { stockModel = new StockHistory(); stockModel.Code = respStockModel.showapi_res_body.indexList[i].code; stockModel.MaxPrice = respStockModel.showapi_res_body.indexList[i].maxPrice; stockModel.MinPrice = respStockModel.showapi_res_body.indexList[i].minPrice; stockModel.Name = respStockModel.showapi_res_body.indexList[i].name; stockModel.NowPrice = respStockModel.showapi_res_body.indexList[i].nowPrice; stockModel.Time = respStockModel.showapi_res_body.indexList[i].time; stockModel.TradeAmount = respStockModel.showapi_res_body.indexList[i].tradeAmount; stockModel.TradeNum = respStockModel.showapi_res_body.indexList[i].tradeNum; stockModel.YestodayClosePrice = respStockModel.showapi_res_body.indexList[i].yestodayClosePrice; stockModel.TodayOpenPrice = respStockModel.showapi_res_body.indexList[i].todayOpenPrice; stockModel.DiffMoney = (Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].nowPrice) - Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice)).ToString(); stockModel.DiffRate = ((Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].nowPrice) - Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice)) / Convert.ToDecimal(respStockModel.showapi_res_body.indexList[i].yestodayClosePrice) * 100).ToString(); stockModel.DateMinute = currDateMinute; stockModel.LastUpdateDate = DateTime.Now; Add(stockModel); } } } else { throw new Exception(string.Format("{0}:{1}", respStockModel.showapi_res_error, result)); } } else { throw new Exception("获取阿里上证指数数据出错"); } } else { throw new Exception("站点还未配置阿里股票账号"); } } catch (Exception ex) { throw new Exception(string.Format("接口返回信息:{0};错误信息:{1};StackTrace:{2}", result, ex.Message, ex.StackTrace)); } return(result); }