using pwt_0x01_ng.Controllers; using pwt_0x01_ng.Models; using pwt_0x01_ng.Models.ApplicationServices; using pwt_0x01_ng.Models.Database; using pwt_0x01_ng.Models.Identity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace pwt_0x01_ng.Areas.Customer.Controllers { [Area("Customer")] [Authorize(Roles = nameof(Roles.Customer))] public class CustomerOrderNotCartController : Controller { const string s_price_total = "Price_total"; const string s_order_items = "OrderItems"; ISecurityApplicationService isas; DBContext ctx; public CustomerOrderNotCartController(ISecurityApplicationService isas, DBContext ctx) { this.isas = isas; this.ctx = ctx; } [HttpPost] public int AddOrderItemsToSession(int? productId) { int price_total = 0; if (HttpContext.Session.IsAvailable) { price_total = HttpContext.Session.GetInt32(s_price_total).GetValueOrDefault(); } Product product = ctx.Product.Where(prod => prod.id == productId).FirstOrDefault(); if (product != null) { OrderItem order_item = new OrderItem() { Product_id = product.id, Product = product, Amount = 1, Price = product.Price }; if (HttpContext.Session.IsAvailable) { List orderItems = HttpContext.Session.GetObject>(s_order_items); OrderItem orderItemInSession = null; if (orderItems != null) orderItemInSession = orderItems.Find(oi => oi.Product_id == order_item.Product_id); else orderItems = new List(); if (orderItemInSession != null) { ++orderItemInSession.Amount; orderItemInSession.Price += order_item.Product.Price; } else { orderItems.Add(order_item); } HttpContext.Session.SetObject(s_order_items, orderItems); price_total += order_item.Product.Price; HttpContext.Session.SetInt32(s_price_total, price_total); } } return price_total; } public async Task ApproveOrderInSession() { if (HttpContext.Session.IsAvailable) { int price_total = 0; List order_items = HttpContext.Session.GetObject>(s_order_items); if (order_items != null) { foreach (OrderItem order_item in order_items) { price_total += order_item.Product.Price * order_item.Amount; order_item.Product = null; } User currentUser = await isas.gimme_current_user(User); Order order = new Order() { Order_Number = Convert.ToBase64String(Guid.NewGuid().ToByteArray()), Price_total = price_total, OrderItems = order_items, User_id = currentUser.Id }; await ctx.AddAsync(order); await ctx.SaveChangesAsync(); HttpContext.Session.Remove(s_order_items); HttpContext.Session.Remove(s_price_total); return RedirectToAction(nameof(CustomerOrdersController.Index), nameof(CustomerOrdersController).Replace("Controller", ""), new { Area = nameof(Customer) }); } } return RedirectToAction(nameof(HomeController.Index), nameof(HomeController).Replace("Controller", ""), new { Area = "" }); } } }