public TwoDaysPurchasedMovie(Customer customer, DateTime purchased) : base(customer, purchased) { priceBeforeDiscount = 4; ExpirationDate = Purchased.AddDays(2); }
public async Task <IActionResult> ReadingChapter(int id) { var chapter = await _db.Chapters.Where(u => u.Id == id).Include(u => u.Book).FirstOrDefaultAsync(); Purchased alreadyBought = new Purchased(); var claimsIdentity = (ClaimsIdentity)User.Identity; if (claimsIdentity.Claims.Count() > 0) { var claimsUser = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); var user = await _db.ApplicationUsers.Where(u => u.Id == claimsUser.Value).FirstOrDefaultAsync(); alreadyBought = await _db.Purchaseds.Where(u => u.ChapterId == chapter.Id && u.ApplicationUserId == user.Id).FirstOrDefaultAsync(); var readingHistory = await _db.ReadingHitories.Where(u => u.Chapter.BookId == chapter.BookId).FirstOrDefaultAsync(); } if (alreadyBought != null || chapter.Price == 0 || User.IsInRole(SD.ADMIN_ROLE) || User.IsInRole(SD.CENSOR_ROLE) || User.IsInRole(SD.LIBRARIAN_ROLE)) { var chaptersOfBook = await _db.Chapters.Where(u => u.BookId == chapter.Book.Id).Include(u => u.Book).ToListAsync(); var index = chaptersOfBook.IndexOf(chapter); BooksVM.Chapter = chapter; BooksVM.Chapters = chaptersOfBook; return(View(nameof(Index), BooksVM)); } else { var book = await _db.Books.Where(u => u.Id == chapter.BookId).FirstOrDefaultAsync(); BooksVM.BuyRequest = "Chương này tính phí vui lòng mua"; BooksVM.Book = book; BooksVM.Chapter = chapter; return(View(nameof(Index), BooksVM)); } }
private static async Task TryAddPurchaseToOrder(Purchased item, string associatedId) { if (associatedId != null) { TOrder order = await _orderContainer.ReadItemAsync <TOrder>(associatedId, new Microsoft.Azure.Cosmos.PartitionKey(_merchantId + item.ASIN)); if (order.PurchaseDictionary == null) { order.PurchaseDictionary = new Dictionary <string, Purchased>(); } if (order.PurchaseDictionary.ContainsKey(order.id)) { order.PurchaseDictionary.Remove(order.id); } if (order.PurchaseDictionary.ContainsKey(item.id)) { order.PurchaseDictionary[item.id] = item; } else { order.PurchaseDictionary.Add(item.id, item); } await _orderContainer.UpsertItemAsync(order); } _log.LogWarning("Updated purchase"); }
public async Task <IActionResult> BuyChapter(int chapterId) { var user = await _db.ApplicationUsers.Where(u => u.Email == User.Identity.Name).FirstOrDefaultAsync(); var chapter = await _db.Chapters.Where(u => u.Id == chapterId).FirstOrDefaultAsync(); Purchased purchased = new Purchased() { ApplicationUserId = user.Id, ChapterId = chapterId, PurchaseDate = DateTime.Now, }; if (user.Balance >= chapter.Price) { _db.Purchaseds.Add(purchased); user.Balance -= chapter.Price; await _db.SaveChangesAsync(); return(RedirectToAction("ReadingChapter", "Read", new { area = "Customer", id = chapterId })); } else { return(RedirectToAction("Index", "Topup")); } }
public ActionResult DeleteConfirmed(int id) { Purchased purchased = db.PurchasedBooks.Find(id); db.PurchasedBooks.Remove(purchased); db.SaveChanges(); return(RedirectToAction("Index")); }
public SaleRecordViewModel(Purchased purchase) { Title = purchase.Book.Title; Buyer = purchase.User.UserName; Quentity = purchase.Quantity; Price = purchase.PurchasedPrice; PurchaseTime = purchase.PurchasedTime; }
private static async Task CreateLinkedPurchase(Purchased purchase) { string response = await FindAssociatedOrder(purchase); if (response != "not-found") { purchase.AssociatedOrderId = response; purchase.id = purchase.id + "linked"; await _container.CreateItemAsync(purchase); } }
private static async Task UpdatePurchases(Purchased purchase) { try { var item = await TryGetLinkedPurchase(purchase); await TryAddPurchaseToOrder(purchase, item.AssociatedOrderId); } catch (Exception e) { _log.LogInformation(e.ToString()); } }
public ActionResult Edit([Bind(Include = "Id,PurchaseId,BookId,OrderPrice,Number")] Purchased purchased) { if (ModelState.IsValid) { db.Entry(purchased).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BookId = new SelectList(db.Books, "Id", "ISBN", purchased.BookId); ViewBag.PurchaseId = new SelectList(db.Purchases, "Id", "Id", purchased.PurchaseId); return(View(purchased)); }
public ProductPurchaseDTO ToDTO() { return(new ProductPurchaseDTO { ProductId = Product.Id.ToString(), DurationMonths = Product.DurationMonths, Name = Product.Name, DateOfPurchase = Purchased.ToString("yyyy-MM-dd"), PriceUSDWhenPurchased = PriceUSDWhenPurchased, TaxUSDWhenPurchased = TaxUSDWhenPurchased, PriceUSD = Product.PriceUSD, TaxUSD = Product.TaxUSD, }); }
// GET: Purchased/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Purchased purchased = db.PurchasedBooks.Find(id); if (purchased == null) { return(HttpNotFound()); } return(View(purchased)); }
/// <summary> /// Print the object's XML to the XmlWriter. /// </summary> /// <param name="objWriter">XmlTextWriter to write with.</param> /// <param name="objCulture">Culture in which to print.</param> /// <param name="strLanguageToPrint">Language in which to print</param> public void Print(XmlTextWriter objWriter, CultureInfo objCulture, string strLanguageToPrint) { objWriter.WriteStartElement("lifestyle"); objWriter.WriteElementString("name", CustomName); objWriter.WriteElementString("cost", Cost.ToString(_objCharacter.Options.NuyenFormat, objCulture)); objWriter.WriteElementString("totalmonthlycost", TotalMonthlyCost.ToString(_objCharacter.Options.NuyenFormat, objCulture)); objWriter.WriteElementString("totalcost", TotalCost.ToString(_objCharacter.Options.NuyenFormat, objCulture)); objWriter.WriteElementString("dice", Dice.ToString(objCulture)); objWriter.WriteElementString("multiplier", Multiplier.ToString(_objCharacter.Options.NuyenFormat, objCulture)); objWriter.WriteElementString("months", Increments.ToString(objCulture)); objWriter.WriteElementString("purchased", Purchased.ToString()); objWriter.WriteElementString("type", StyleType.ToString()); objWriter.WriteElementString("increment", IncrementType.ToString()); objWriter.WriteElementString("sourceid", SourceID.ToString("D")); objWriter.WriteElementString("bonuslp", BonusLP.ToString(objCulture)); string strBaseLifestyle = string.Empty; // Retrieve the Advanced Lifestyle information if applicable. if (!string.IsNullOrEmpty(BaseLifestyle)) { XmlNode objXmlAspect = GetNode(); if (objXmlAspect != null) { strBaseLifestyle = objXmlAspect["translate"]?.InnerText ?? objXmlAspect["name"]?.InnerText ?? strBaseLifestyle; } } objWriter.WriteElementString("baselifestyle", strBaseLifestyle); objWriter.WriteElementString("trustfund", TrustFund.ToString()); objWriter.WriteElementString("source", CommonFunctions.LanguageBookShort(Source, strLanguageToPrint)); objWriter.WriteElementString("page", DisplayPage(strLanguageToPrint)); objWriter.WriteStartElement("qualities"); // Retrieve the Qualities for the Advanced Lifestyle if applicable. foreach (LifestyleQuality objQuality in LifestyleQualities) { objQuality.Print(objWriter, objCulture, strLanguageToPrint); } // Retrieve the free Grids for the Advanced Lifestyle if applicable. foreach (LifestyleQuality objQuality in FreeGrids) { objQuality.Print(objWriter, objCulture, strLanguageToPrint); } objWriter.WriteEndElement(); if (_objCharacter.Options.PrintNotes) { objWriter.WriteElementString("notes", Notes); } objWriter.WriteEndElement(); }
public DateTime GetExpirationDate() { switch (LicensingModel) { case LicensingModel.TwoDays: return Purchased.AddDays(2); case LicensingModel.LifeLong: return DateTime.MaxValue; default: throw new ArgumentOutOfRangeException(); } }
public SubscriptionDTO ToDTO() { return(new SubscriptionDTO { Id = Id.ToString(), TotalDurationMonths = TotalDurationMonths, StartDate = Purchased?.ToString("yyyy-MM-dd"), EndDate = Expires?.ToString("yyyy-MM-dd"), PurchasedProducts = ProductsPurchased.Select(purchased => purchased.ToDTO()).OrderBy(purchase => purchase.DateOfPurchase), TotalPurchaseCostUSD = TotalPurchaseCostUSD, TotalTaxCostUSD = TotalTaxCostUSD, DatePaused = ActivePause?.Started.ToString("yyyy-MM-dd") }); }
/// <summary> /// この強化の購入を要求する。 /// </summary> public override void Purchase() { if (IsPurchased) { return; } // すでに購入済み。 var game = Game.Instance; if (game.TryPurchase(Master)) { IsPurchased = true; Purchased?.Invoke(this); } }
private static async Task <string> FindAssociatedOrder(Purchased purchase) { var items = await GetOrdersFromAsin(purchase.ASIN); items = items.OrderByDescending(x => x.PurchaseDate).ToList(); _log.LogWarning(items.Count + ""); foreach (var item in items) { if (item.OrderStatus == "Cancelled") { continue; } //check if all are cancelled and the item is not damaged if (item.PurchaseDictionary != null && item.Damaged == false && !AllCancelled(item.PurchaseDictionary)) { _log.LogWarning($"Possible duplicate {item.ProductName}"); continue; } if (DateTime.Parse(item.PurchaseDate).AddHours(-DateTime.Parse(item.PurchaseDate).Hour - 1).Ticks <= purchase.OrderDate.Value.Ticks) { if (item.Damaged) { item.Damaged = false; item.DamagedNote = ""; } if (item.PurchaseDictionary == null) { item.PurchaseDictionary = new Dictionary <string, Purchased>(); } else if (item.PurchaseDictionary.ContainsKey(purchase.id)) { continue; } else if (item.PurchaseDictionary.ContainsKey(item.id)) { item.PurchaseDictionary.Remove(item.id); } item.PurchaseDictionary.Add(purchase.id, purchase); await _orderContainer.UpsertItemAsync(item); return(item.id); } } _log.LogWarning("not found"); return("not-found"); }
public override int GetHashCode() { unchecked { var hashCode = (PartitionKey != null ? PartitionKey.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (RowKey != null ? RowKey.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Timestamp.GetHashCode(); hashCode = (hashCode * 397) ^ Cost.GetHashCode(); hashCode = (hashCode * 397) ^ (Name != null ? Name.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Purchased.GetHashCode(); hashCode = (hashCode * 397) ^ Count; hashCode = (hashCode * 397) ^ GlobalGuid.GetHashCode(); hashCode = (hashCode * 397) ^ Awesomeness.GetHashCode(); return(hashCode); } }
// GET: Purchased/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Purchased purchased = db.PurchasedBooks.Find(id); if (purchased == null) { return(HttpNotFound()); } ViewBag.BookId = new SelectList(db.Books, "Id", "ISBN", purchased.BookId); ViewBag.PurchaseId = new SelectList(db.Purchases, "Id", "Id", purchased.PurchaseId); return(View(purchased)); }
public async Task <IActionResult> DetailsPost(int id) { var book = await _db.Books.Where(u => u.Id == id).Include(u => u.Author).Include(u => u.Publisher).FirstOrDefaultAsync(); var user = await _db.ApplicationUsers.Where(u => u.Email == User.Identity.Name).FirstOrDefaultAsync(); var chapterOfBook = await _db.Chapters.Where(u => u.BookId == id).ToListAsync(); var reviewOfBook = await _db.Reviews.Where(u => u.BookId == id).ToListAsync(); var commentOfBook = await _db.Comments.Where(u => u.BookId == id).ToListAsync(); var boughtChapters = await _db.Purchaseds.Where(u => u.Chapter.BookId == id && u.ApplicationUserId == user.Id).Select(u => u.Chapter).ToListAsync(); var sellingChapters = await _db.Chapters.Where(u => u.BookId == id && u.Price > 0).ToListAsync(); boughtChapters.ForEach(delegate(Chapter chapter) { sellingChapters.Remove(chapter); }); if (user.Balance >= sellingChapters.Sum(u => u.Price)) { foreach (var chapter in sellingChapters) { Purchased purchased = new Purchased() { ChapterId = chapter.Id, ApplicationUserId = user.Id, PurchaseDate = DateTime.Now }; _db.Purchaseds.Add(purchased); } user.Balance -= sellingChapters.Sum(u => u.Price); await _db.SaveChangesAsync(); return(RedirectToAction("Index", "Books", new { area = "Customer" })); } else { BooksVM.Error = "Số dư không đủ vui lòng nạp thêm"; BooksVM.Book = book; BooksVM.Chapters = chapterOfBook; BooksVM.Reviews = reviewOfBook; BooksVM.Comments = commentOfBook; } return(View(nameof(Details), BooksVM)); }
private static async Task <Purchased> TryGetLinkedPurchase(Purchased purchase) { Purchased item = new Purchased(); try { item = await _container.ReadItemAsync <Purchased>(purchase.id + "linked", new Microsoft.Azure.Cosmos.PartitionKey(purchase.ASIN)); } catch (CosmosException e) { if (e.Message.Contains("404")) { await CreateLinkedPurchase(purchase); } } return(item); }
public void MoveToPurchased(string user, ShoppingCart cart) { var cartId = cart.ShoppingCartId; var cartItems = GetCartItems(cartId); foreach (var item in cartItems) { var cartItem = new Purchased() { CartId = item.CartId, BookId = item.BookId, Quantity = item.Quantity, DateCreated = item.DateCreated, Book = item.Book }; _db.Purchased.Add(cartItem); } }
public ActionResult Purchaseds_Create([DataSourceRequest] DataSourceRequest request, Purchased purchased) { if (ModelState.IsValid) { var entity = new Purchased { BookID = purchased.BookID, UserID = purchased.UserID, Title = purchased.Title, Quantity = purchased.Quantity, PurchasedPrice = purchased.PurchasedPrice, PurchasedTime = purchased.PurchasedTime, }; db.Purchaseds.Add(entity); db.SaveChanges(); purchased.PurchasedID = entity.PurchasedID; } return(Json(new[] { purchased }.ToDataSourceResult(request, ModelState))); }
protected bool Equals(Purchase other) { // intentionally leaves out Timestamp (changed by server) return(string.Equals(PartitionKey, other.PartitionKey) && string.Equals(RowKey, other.RowKey) && Cost.Equals(other.Cost) && string.Equals(Name, other.Name) && Purchased.Equals(other.Purchased) && Count == other.Count && GlobalGuid.Equals(other.GlobalGuid) && Awesomeness.Equals(other.Awesomeness)); }
protected void Page_Load(object sender, EventArgs e) { string cid = Request.QueryString["cId"]; int readerId = 0; bool isVip = false, cantSee = false; char vStatus = '\0'; string email = HttpContext.Current.User.Identity.Name; Comic f = db.Comics.SingleOrDefault(o => o.C_Id.ToString() == cid); //f comic readers r = db.readers.SingleOrDefault(a => a.R_email == email); ComicCreator cc = db.ComicCreators.SingleOrDefault(a => a.CC_email == email); // cc comiccreator admin ad = db.admins.SingleOrDefault(a => a.A_email == email); if (r != null) { readerId = r.R_Id; } if (f != null) { hfId.Value = f.C_Id.ToString(); // Id is int lblName.Text = f.C_Title; lblD.Text = f.C_Description; vStatus = f.C_Status; isVip = f.C_IsForVip; cantSee = f.C_CantViewable; ComicCreator c = db.ComicCreators.SingleOrDefault( a => a.CC_Id == f.CC_Id); if (isVip == true) { lblVip.Visible = true; } lblAuthor.Text = c.CC_NickName; //get the discount lblPrice.Text = "RM" + f.C_Price; lblDiscount.Text = "RM" + Math.Round(f.C_Price * Convert.ToDecimal(0.9), 2); if (cantSee == true) { //cant see Response.Redirect("~/error.aspx?err=You didnt have the permission"); } if (cc != null) //Is comic creator { if (cc.CC_Id == f.CC_Id) // If the comic creator itself see it own comic { btnEdit.Visible = true; btnAddEpisode.Visible = true; btnRead.Visible = false; btnCantRead.Visible = false; btnFavourite.Visible = false; btnFavourited.Visible = false; btnPurchase.Visible = false; btnPurchased.Visible = false; lvEpisode.Visible = false; lvUpdate.Visible = true; btnStatus.Visible = true; string status = verifyStatus(f.C_Status); btnStatus.Text = status; lvCantView.Visible = false; } else //Other comic creator see ur comic { if (vStatus != 'V') { // Error page Response.Redirect("~/error.aspx?err=The result cant be found"); } //Default button btnFavourite.Visible = false; btnFavourited.Visible = false; btnPurchase.Visible = false; btnPurchased.Visible = false; btnCantRead.Visible = true; btnRead.Visible = false; lvCantView.Visible = true; lvCan.Visible = false; lvEpisode.Visible = false; lvOnlyVip.Visible = true; } } else if (r != null) // Is reader { if (r.R_isvip == true && isVip == true) // vip with comic vip { Purchased p = db.Purchaseds.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (p != null) //Is purchased { btnPurchase.Visible = false; btnPurchased.Visible = true; btnPurchased.Enabled = false; lvOnlyVip.Visible = false; lvEpisode.Visible = true; lvCantView.Visible = false; lvCan.Visible = true; } else { btnPurchase.Visible = true; btnPurchased.Visible = false; } Favourite fa = db.Favourites.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (fa != null) // Is Faourite { btnFavourite.Visible = false; btnFavourited.Visible = true; btnFavourited.Enabled = false; } else { btnFavourite.Visible = true; btnFavourited.Visible = false; } Episode ep = db.Episodes.SingleOrDefault(a => a.C_Id == f.C_Id && a.E_Id == 1); if (ep == null) //Didnt have episode { btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; } else { btnRead.Visible = true; btnCantRead.Visible = false; } } else if (r.R_isvip == true && isVip == false) // if the reader is vip and comic not vip { Purchased p = db.Purchaseds.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (p != null) //Is purchased { btnPurchase.Visible = false; btnPurchased.Visible = true; btnPurchased.Enabled = false; lblPrice.CssClass += " discount"; lblDiscount.Visible = true; lvCantView.Visible = false; lvCan.Visible = true; lvEpisode.Visible = true; lvOnlyVip.Visible = false; } else { lblPrice.CssClass += " discount"; lblDiscount.Visible = true; lvEpisode.Visible = true; lvOnlyVip.Visible = false; lvCantView.Visible = true; btnPurchase.Visible = true; btnPurchased.Visible = false; } Favourite fa = db.Favourites.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (fa != null) // Is Faourite { btnFavourite.Visible = false; btnFavourited.Visible = true; btnFavourited.Enabled = false; } else { btnFavourite.Visible = true; btnFavourited.Visible = false; } Episode ep = db.Episodes.SingleOrDefault(a => a.C_Id == f.C_Id && a.E_Id == 1); if (ep == null) //Didnt have episode { btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; } else { btnRead.Visible = true; btnCantRead.Visible = false; } } else if (r.R_isvip == false && isVip == true) { btnPurchase.Visible = false; btnPurchased.Visible = false; btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; btnFavourite.Visible = false; btnFavourited.Visible = false; lvOnlyVip.Visible = true; lvEpisode.Visible = false; lvCantView.Visible = true; lvCan.Visible = false; } else { Purchased p = db.Purchaseds.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (p != null) //Is purchased { btnPurchase.Visible = false; btnPurchased.Visible = true; btnPurchased.Enabled = false; lvOnlyVip.Visible = false; lvEpisode.Visible = true; lvCantView.Visible = false; lvCan.Visible = true; } else { btnPurchase.Visible = true; btnPurchased.Visible = false; } Favourite fa = db.Favourites.SingleOrDefault(a => a.R_Id == readerId && a.C_Id == f.C_Id); if (fa != null) // Is Faourite { btnFavourite.Visible = false; btnFavourited.Visible = true; btnFavourited.Enabled = false; } else { btnFavourite.Visible = true; btnFavourited.Visible = false; } Episode ep = db.Episodes.SingleOrDefault(a => a.C_Id == f.C_Id && a.E_Id == 1); if (ep == null) //Didnt have episode { btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; } else { btnRead.Visible = true; btnCantRead.Visible = false; } } if (vStatus != 'V') { // Error page Response.Redirect("~/error.aspx?err=The result cant be found"); } } else if (ad != null) //Admin { btnStatus.Visible = true; string status = verifyStatus(f.C_Status); btnStatus.Text = status; btnFail.Visible = true; btnVerify.Visible = true; btnUnverify.Visible = true; btnRead.Visible = false; btnCantRead.Visible = false; btnFavourite.Visible = false; btnFavourited.Visible = false; btnPurchase.Visible = false; btnPurchased.Visible = false; lvCantView.Visible = false; lvCan.Visible = true; lvEpisode.Visible = true; lvOnlyVip.Visible = false; } else { if (isVip == true) { btnPurchase.Visible = true; btnPurchased.Visible = false; btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; btnFavourite.Visible = false; btnFavourited.Visible = false; lvEpisode.Visible = false; lvOnlyVip.Visible = true; } else { Episode ep = db.Episodes.SingleOrDefault(a => a.C_Id == f.C_Id && a.E_Id == 1); if (ep == null) //Havent Favourite { btnRead.Visible = false; btnCantRead.Visible = true; btnCantRead.Enabled = false; } else { btnRead.Visible = true; btnCantRead.Visible = false; } } //Default button btnFavourite.Visible = true; btnFavourited.Visible = false; btnPurchase.Visible = true; btnPurchased.Visible = false; if (vStatus != 'V') { // Error page Response.Redirect("~/error.aspx?err=The result cant be found"); } } //Verified the available to see all or not } else { Response.Redirect("~/error.aspx?err=The result cant be found"); } }
public ActionResult CheckoutCart() { Cart cart; String userId; string uname; string SessionId = HttpContext.Session.GetString("SessionId"); if (HttpContext.Session.GetString("UserId") == null) { return(RedirectToRoute(new { controller = "Home", action = "Index" })); } else { userId = HttpContext.Session.GetString("UserId"); cart = db.Cart.Where(x => x.CustomerId == userId && x.IsCheckOut == 0).First(); cart.CustomerId = userId; db.Cart.Update(cart); uname = HttpContext.Session.GetString("Username"); ViewBag.Username = uname; ViewBag.ItemCount = GetItemCount(); db.SaveChanges(); } using (var dbTransaction = db.Database.BeginTransaction()) { try { cart = db.Cart.FirstOrDefault(x => x.CustomerId == userId && x.IsCheckOut == 0); if (cart == null) { throw new Exception("Cart not found"); } cart.CartItems = db.CartItem.Where(x => x.CartId == cart.Id).ToList(); if (cart.CartItems.Count == 0) { throw new Exception("Cart is empty"); } foreach (CartItem cartItem in cart.CartItems) { Product product = db.Products.FirstOrDefault(x => x.Id == cartItem.ProductId); if (product == null) { throw new Exception("Product not exists"); } for (int i = 0; i < cartItem.Quantity; i++) { string activationCode = GetActivationCode(); Purchased purchased = new Purchased(cartItem.Id, activationCode); db.Purchased.Add(purchased); db.SaveChanges(); } } cart.IsCheckOut = 1; cart.CheckoutTime = DateTime.Now; db.SaveChanges(); dbTransaction.Commit(); } catch (Exception e) { dbTransaction.Rollback(); throw new Exception(e.Message); } } ViewBag.cartItems = GetCartItems(cart.Id); ViewBag.ItemCount = 0; HttpContext.Session.SetInt32("cartItemCount", 0); return(View()); }
public async Task <IActionResult> Index(int id) { var claimsIdentity = (ClaimsIdentity)User.Identity; var claimsUser = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier); Purchased alreadyBought = new Purchased(); ApplicationUser user = new ApplicationUser(); ReadingHistory readingHistory = new ReadingHistory(); if (claimsUser != null) { user = await _db.ApplicationUsers.Where(u => u.Id == claimsUser.Value).FirstOrDefaultAsync(); alreadyBought = await _db.Purchaseds.Where(u => u.Chapter.BookId == id && u.ApplicationUserId == user.Id).FirstOrDefaultAsync(); readingHistory = await _db.ReadingHitories.Where(u => u.ApplicationUserId == user.Id && u.Chapter.BookId == id).FirstOrDefaultAsync(); } var book = await _db.Books.Where(u => u.Id == id).FirstOrDefaultAsync(); if (alreadyBought != null || book.BookPrice == 0 || User.IsInRole(SD.CENSOR_ROLE) || User.IsInRole(SD.ADMIN_ROLE) || User.IsInRole(SD.LIBRARIAN_ROLE)) { Chapter chapter = new Chapter(); var genres = (from a in _db.Books join b in _db.BookGenres on a.Id equals b.BookId join c in _db.Genres on b.GenresId equals c.Id where a.Id == id select c).ToList(); var chaptersOfBook = await _db.Chapters.Where(u => u.BookId == id).Include(u => u.Book).ToListAsync(); if (chaptersOfBook.Count > 0) { if (readingHistory != null) { BooksVM.Chapter = await _db.Chapters.Where(u => u.Id == readingHistory.ChapterId).FirstOrDefaultAsync(); } else { ReadingHistory history = new ReadingHistory() { ApplicationUserId = user.Id, ChapterId = chaptersOfBook[0].Id }; _db.ReadingHitories.Add(history); await _db.SaveChangesAsync(); BooksVM.Chapter = chaptersOfBook[0]; } } BooksVM.Chapters = chaptersOfBook; if (User.IsInRole(SD.CENSOR_ROLE)) { BooksVM.Chapters = chaptersOfBook.Where(u => u.Approved == false).ToList(); } BooksVM.Genres = genres; } else { BooksVM.BuyRequest = "Sách này tính phí vui lòng mua"; BooksVM.Book = book; } return(View(BooksVM)); }
public CustomerWrapper(Customer _customer) { customer = _customer; Orders.ForEach(x => Product.Add(new ProductForCustomerWrapper(x))); Purchased.ForEach(x => Product.Add(new ProductForCustomerWrapper(x))); }