private SellDto CreateRandomSell(DateTimeOffset ts, int drinkId) { var sell = new SellDto(); var rand = new Random(ts.Hour); sell.Id = 1000 * rand.Next(); sell.Fill = (uint)(1000 * rand.NextDouble() * 1.5); sell.IsCleaning = rand.NextDouble() > 0.5; sell.Price = GetPrice(drinkId); sell.Money = (uint)(((sell.Fill / 1000.0) * (sell.Price / 100.0)) * 100); sell.MoneyDelta = (uint)((rand.NextDouble() * 200) + (rand.NextDouble() * 100)); sell.IsMoneyDeltaRed = rand.NextDouble() > 0.5; sell.Ts = ts; return(sell); }
static async Task <string> sellCurrency(string currency, double amount) { HttpClient client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, API_URL + "account/sell"); SellDto contentJson = new SellDto { Symbol = currency, Amount = amount }; string serializedObject = JsonConvert.SerializeObject(contentJson); StringContent content = new StringContent(serializedObject, Encoding.UTF8, "application/json"); request.Content = content; request.Headers.Add("X-Access-Token", SECRET_KEY); HttpResponseMessage response = await client.SendAsync(request); return(response.StatusCode.ToString()); }
public void SetSellStatus(UserPass user, SellDto sell, bool isCleaning) { if (!_security.Check(user)) { throw new AuthenticationException(); } using (var context = new BeerControlEntities()) { var dbSell = context.Sell.FirstOrDefault(s => s.id == sell.Id); if (dbSell == null) { return; } dbSell.isCleaning = isCleaning; context.SaveChanges(); } }
//// <summary> /// show list view in View as Datatable jquery /// </summary> /// <returns></returns> public IActionResult List() { try { var dtValues = SetDataTableRequest(); int recordsTotal = 0; var data = _uow.SellRepo.AffiliateCustomers(dtValues.draw, dtValues.length, dtValues.sortColumn, dtValues.sortColumnDirection, dtValues.searchValue, dtValues.pageSize, dtValues.skip, ref recordsTotal, UserExtention.GetUserMail(User)); List <SellDto> list = new List <SellDto>(); foreach (var email in data) { var model = new SellDto() { Email = email }; list.Add(model); } dtValues.recordsTotal = recordsTotal; return(Json(new AjaxResult { draw = dtValues.draw, recordsFiltered = dtValues.recordsTotal, recordsTotal = dtValues.recordsTotal, data = list })); } catch (Exception ex) { return(Json("error")); } }
public void SetSellStatus(SellDto sellItem, bool isCleaning) { _clientProxyBeerData.Execute(a => a.SetSellStatus(UserPass, sellItem, isCleaning)); }
public void SetSellStatus(UserPass user, SellDto sell, bool isCleaning) { IBeerData provider = _factory.GetOrCreateProvider(user); provider.SetSellStatus(null, sell, isCleaning); }
/// <summary> /// 1- Mapping From SellDto to Sell Object . /// 2- determine Sell_State whether its Return Invoice or New Invoice . /// 3- based on Sell_State Location_Qty will be decreased or increased . /// 4- Validate that requsted qty available and selected Location are valid or loggedInUser . /// 5- Calculate { total price , total quntity } . /// </summary> /// <param name="sell">Mapping Destination </param> /// <param name="sellDto">Mapping Source </param> /// Exceptions: /// T: ApplicationException: in case un valid data for example : requsted quntity not available /// /// <returns></returns> private async Task PrepareSellObjectAsync(Sell sell, SellDto sellDto) { // Mapping Sell Object and Sell.Sell_Details Collection mapper.Map <SellDto, Sell>(sellDto, sell); sell.Sell_Details = mapper.Map <ICollection <Sell_DetailsDto>, ICollection <Sell_Details> >(sellDto.Sell_DetailsDto); //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Set Sell State {new invoice or returned invoice } // determine whether the Quantity in the Store will Increased or decrease //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- int minusOrPlus; //(1 or -1) In case (+1) mean Location_Qty will Increased in amount]|[ In Case (-1) LocationQty will decreased in amount if (sellDto.isReturn) { sell.Sell_StateId = Sell_State.Refunded; // Returned Invoice minusOrPlus = 1; // In case (+1) mean Location_Qty will Increased in amount } else { sell.Sell_StateId = Sell_State.New; // New Invoice minusOrPlus = -1; //In Case (-1) LocationQty will decrease in amount } // Products that will be Decreased or Increased in Quantity From Location based on its NewSell or Return var productsIDs = sell.Sell_Details.Select(d => d.ProductId); //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- // Get Location_Qty Entity and Product Price For each Product // { Note : i added condition to validate the location_Qty based on his Branch so user cant hack and send id for location in other branch} //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- int UserBranchId = Convert.ToInt32(User.FindFirst(ClaimName.BranchId).Value); var locationId = sell.LocationId; var DetailsQtyAndPrices = await db.Location_Qty.Where(r => productsIDs.Contains(r.ProductId) && r.LocationId == locationId && r.Location.BranchId == UserBranchId).Select(r => new { LocationQty = r, r.Product.price }).ToListAsync(); if (DetailsQtyAndPrices == null || DetailsQtyAndPrices.Count == 0) { throw new ApplicationException(localizer["QtyNotAvailableOrNotAllowedLocation"]); } //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- //1- Get Location QTy and Unit Price For Each Sell Details Item //2- Update Sell_Details Object For UnitPrice (the accepted UnitPrice from db not user form) //3- Check The Availability of Requested Quantity In Case New Invoice and subtract Quantity from the Location_Qty // (In Case Returned Invoice Location_QTy will Increased ) //4- Calculate Sell TotalPrice //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- decimal totalPrice = 0; foreach (var detailsItem in sell.Sell_Details) { var prodID = detailsItem.ProductId; var LocationQtyAndPrice = DetailsQtyAndPrices.Single(r => r.LocationQty.ProductId == prodID); detailsItem.unitPrice = LocationQtyAndPrice.price; Location_Qty LocationQTY = LocationQtyAndPrice.LocationQty; // Check the availability of Requested Quantity Just In Case New Sell Invoice if (sell.isReturn == false && LocationQTY.qty < detailsItem.qty) { throw new ApplicationException(localizer["QuantityNotAvailable"]); } LocationQTY.qty += (minusOrPlus * detailsItem.qty);// example : [20 + (1*10) = 30] and [20 + (-1*10) =10] // Calculate Details Item Total Price totalPrice += calcTotal(detailsItem.discount, detailsItem.isPercentDiscount, detailsItem.qty, detailsItem.unitPrice); } //-------------------------------------------------------------------------------------------------------------------------------------------- // Calculate Total Quantity & Calculate Total Price //-------------------------------------------------------------------------------------------------------------------------------------------- sell.totalQty = sell.Sell_Details.Select(r => r.qty).Sum(); decimal TaxAmount = (sell.isPercentTax) ? ((totalPrice * sell.tax) / 100) : sell.tax; totalPrice += decimal.Round(TaxAmount, 2); decimal GlobalDiscountAmount = (sell.isPercentDiscount) ? ((totalPrice * sell.discount) / 100) : sell.discount; totalPrice -= decimal.Round(GlobalDiscountAmount, 2); sell.totalPrice = totalPrice; //-------------------------------------------------------------------------------------------------------------------------------------------- }
public async Task <IActionResult> Edit(SellDto sellDto) { try { if (!ModelState.IsValid) { // Get All Model Errors and Join Them in One Sting Seperated by coma "," var aLLmsg = Global.ModelErrorsToJoinString(ModelState, ","); throw new ApplicationException(aLLmsg); } int UserBranchId = Convert.ToInt32(User.FindFirst(ClaimName.BranchId).Value); // Get Sell&Sell_Details Obj From DB where 1- sell not deleted 2- sell belongs to user Branch Sell sellToUpdate = await db.Sells.Include(s => s.Sell_Details).FirstOrDefaultAsync(s => s.sellId == sellDto.sellId && s.isDeleted != true && s.Location.BranchId == UserBranchId); if (sellToUpdate == null) { return(NotFound()); } await ResetLocationQtyAsync(sellToUpdate); // Delete Sell_Details db.Sell_Details.RemoveRange(sellToUpdate.Sell_Details); // Clear old Sell_Details from object to add New Sell_Details sellToUpdate.Sell_Details = null; // Mapping Sell Object and Sell_Details Object and Apply business requirements // Note maybe throw ApplicationException: in case un valid data for example : requsted quntity not available await PrepareSellObjectAsync(sellToUpdate, sellDto); //-------------------------------------------------------------------------------------------------------------------------------------------- // Upload Sell Document {Note: the file was Validated by DataAnnotation in DTO model} (Note: Uploade Operation must come after all Validation) //-------------------------------------------------------------------------------------------------------------------------------------------- if (sellDto.docment != null && sellDto.docment.Length != 0) { // path for Old Document for This Sell Invoice string deletedPath = Path.Combine(hostingEnvironment.WebRootPath, sellToUpdate.docment); // Uploade New Document sellToUpdate.docment = await FileManager.UploadFileAsync(sellDto.docment, hostingEnvironment.WebRootPath, FileSettings.SellDirectory); //Delete Old Document FileManager.RemoveFileFromServer(deletedPath); } //-------------------------------------------------------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------------------------------------------------------- // AuditTrial => Log Update Operation To DataBase //-------------------------------------------------------------------------------------------------------------------------------------------- AuditTrial aditTrail = new AuditTrial() { actionDate = DateTime.UtcNow, ActionId = Models.Action.Update, // This will Throw Exception in case a ControllerName not Match one of Pages Enum Member PageId = Convert.ToInt32(Enum.Parse(typeof(Page.Pages), ControllerContext.ActionDescriptor.ControllerName.ToLower())), recordId = sellToUpdate.sellId, UserId = Convert.ToInt64(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value) }; await db.AuditTrials.AddAsync(aditTrail); //-------------------------------------------------------------------------------------------------------------------------------------------- await db.SaveChangesAsync(); return(Json(new { isError = 0, msg = localizer["SavedSuccessfully"] })); } catch (ApplicationException ex) { return(Json(new { isError = 1, msg = ex.Message })); } catch (DbUpdateException ex) { Global.LogException(HttpContext, ex); return(Json(new { isError = 1, msg = localizer["UnableToSaveTryAgainOrCallUs"] })); } // Create New Sell_Details // Use New Sell_Details to Update Location_Qty {Decrease Operation} // Update Sell Obj Values // Insert Aduit Trails {Update Action} }
public async Task <IActionResult> Add(SellDto sellDto) { try { if (!ModelState.IsValid) { // Get All Model Errors and Join Them in One Sting Seperated by coma "," var aLLmsg = Global.ModelErrorsToJoinString(ModelState, ","); throw new ApplicationException(aLLmsg); } Sell sell = new Sell(); // Mapping Sell Object and Sell_Details Object and Apply business requirements // Note maybe throw ApplicationException: in case un valid data for example : requsted quntity not available await PrepareSellObjectAsync(sell, sellDto); //-------------------------------------------------------------------------------------------------------------------------------------------- // Upload Sell Document {Note: the file was Validated by DataAnnotation in DTO model} (Note: Uploade Operation must come after all Validation) //-------------------------------------------------------------------------------------------------------------------------------------------- if (sellDto.docment != null && sellDto.docment.Length != 0) { sell.docment = await FileManager.UploadFileAsync(sellDto.docment, hostingEnvironment.WebRootPath, FileSettings.SellDirectory); } //-------------------------------------------------------------------------------------------------------------------------------------------- using (var transaction = db.Database.BeginTransaction()) { //-------------------------------------------------------------------------------------------------------------------------------------------- // Insert Sell Object To DataBase //-------------------------------------------------------------------------------------------------------------------------------------------- db.Sells.Add(sell); await db.SaveChangesAsync(); //-------------------------------------------------------------------------------------------------------------------------------------------- // AuditTrial => Log Insert Operation To DataBase //-------------------------------------------------------------------------------------------------------------------------------------------- AuditTrial aditTrail = new AuditTrial() { actionDate = DateTime.UtcNow, ActionId = Models.Action.Create, // This will Throw Exception in case a ControllerName not Match one of Pages Enum Member PageId = Convert.ToInt32(Enum.Parse(typeof(Page.Pages), ControllerContext.ActionDescriptor.ControllerName.ToLower())), recordId = sell.sellId, UserId = Convert.ToInt64(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier).Value) }; await db.AuditTrials.AddAsync(aditTrail); await db.SaveChangesAsync(); //-------------------------------------------------------------------------------------------------------------------------------------------- //throw new Exception(); transaction.Commit(); } return(Json(new { isError = 0, msg = localizer["SavedSuccessfully"] })); } catch (ApplicationException ex) { return(Json(new { isError = 1, msg = ex.Message })); } catch (DbUpdateException ex) { Global.LogException(HttpContext, ex); return(Json(new { isError = 1, msg = localizer["UnableToSaveTryAgainOrCallUs"] })); } catch (Exception ex) { Global.LogException(HttpContext, ex); return(Json(new { isError = 1, msg = ex.Message })); } }
public void SetSellStatus(UserPass user, SellDto sell, bool isCleaning) { return; }