public void DeleteClientCart(ClientCart clientCart) { // Delete backup file string filename = BuildClientFilename(clientCart); File.Delete(filename); }
public List <ClientCart> GetClientCarts() { List <Exception> exceptions = null; List <ClientCart> carts = new List <ClientCart>(); string path = PPCConfigurationManager.BackupPath; if (Directory.Exists(path)) { foreach (string filename in Directory.EnumerateFiles(path, "*.xml", SearchOption.TopDirectoryOnly).Where(x => !x.Contains(ShopFilename) && !x.Contains(NotesFilename))) { try { ClientCart cart = LoadClient(filename); carts.Add(cart); } catch (Exception ex) { // TODO: logging exceptions = exceptions ?? new List <Exception>(); exceptions.Add(new Exception($"Error while loading {filename ?? "??"} cart", ex)); } } } if (exceptions != null) { throw new GetClientCartsException(carts, exceptions); } return(carts); }
public ClientCart Update(int id, ClientCart cartToUpdate) { ClientCart currentCart = _context.ClientCart.SingleOrDefault(cart => cart.Id == id); currentCart.Products = cartToUpdate.Products; return(currentCart); }
public void SaveClientCart(ClientCart clientCart) { if (!Directory.Exists(PPCConfigurationManager.BackupPath)) { Directory.CreateDirectory(PPCConfigurationManager.BackupPath); } string filename = BuildClientFilename(clientCart); DataContractHelpers.Write(filename, clientCart); }
//bấm nút mua sẽ thêm vào được giỏ hàng public ActionResult AddCIFromListProduct(int proId, int catId, int page) { if (Session["cart"] == null) { Session["cart"] = new ClientCart(); } var c = Session["cart"] as ClientCart; c = CSDLQLBH.InsertCartItem(c, proId); return(RedirectToAction("GetListByCategory", "Product", new { id = catId, page = page })); }
//bấm nút mua sẽ thêm vào được giỏ hàng public ActionResult AddCIFromIndex(int proId) { if (Session["cart"] == null) { Session["cart"] = new ClientCart(); } var c = Session["cart"] as ClientCart; c = CSDLQLBH.InsertCartItem(c, proId); return(RedirectToAction("Index", "Home")); }
public ActionResult Add(int proId, int quantity) { if (Session["cart"] == null) { Session["cart"] = new ClientCart(); } var c = Session["cart"] as ClientCart; c = CSDLQLBH.InsertCartItem(c, proId, quantity); return(RedirectToAction("Detail", "Product", new { id = proId })); }
public async Task <ClientCart> UpdateCartAsync(ClientCart clientCart) { var created = await _database.StringSetAsync(clientCart.Id, JsonSerializer.Serialize(clientCart), TimeSpan.FromDays(2)); if (!created) { return(null); } return(await GetCartAsync(clientCart.Id)); }
/// <summary> /// Inserts the specified authenticated user's cart into the cache memory. /// </summary> /// <param name="userId">The id of the authenticated user.</param> /// <param name="userCart">The authenticated user's cart to cache.</param> private void CacheAuthUserCart(int userId, ClientCart userCart) { if (userCart == null) { throw new ArgumentNullException(nameof(userCart), $"{nameof(userCart)} cannot be null."); } _cache.Set($"{CACHE_IDENTIFIER}_user_{userId}", userCart, new MemoryCacheEntryOptions() { SlidingExpiration = TimeSpan.FromMinutes(30) }); }
/// <summary> /// Inserts the specified client's cart into the cache memory. /// </summary> /// <param name="clientCart">The client's cart to cache.</param> private void CacheClientCart(ClientCart clientCart) { if (clientCart == null) { throw new ArgumentNullException(nameof(clientCart), $"{nameof(clientCart)} cannot be null."); } _cache.Set($"{CACHE_IDENTIFIER}_{clientCart.Id}", clientCart, new MemoryCacheEntryOptions() { SlidingExpiration = TimeSpan.FromMinutes(30) }); }
/// <summary> /// Initializes the client's cart, either from the database (if user is authenticated) or the cookie. /// </summary> /// <remarks>Using memory cache for performance improvments.</remarks> private void InitializeClientCart() { ClientCart clientCart = null; // (1) - Checks if the user is authenticated - then gets the cart from the DB: if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) { // First checks if the cart is in the cache memory: int? userId = _httpContextAccessor.HttpContext.User.Identity.GetId(); ClientCart userCart; if (_cache.TryGetValue($"{CACHE_IDENTIFIER}_user_{userId.Value}", out userCart)) { clientCart = userCart; } else { clientCart = Task.Run(() => GetAuthUserCartByDatabase()).Result; // Inserts the user's cart into cache: if (clientCart != null) { this.CacheAuthUserCart(userId.Value, clientCart); } } } // (2) - User is not authenticated - so gets the cart from the cookie: if (clientCart == null) { // First checks if the cart is in the cache memory: int?cartId = this.GetUserCartIdByCookie(); if (cartId.HasValue) { ClientCart cCart; if (_cache.TryGetValue($"{CACHE_IDENTIFIER}_{cartId.Value}", out cCart)) { clientCart = cCart; } else { clientCart = Task.Run(() => GetClientCartByDatabase(cartId.Value)).Result; // Inserts the client's cart into cache: if (clientCart != null) { this.CacheClientCart(clientCart); } } } } // Assigns the cart found to the current scope: this.Cart = clientCart; }
public void SaveClientCart(ClientCart clientCart) { //https://stackoverflow.com/questions/38839260/update-property-in-nested-array-of-entities-in-mongodb // Try to update var filter = Builders <Session> .Filter; var clientCartIdAndSessionIdFilter = filter.Eq(x => x.Guid, _activeSessionId) & filter.ElemMatch(x => x.ClientCarts, x => x.Guid == clientCart.Guid); UpdateResult updateResult = SessionsCollection.UpdateOne(clientCartIdAndSessionIdFilter, Builders <Session> .Update.Set(x => x.ClientCarts[-1], clientCart)); // Update failed -> insert if (updateResult.ModifiedCount == 0) { SessionsCollection.UpdateOne(x => x.Guid == _activeSessionId, Builders <Session> .Update.Push(x => x.ClientCarts, clientCart)); } }
public static ClientCart RemoveCartItem(ClientCart cart, int proId) { try { var endPointString = endPointQLBH + "api/carts/Delete/Item?productId=" + proId; var cartUpdate = Task.Run(() => PutAsync <ClientCart>(endPointString, cart)).Result; return(cartUpdate); } catch (BusinessLayerException) { throw new BusinessLayerException(500, "#1001002 Cập nhật giỏ hàng thất bại."); } catch (Exception) { throw new BusinessLayerException(500, "#1001003 Cập nhật giỏ hàng thất bại."); } }
public static ClientCart Checkout(ClientCart cart) { try { var endPointString = endPointQLBH + "api/carts/Checkout"; var cartCheckout = Task.Run(() => PostAsync <ClientCart>(endPointString, cart)).Result; return(cartCheckout); } catch (BusinessLayerException) { throw new BusinessLayerException(500, "#1001002 Cập nhật giỏ hàng thất bại."); } catch (Exception) { throw new BusinessLayerException(500, "#1001003 Cập nhật giỏ hàng thất bại."); } }
public static ClientCart InsertCartItem(ClientCart cart, int proId, int quantity = 1) { try { var endPointString = endPointQLBH + "api/carts/Add/Item?productId=" + proId + "&quantity=" + quantity; var cartUpdate = Task.Run(() => PostAsync <ClientCart>(endPointString, cart)).Result; return(cartUpdate); } catch (BusinessLayerException) { throw new BusinessLayerException(500, "#1001002 Cập nhật giỏ hàng thất bại."); } catch (Exception) { throw new BusinessLayerException(500, "#1001003 Cập nhật giỏ hàng thất bại."); } }
/// <summary> /// Deletes the specified user. /// </summary> /// <param name="userId">The id of the user to delete.</param> /// <returns>Returns true if the delete has succeeded, otherwise false.</returns> public async Task <bool> DeleteUser(int userId) { User user = await this.GetByIdAsync(userId); if (user.ClientCartId.HasValue) { ClientCart cart = await _dbContext.ClientCarts.FindAsync(user.ClientCartId.Value); _dbContext.ClientCarts.Remove(cart); } if (user.Address != null) { _dbContext.Addresses.Remove(user.Address); } _dbContext.Users.Remove(user); await _dbContext.SaveChangesAsync(); _userCache.Remove(user.Id); return(true); }
public void GetClients(ClientCart client) { _medContext.UpdateClient(client); }
public async Task <ActionResult <ClientCart> > UpdateCart(ClientCart cart) { var updatedBasket = await _cartRepository.UpdateCartAsync(cart); return(Ok(updatedBasket)); }
public void AddClient(ClientCart client) { Clients.Add(client); }
public void UpdateClient(ClientCart client) { Clients.Update(client); }
/// <summary> /// Sets (adds or updates) the specified product and quantity in the cart. /// </summary> /// <param name="productId">The id of the product to set.</param> /// <param name="quantity">The quantity to set.</param> public async Task SetProductAsync(int productId, int quantity) { if (quantity < 1) { throw new ArgumentException($"{nameof(quantity)} cannot be less than 1.", nameof(quantity)); } // First, checks the product exists and valid in the database: if (!await _dbContext.Products.AnyAsync(p => p.Id == productId && p.IsAvailable)) { return; } // Creates/Updates the cart: // Now, checks if it's the first item in the cart: if (this.IsEmpty()) { // So creates a new cart: this.Cart = new ClientCart(); this.Cart.Products = new List <ClientCartProduct>(); ClientCartProduct cartProduct = new ClientCartProduct() { ClientCart = Cart, ProductId = productId, Quantity = quantity }; this.Cart.Products.Add(cartProduct); _dbContext.ClientCarts.Add(this.Cart); } // Otherwise, it's not the first item: else { // Checks if the product already exists in the cart: ClientCartProduct cartProduct = this.Cart.Products.FirstOrDefault(p => p.ProductId == productId); if (cartProduct != null) { // Updates the item: cartProduct.Quantity = quantity; _dbContext.ClientCartProducts.Update(cartProduct); } else { // Adds the item: cartProduct = new ClientCartProduct() { ClientCartId = this.Cart.Id, ProductId = productId, Quantity = quantity }; _dbContext.ClientCartProducts.Add(cartProduct); } } // If the user is authenticated - connects the cart to him: User user = await _userIdentity.GetCurrentAsync(); if (user != null && user.ClientCartId == null) { user.ClientCart = this.Cart; _dbContext.Users.Update(user); } await _dbContext.SaveChangesAsync(); // Gets the cart back from the database: ClientCart clientCartBack = null; if (user != null) { clientCartBack = Task.Run(() => GetAuthUserCartByDatabase()).Result; user.ClientCartId = clientCartBack.Id; _userCache.Set(user); this.CacheAuthUserCart(user.Id, clientCartBack); } else { clientCartBack = Task.Run(() => GetClientCartByDatabase(this.Cart.Id)).Result; this.CacheClientCart(clientCartBack); } // If user is anonymous - sets his cart id to the cookie: if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated == false) { this.SetUserCartIdToCookie(this.Cart.Id); } }
public void PutProductInCart(int id, int clientId, [FromBody] ProductsAndShoopingCartViewModel productOnCart) { var clientCart = _context.ClientCart.Include(c => c.Products).SingleOrDefault(); if (clientCart != null) { var productExist = clientCart.Products.SingleOrDefault(c => c.ProductId == id); if (productExist != null) { productExist.Quantity++; var product = _context.Products.SingleOrDefault(p => p.ProductId == id); productExist.TotalPricePerProduct = product.Price * productExist.Quantity; } else { var product = _context.Products.SingleOrDefault(p => p.ProductId == id); productExist = new ProductsOnCart { Product = product, ClientCartId = clientCart.Id, Quantity = 1.0, TotalPricePerProduct = product.Price * 1, }; clientCart.Products.Add(productExist); } double?total = 0.0; foreach (var product in clientCart.Products) { total = total + product.TotalPricePerProduct; } clientCart.TotalPriceOfCartForUser = total; _context.SaveChanges(); } else { var product = _context.Products.SingleOrDefault(p => p.ProductId == id); var newCartOfClient = new ClientCart { ClientAccoundId = clientId, TotalPriceOfCartForUser = product.Price * 1.0 }; var cartWithNoProductsInIt = new ProductsOnCart { ClientCartId = newCartOfClient.Id, ClientCart = newCartOfClient, Product = product, ProductId = id, Quantity = 1.0, TotalPricePerProduct = product.Price * 1.0 }; _context.Add(newCartOfClient); _context.Add(cartWithNoProductsInIt); _context.SaveChanges(); //trebuie verificat } }
public void RemoveClient(ClientCart client) { Clients.Remove(client); }
private ClientCart LoadClient(string filename) { ClientCart cart = DataContractHelpers.Read <ClientCart>(filename); return(cart); }
public string AddingClientCart(ClientCart client) { _medContext.AddClient(client); return(null); }
public CustomJsonResult Operate(string operater, string clientUserId, RopCartOperate rop) { var result = new CustomJsonResult(); if (rop.ProductSkus == null || rop.ProductSkus.Count == 0) { return(new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "选择商品为空")); } lock (lock_Operate) { using (TransactionScope ts = new TransactionScope()) { foreach (var item in rop.ProductSkus) { var clientCart = CurrentDb.ClientCart.Where(m => m.ClientUserId == clientUserId && m.StoreId == rop.StoreId && m.PrdProductSkuId == item.Id && m.ReceptionMode == item.ReceptionMode && m.Status == E_ClientCartStatus.WaitSettle).FirstOrDefault(); switch (rop.Operate) { case E_CartOperateType.Selected: clientCart.Selected = item.Selected; break; case E_CartOperateType.Decrease: if (clientCart.Quantity >= 2) { clientCart.Quantity -= 1; clientCart.MendTime = DateTime.Now; clientCart.Mender = operater; } break; case E_CartOperateType.Increase: if (clientCart == null) { var productSku = CurrentDb.PrdProductSku.Where(m => m.Id == item.Id).FirstOrDefault(); var store = CurrentDb.Store.Where(m => m.Id == rop.StoreId).FirstOrDefault(); clientCart = new ClientCart(); clientCart.Id = GuidUtil.New(); clientCart.ClientUserId = clientUserId; clientCart.MerchId = store.MerchId; clientCart.StoreId = rop.StoreId; clientCart.PrdProductId = productSku.PrdProductId; clientCart.PrdProductSkuId = item.Id; clientCart.Selected = true; clientCart.CreateTime = DateTime.Now; clientCart.Creator = operater; clientCart.Quantity = 1; clientCart.ReceptionMode = item.ReceptionMode; clientCart.Status = E_ClientCartStatus.WaitSettle; CurrentDb.ClientCart.Add(clientCart); } else { clientCart.Quantity += 1; clientCart.MendTime = DateTime.Now; clientCart.Mender = operater; } break; case E_CartOperateType.Delete: clientCart.Status = E_ClientCartStatus.Deleted; clientCart.MendTime = DateTime.Now; clientCart.Mender = operater; break; } } CurrentDb.SaveChanges(); ts.Complete(); result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "操作成功"); } } return(result); }
public void DeleteClientCart(ClientCart clientCart) { SessionsCollection.UpdateOne(x => x.Guid == _activeSessionId, Builders <Session> .Update.PullFilter(x => x.ClientCarts, x => x.Guid == clientCart.Guid)); }