public async Task <IActionResult> Register([FromBody] PurchaseDTO purchase) { try { _logger.LogInformation("register purchase of currency"); Currencies currencyVal = _getCurrency(purchase.Currency); var quotation = await _quotationRepository.GetQuotation(currencyVal); var value = await UpdateAmount(purchase.Amount, quotation, currencyVal); if (!CheckAmountLimits(value, currencyVal, purchase.UserId)) { return(BadRequest(new InternalServerError("El limite de compra se ha excedido"))); } var purchaseEntity = new Purchase() { Amount = purchase.Amount, Value = value, UserId = purchase.UserId, Currency = purchase.Currency }; await _purchaseRepository.Add(purchaseEntity); return(Ok(purchaseEntity)); } catch (Exception e) { _logger.LogError("error: " + e.Message); return(StatusCode(500, "Internal server error")); } }
public ActionResult Add([FromBody] PurchaseDTO purchaseDTO) { var purchase = purchaseDTO.getPurchase(GetUserId()); _purchaseRepository.Add(purchase); return(Created("", purchase)); }
public async Task <OperationDetails <PurchaseDTO> > GetPurchaseById(int purchaseId) { OperationDetails <PurchaseDTO> operationDetails = new OperationDetails <PurchaseDTO>(false, "Что-то пошло не так, проверте данные и повториет позже", new PurchaseDTO()); if (purchaseId <= 0) { return(operationDetails); } var purchase = await _uof.PurchaseRepository.FindPurchaseByIdAsync(purchaseId); if (purchase == null) { return(operationDetails); } var pruchaseDTO = new PurchaseDTO { PurchaseId = purchase.PurchaseId, TotalCost = purchase.TotalCost, DateOfPayment = purchase.DateOfPayment, StartDateService = purchase.StartDateService, EndDateService = purchase.EndDateService, IsPayed = purchase.IsPayed, ServicesId = purchase.ServicesId, AdId = purchase.AdId }; operationDetails = new OperationDetails <PurchaseDTO>(true, "", pruchaseDTO); return(operationDetails); }
public async Task <ActionResult> Post(PurchaseDTO purchase) { try { var reslult = await _purchaseService.CreatePurchase(purchase); if (reslult != null) { _logger.LogInformation($"Post : Success. User: {purchase.UserId}. Currency {purchase.ISOCurrencyCode}. Amount: {purchase.AmountARGCurrency}"); return(Ok(purchase)); } else { _logger.LogInformation($"Post : Purchase limit exceeded. User: {purchase.UserId}. Currency {purchase.ISOCurrencyCode}. Amount: {purchase.AmountARGCurrency}."); return(Unauthorized()); } } catch (ArgumentException) { _logger.LogInformation($"Post : Error for Currency {purchase.ISOCurrencyCode}. User: {purchase.UserId}"); return(NotFound()); } catch (Exception ex) { _logger.LogError($"Post : Error creating Purchase. User: {purchase.UserId}, Currency: {purchase.ISOCurrencyCode}, Amount: {purchase.AmountARGCurrency}. Error message: {ex.Message}"); return(NoContent()); } }
public async Task <IActionResult> PutPurchase(int id, PurchaseDTO PurchaseDTO) { if (id != PurchaseDTO.ID) { return(BadRequest()); } _context.Entry(PurchaseDTO).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PurchaseExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public string Create(EmailType type, PurchaseDTO purchase) { string products = PrepareProducts(purchase.Products); string body = PrepareBody(type, purchase); body = body.Replace(@"<<products>>", products); return(body); }
public async Task UpdateItem(PurchaseDTO purchaseDTO) { var purchase = _mapper.Map <Purchase>(purchaseDTO); _dbContext.Purchases.Update(purchase); await _dbContext.SaveChangesAsync(); }
public async Task InsertItem(PurchaseDTO purchaseDTO) { var purchase = _mapper.Map <Purchase>(purchaseDTO); _dbContext.Purchases.Add(purchase); await _dbContext.SaveChangesAsync(); }
public void AddPurchase(PurchaseDTO p) { repository.AddPurchase(new Purchase { UserId = p.UserId, EventSeatId = p.EventSeatId }); }
/// <summary> /// Actualiza un Purchase por medio del id /// </summary> public void Update(string id, PurchaseDTO entity) { using (var dbContextScope = new TiendaDbContext()) { _repository.Update(this.GetEntity(entity), id); dbContextScope.SaveChanges(); } }
public ActionResult Update([FromBody] PurchaseDTO purchaseDTO, int purchaseId) { var purchase = purchaseDTO.getPurchase(GetUserId()); purchase.Id = purchaseId; _purchaseRepository.Update(purchase); return(Ok()); }
private BLLStandard.DTO.PurchaseDTO FromWcfPurchaseDTOToBllPurchaseDTO(PurchaseDTO wcfPurchaseDTO) { return(new BLLStandard.DTO.PurchaseDTO() { Id = wcfPurchaseDTO.Id, UserId = wcfPurchaseDTO.UserId, EventSeatId = wcfPurchaseDTO.EventSeatId }); }
// POST: api/Purchase public IHttpActionResult Post([FromBody] PurchaseDTO dto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } _purchaseService.AddPurchase(dto); return(Ok()); }
/// <summary> /// Metodo que dada una entidad devuelve su DTO /// </summary> /// <param name="entity">Entidad de la cual se requiere el DTO</param> /// <returns>DTO para la entidad pasada por parametro</returns> private PurchaseDTO GetDTO(Purchase entity) { PurchaseDTO dto = new PurchaseDTO(); dto.PurchaseId = entity.PurchaseId; this.SetDTOExtras(entity, ref dto); return(dto); }
/// <summary> /// Servicio que permite insertar una nueva entidad: Purchase (Purchase) /// </summary> /// <param name="entity">DTO de la entidad a insertar</param> /// <param name="user">Usuario que ejecuta la inserción</param> /// <returns>Se devulve el DTO de la entidad creada con el id asignado</returns> public PurchaseDTO Insert(PurchaseDTO dto, string user) { using (var dbContextScope = new TiendaDbContext()) { Purchase entity = GetEntity(dto); entity = _repository.Insert(entity, user); dbContextScope.SaveChanges(); return(GetDTO(entity)); } }
public async Task <OperationDetails <int> > UpdatePurchase(PurchaseDTO purchase) { OperationDetails <int> operationDetails = new OperationDetails <int>(false, "Что-то пошло не так, проверте данные и повториет позже", 0); if (purchase.AdId <= 0) { return(operationDetails); } var ad = await _uof.AdRepository.FindAdByIdAsync(purchase.AdId); if (ad == null) { return(operationDetails); } var oldService = await _uof.ServiceRepository.FindServiceByIdAsync(purchase.ServicesId); if (oldService == null) { return(operationDetails); } var oldPurchase = await _uof.PurchaseRepository.FindPurchaseByIdAsync(purchase.PurchaseId); if (oldPurchase == null) { return(operationDetails); } oldPurchase.TotalCost = purchase.TotalCost; oldPurchase.DateOfPayment = purchase.DateOfPayment; oldPurchase.StartDateService = purchase.StartDateService; oldPurchase.EndDateService = purchase.EndDateService; oldPurchase.IsPayed = purchase.IsPayed; oldPurchase.ServicesId = purchase.ServicesId; oldPurchase.IsActive = purchase.IsActive; oldPurchase.AdId = purchase.AdId; try { await _uof.PurchaseRepository.UpdatePurchase(oldPurchase); operationDetails = new OperationDetails <int>(true, "", oldPurchase.PurchaseId); } catch (Exception ex) { operationDetails = new OperationDetails <int>(false, ex.Message, 0); } return(operationDetails); }
public async Task CreatePurchase(PurchaseDTO model) { try { var item = await _uow.Items.Query() .Where(s => s.ItemId == model.ItemId) .Include(s => s.Purchases) .FirstOrDefaultAsync(); decimal?sumprice = 0; foreach (var purch in item.Purchases) { sumprice += purch.Price * purch.Count; } if (model.IsSale == false) { item.AllBuyCount = item.AllBuyCount + model.Count; item.AvgBuyPrice = (sumprice + (model.Price * model.Count)) / item.AllBuyCount; item.SumBuyPrice = sumprice + (model.Price * model.Count); } else { item.AllBuyCount = item.AllBuyCount - model.Count; item.AvgBuyPrice = (sumprice - (model.Price * model.Count)) / item.AllBuyCount; item.SumBuyPrice = sumprice - (model.Price * model.Count); } _uow.Items.Update(item); var newpurchase = _mapper.Map <Purchase>(model); _uow.Purchases.Add(newpurchase); await _uow.SaveChangesAsync(); var portfolio = await _uow.Items.Query() .Where(s => s.ItemId == model.ItemId) .Include(s => s.Portfolio) .Select(s => s.Portfolio) .FirstOrDefaultAsync(); if (model.IsSale == false) { portfolio.Balance -= model.Price * model.Count; } else { portfolio.Balance += model.Price * model.Count; } _uow.Portfolios.Update(portfolio); await _uow.SaveChangesAsync(); } catch (Exception ex) { throw; } }
public JsonResult Create(PurchaseDTO purchase) { if (ModelState.IsValid) { var isSuccess = _unitOfWork.MakePurchase(purchase); if (isSuccess) { return(Json(new { success = true }, JsonRequestBehavior.AllowGet)); } } return(Json(new { success = false, message = "Invalid purchase operation!" }, JsonRequestBehavior.AllowGet)); }
public ActionResult Edit(int id, PurchaseDTO dto) { try { // TODO: Add update logic here bool result = purchaseDa.Update(id, dto); return(RedirectToAction("Index")); } catch { return(View()); } }
public IActionResult purchase(PurchaseDTO purchaseDTO) { SalesManager salesManager = new SalesManager(); bool judge = salesManager.purchase(purchaseDTO); if (judge) { return(Ok(JsonCreate.newInstance(ConstMessage.INSERT_SUCCESS, judge))); } else { return(Conflict(JsonCreate.newInstance(ConstMessage.CONFILICT, judge))); } }
public PurchaseGet Post(PurchasePost post) { var purchaseDTO = new PurchaseDTO(post); m_Context.Purchases.Add(purchaseDTO); m_Context.SaveChanges(); if (purchaseDTO == null) { return(null); } return(new PurchaseGet(m_Context, purchaseDTO)); }
public async Task <ActionResult> PostPurchase(PurchaseDTO purchaseDTO) { try { await _service.InsertItem(purchaseDTO); return(CreatedAtAction("GetPurchase", new { id = purchaseDTO.PurchaseId }, purchaseDTO)); } catch (Exception ex) { Log.LogError($"Chyba při ukládání do databáze: {ex.InnerException}"); return(NotFound()); } }
public ActionResult Create(PurchaseDTO dto) { var merchants = merchantDa.GetAllMerchant(); ViewData["merchants"] = merchants; try { bool result = purchaseDa.Save(dto); return(RedirectToAction("Index")); } catch { return(View()); } }
public async Task <OperationDetails <int> > CreatePurchase(PurchaseDTO purchase) { OperationDetails <int> operationDetails = new OperationDetails <int>(false, "Что-то пошло не так, проверте данные и повториет позже", 0); if (purchase.AdId <= 0) { return(operationDetails); } var ad = await _uof.AdRepository.FindAdByIdAsync(purchase.AdId); if (ad == null) { return(operationDetails); } var service = await _uof.ServiceRepository.FindServiceByIdAsync(purchase.ServicesId); if (service == null) { return(operationDetails); } Purchase newPurchase = new Purchase { TotalCost = purchase.TotalCost, DateOfPayment = purchase.DateOfPayment, StartDateService = purchase.StartDateService, EndDateService = purchase.EndDateService, IsPayed = purchase.IsPayed, ServicesId = purchase.ServicesId, AdId = purchase.AdId }; try { newPurchase.PurchaseId = await _uof.PurchaseRepository.AddPurchaseAsync(newPurchase); operationDetails = new OperationDetails <int>(true, "", newPurchase.PurchaseId); } catch (Exception ex) { operationDetails = new OperationDetails <int>(false, ex.Message, 0); } return(operationDetails); }
public async Task <IActionResult> SubmitPurchase(PurchaseViewModel purchase) { var mapper = MapperService.CreateFilmViewModelToFilmDTOMapper(); PurchaseDTO purchaseDTO = mapper.Map <PurchaseViewModel, PurchaseDTO>(purchase); await _adminService.SavePurchaseAsync(purchaseDTO); TempData["message"] = $"Purchase #{purchase.Id}. Status: {purchase.Status}."; if (purchase.Status != Status.Pending) { await _emailSender.SendEmailAsync(purchase.Customer.User.Email, "Purchase status", $"Your purchase #{purchase.Id} was {purchase.Status}"); } return(RedirectToAction("Purchases")); }
public JsonResult UpdatePurchase(PurchaseDTO dto) { PurchaseDTO result = null; try { var entity = UnitOfWork.TblPurchase.Get(dto.id); if (entity != null) { entity.purch_plant_id = dto.purch_plant_id; entity.purch_aqsn_cost = dto.purch_aqsn_cost; entity.purch_currncy_id = dto.purch_currncy_id; entity.purch_puom = dto.purch_puom; entity.purch_suom = dto.purch_suom; entity.purch_uuom = dto.purch_uuom; entity.purch_puom_qty = dto.purch_puom_qty; entity.purch_suom_qty = dto.purch_suom_qty; entity.purch_uuom_qty = dto.purch_uuom_qty; entity.purch_VAT_refund = dto.purch_VAT_refund; entity.purch_inbnd_fgt = dto.purch_inbnd_fgt; entity.purch_import_duty = dto.purch_import_duty; entity.purch_cost_type_id = dto.purch_cost_type_id; entity.purch_eoq_min = dto.purch_eoq_min; entity.purch_eoq_max = dto.purch_eoq_max; entity.purch_cartn_lgt = dto.purch_cartn_lgt; entity.purch_cartn_wdt = dto.purch_cartn_wdt; entity.purch_cartn_hgt = dto.purch_cartn_hgt; entity.purch_cartn_wgt = dto.purch_cartn_wgt; entity.purch_lead_time = dto.purch_lead_time; entity.purch_scrap = dto.purch_scrap; entity.purch_expry = dto.purch_expry; entity.purch_date_expry = dto.purch_date_expry; UnitOfWork.Save(); result = Mapper.Map <PurchaseDTO>(entity); } } catch (Exception ex) { _logger.Error(ex); result = null; } return(Json(result, JsonRequestBehavior.AllowGet)); }
public async Task <ActionResult <PurchaseDTO> > Delete(Guid cartId, Guid purchaseId) { try { Purchase purchase = await purchasesService.RemovePurchaseFromCartAsync(purchaseId, cartId); PurchaseDTO purchaseDTO = PurchaseDTO.FromDbModel(purchase); return(Ok(purchaseDTO)); } catch (Exception e) { if (e is ShoppingCartClosedException || e is ItemNotInCartException) { return(BadRequest(e.Message)); } return(Problem(e.Message, statusCode: StatusCodes.Status500InternalServerError)); } }
private void Validate(PurchaseDTO dto) { if (dto == null) { throw new ArgumentNullException("Function argument can not be null"); } var cost = 0; foreach (var el in dto.ShoppingCartItemDTOs) { cost += el.Quantity * _dbContext.Products.Where(p => p.Id == el.ProductId).First().Price; } if (dto.ProductsCost != cost) { throw new ArgumentException("Invalid purchase cost parameter"); } }
private string PrepareBody(EmailType type, PurchaseDTO purchase) { string bodyTemplate = string.Empty; string generated = string.Empty; int total = purchase.Products.Sum(val => val.Cost * val.Quantity); if (type == EmailType.External) { using (StreamReader sourceReader = System.IO.File.OpenText(templatesPath + ExternalHtml)) { bodyTemplate = sourceReader.ReadToEnd(); if (string.IsNullOrEmpty(bodyTemplate)) { throw new FileNotFoundException("Cannot load external body html template."); } } generated = string.Format(bodyTemplate, total, purchase.Credentials.Name); } else { using (StreamReader sourceReader = System.IO.File.OpenText(templatesPath + InternalHtml)) { bodyTemplate = sourceReader.ReadToEnd(); if (string.IsNullOrEmpty(bodyTemplate)) { throw new FileNotFoundException("Cannot load internal body html template."); } } generated = string.Format(bodyTemplate, total, purchase.Credentials.Name, purchase.Credentials.Email, purchase.Credentials.PhoneNumber, purchase.PaymentMethod, purchase.DeliveryMethod, purchase.Credentials.Address, purchase.Comment); } return(generated); }
public override void Fill(IDbConnection connection, int count = 100) { CreateTable(connection); Random random = new Random(); string InsertionString = GenerateInsertionString(); for (int i = 0; i < count; ++i) { PurchaseDTO vendor = new PurchaseDTO(); // int numProducts = 1 + random.Next() % 19; string productIDs = ""; string productQuantities = ""; string productBuyingPrices = ""; double totalBuyingPrice = 0; for (int n = 0; n < numProducts; ++n) { int id = random.Next() % 99 + 1; int quantity = random.Next() % 20 + 1; double price = random.NextDouble() * 100 + 1; totalBuyingPrice += price * quantity; productIDs += id.ToString() + ","; productQuantities += quantity.ToString() + ","; productBuyingPrices += price.ToString() + ","; } productIDs = productIDs.Substring(0, productIDs.Length - 1); productQuantities = productQuantities.Substring(0, productQuantities.Length - 1); productBuyingPrices = productBuyingPrices.Substring(0, productBuyingPrices.Length - 1); vendor.VendorID = random.Next() % 99 + 1; vendor.ProductIDs = productIDs; vendor.ProductQuantities = productQuantities; vendor.ProductBuyingPrices = productBuyingPrices; vendor.TotalBuyingPrice = totalBuyingPrice; connection.Execute(InsertionString, vendor); } }