Ejemplo n.º 1
0
        public async Task <IActionResult> SellStock(StockDetails stockdetails)
        {
            try
            {
                if (CheckValid())
                {
                    int portfolioid = Convert.ToInt32(HttpContext.Session.GetString("Id"));
                    _log4net.Info("Selling the stocks of user with id = " + portfolioid);

                    AssetSaleResponse assetSaleResponse = await _customerRepository.SellStocks(portfolioid, stockdetails);

                    _log4net.Info("sale of stock of user with id" + portfolioid + "done");
                    Sale _sale = new Sale();
                    _sale.PortFolioID = portfolioid;
                    _sale.NetWorth    = assetSaleResponse.Networth;
                    _sale.status      = assetSaleResponse.SaleStatus;
                    _saleRepository.Add(_sale);

                    return(View("Reciept", assetSaleResponse));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception ex)
            {
                _log4net.Error("An exception occured in the" + nameof(SellStock) + " while selling mutualFund. The message is:" + ex.Message);
                return(RedirectToAction("Index", "Home"));
            }
        }
Ejemplo n.º 2
0
        public void SaleRepository_Add_ShouldBeOk()
        {
            _product.Object.Id = 1;
            _sale = ObjectMother.GetSaleSql(_product.Object);

            _expectedSale = _repository.Add(_sale);

            _expectedSale.Should().NotBeNull();
            _expectedSale.Id.Should().Be(_sale.Id);
        }
Ejemplo n.º 3
0
        public ActionResult Buy(ICollection <UserOrder> data, string userName)
        {
            var cart = GetCart();

            cart.SetCountGoods(data);
            var orders = cart.GetAllGoodsId();

            cart.RenewPriceGoods(_goods.FindBy(g => orders.Contains(g.GoodId)));
            try
            {
                _unit.StartTransaction();
                var sale = _sale.Add(cart.GetSale(userName));
                _salePos.Add(cart.GetSalePoses(), sale);
                _unit.Save();
                _unit.Commit();
            }
            catch (ArgumentException e)
            {
                _unit.Rollback();
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, e.Message));
            }
            catch (Exception e)
            {
                _unit.Rollback();
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Your order has not been added"));
            }
            return(new HttpStatusCodeResult(HttpStatusCode.Accepted, "Your order has been successfully added"));
        }
Ejemplo n.º 4
0
        public void Add(params Sale[] sales)
        {
            _locker.EnterWriteLock();
            try
            {
                foreach (var sale in sales)
                {
                    //sale.Client.Id = _clients.GetId(sale.Client.FirstName, sale.Client.LastName);
                    sale.ClientId = _clients.GetId(sale.Client.FirstName, sale.Client.LastName);
                    sale.Client   = null;

                    //sale.Manager.Id = _managers.GetId(sale.Manager.LastName);
                    sale.ManagerId = _managers.GetId(sale.Manager.LastName);
                    sale.Manager   = null;

                    //sale.Product.Id = _products.GetId(sale.Product.Name);
                    sale.ProductId = _products.GetId(sale.Product.Name);
                    sale.Product   = null;

//                    _context.Entry(sale.Client).State = EntityState.Unchanged;
//                    _context.Entry(sale.Manager).State = EntityState.Unchanged;
//                    _context.Entry(sale.Product).State = EntityState.Unchanged;

                    _sales.Add(sale);
                    _sales.Save();
                }
            }

            finally
            {
                _locker.ExitWriteLock();
            }
        }
Ejemplo n.º 5
0
        public IActionResult Create([FromBody] SaleViewModel sale)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Sale _newSale = Mapper.Map <SaleViewModel, Sale>(sale);

            _newSale.CreateDate = DateTime.Now;

            _saleRepository.Add(_newSale);
            _saleRepository.Commit();

            IEnumerable <Operation> operations = _operationRepository.FindBy(x => x.SellerId == sale.SellerId).ToList();

            var cardInit = operations.FirstOrDefault(x => x.OperationType == OperationType.CardInitiate);
            var cardSale = operations.FirstOrDefault(x => x.OperationType == OperationType.Sale);

            Report newReport = new Report()
            {
                Discount      = sale.SaleType == SaleType.CardInitiate ? (cardInit != null ? cardInit.Discount : 5) : (sale.Price * (cardSale != null ? cardSale.Discount : 10) / 100),
                CreateDate    = DateTime.Now,
                UpdateDate    = DateTime.Now,
                IsActive      = true,
                IsDeleted     = false,
                OperationType = sale.SaleType == SaleType.CardInitiate ? OperationType.CardInitiate.ToString() : OperationType.Sale.ToString(),
                SellerId      = sale.SellerId
            };

            _reportRepository.Add(newReport);
            _reportRepository.Commit();

            sale = Mapper.Map <Sale, SaleViewModel>(_newSale);

            CreatedAtRouteResult result = CreatedAtRoute("GetSale", new { controller = "Sale", id = sale.Id }, sale);

            return(result);
        }
Ejemplo n.º 6
0
 public SaleLead CreateSaleLead(int customerId, int stateId, int saleId, DateTime timestamp)
 {
     if (saleId == 0)
     {
         var sale = new Sale { OrderNumber = 0, Date = DateTime.Now };
         _repoSale.Add(sale);
         var addedSale = _repoSale.AsQueryable().Where(o => o.OrderNumber == 0).ToList();
         saleId = addedSale.First().Id;
     }
     var lead = new SaleLead { CustomerId = customerId, StateId = stateId, SaleId = saleId, Timestamp = timestamp };
     _repoSaleLead.Add(lead);
     return lead;
 }
Ejemplo n.º 7
0
        public Sale FindOrCreateSaleLead(CustomerDTO cus, int orderNo, DateTime date, Boolean finalised)
        {
            SaleLead lead = null;

            if (cus != null)
            {
                var cusSpec    = new Specification <SaleLead>(c => c.CustomerId == cus.CustomerId);
                var saleSpec   = new Specification <SaleLead>(s => s.Sale.OrderNumber == orderNo);
                var cusAndSale = cusSpec.And(saleSpec);
                lead = _repoSaleLead.Find(cusAndSale);
            }
            if (lead == null)
            {
                var orderSpec    = new Specification <Sale>(x => x.OrderNumber == orderNo);
                var dateSpec     = new Specification <Sale>(y => y.Date == date);
                var orderAndDate = orderSpec.And(dateSpec);
                var sale         = _repoSale.Find(orderAndDate);
                if (sale == null)
                {
                    sale = new Sale {
                        Date = date, OrderNumber = orderNo
                    };
                    _repoSale.Add(sale);
                }
                var state = _repoLeadState.AsQueryable().FirstOrDefault();
                if (cus != null)
                {
                    var customer = _repoCustomer.Get(cus.CustomerId);
                    var newLead  = new SaleLead {
                        SaleId = sale.Id, Sale = sale, SaleLeadState = state, StateId = state.Id, Customer = customer, CustomerId = customer.Id
                    };
                    _repoSaleLead.Add(newLead);
                    return(sale);
                }
                else
                {
                    var customer = _repoCustomer.AsQueryable().FirstOrDefault();
                    var newLead  = new SaleLead {
                        SaleId = sale.Id, Sale = sale, SaleLeadState = state, StateId = state.Id, Customer = customer, CustomerId = customer.Id
                    };
                    _repoSaleLead.Add(newLead);
                    return(sale);
                }
            }
            else
            {
                var sale = _repoSale.AsQueryable().FirstOrDefault(s => s.Id == lead.Sale.Id);
                return(sale);
            }
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> CreateSale(SaleDTO saleDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid ModelState"));
            }

            var sale = mapper.Map <SaleDTO, Sale>(saleDTO);

            repo.Add(sale);
            await uow.CompleteAsync();

            return(Ok());
        }
Ejemplo n.º 9
0
        public async Task <SaleDTO> CreateSale(CreateSaleDTO dto)
        {
            var reseller = await _resellerRepository.FindResellerByCPF(dto.CPF);

            if (reseller != null)
            {
                var sale = _mapper.Map <Sale>(dto);
                sale.StatusSaleId = SalesHelper.SALES_CPF_APPROVED == reseller.CPF ? (int)SaleStatus.Approved : (int)SaleStatus.InValidation;
                sale.ResellerId   = reseller.Id;
                sale.Reseller     = reseller;
                var insert = _saleRepository.Add(sale);
                return(_mapper.Map <SaleDTO>(insert));
            }
            return(null);
        }
Ejemplo n.º 10
0
 public (bool, string) AddSale(SaleForOperationsDto saledto)
 {
     var(isvalid, message) = saledto.Validate();
     if (!isvalid)
     {
         return(false, message.First().ToString());
     }
     try
     {
         var saledao = Mapping.Mapper.Map <Sale>(saledto);
         var res     = _saleRepo.Add(saledao);
         return(res, res ? "Them thanh cong" : "Có lỗi xảy ra");
     }
     catch
     {
         return(false, "Có lỗi xảy ra (Ánh xạ)");
     }
 }
Ejemplo n.º 11
0
        public async Task Execute(CreateSaleModel model)
        {
            var customer = await _customerRepository.Get(model.CustomerId);

            var employee = await _employeeRepository.Get(model.EmployeeId);

            var product = await _productRepository.Get(model.ProductId);

            var sale = new Sale
                       (
                Guid.NewGuid(),
                customer,
                employee,
                product,
                model.Quantity
                       );

            await _saleRepository.Add(sale);

            await _uow.Save();
        }
Ejemplo n.º 12
0
        public async Task <bool> Handle(CreateSaleCommand message, CancellationToken cancellationToken)
        {
            var sale     = Sale.SaleFactory.NewSale(message.CustomerId);
            var customer = await saleRepository.GetCustomerByIdAsync(sale.CustomerId);

            if (customer == null)
            {
                await mediator.RaiseEvent(new DomainNotification(message.MessageType, $"Não existe Cliente cadastrado como o id: {message.CustomerId}"));

                return(false);
            }
            sale.SetCustomer(customer);
            sale.SetSaleItems(message.Items);

            foreach (var item in sale.Items)
            {
                var disc = await discRepository.GetById(item.DiscId);

                if (disc == null)
                {
                    await mediator.RaiseEvent(new DomainNotification(message.MessageType, $"Não existe nenhum Disco cadastrado como o id: {item.DiscId}"));

                    return(false);
                }
                if (!IsValid(item))
                {
                    return(false);
                }
                item.SetDependencies(sale, disc.Id);
                item.ComputeCashBack(disc);
            }

            if (!IsValid(sale))
            {
                return(false);
            }
            await saleRepository.Add(sale);

            return(await Commit());
        }
Ejemplo n.º 13
0
        public void Add(SaleViewModel saleViewModel)
        {
            Sale sale = mapper.Map <Sale>(saleViewModel);

            foreach (SaleItemViewModel saleItemViewModel in saleViewModel.SaleItems)
            {
                List <InventoryItem> inventoryItems = inventoryItemRepository.TaleInventoryItems(saleItemViewModel.ProductId, saleItemViewModel.Quantity).ToList();
                inventoryItems.Select(x => { x.InventoryItemStatusId = (int)InventoryItemStatusType.Sold; return(x); });

                for (int i = 0; i < saleItemViewModel.Quantity; i++)
                {
                    sale.SaleItems.Add(new SaleItem
                    {
                        Price           = saleItemViewModel.Price,
                        InventoryItem   = inventoryItems[i],
                        InventoryItemId = inventoryItems[i].Id
                    });
                }
            }

            saleRepository.Add(sale);
            saleRepository.SaveChanges();
        }
Ejemplo n.º 14
0
        public async Task Add(Sale sale)
        {
            //if (!ExecuteValidation(new SaleValidation(), sale)) return;

            await _saleRepository.Add
            (
                new Sale()
            {
                TotalValue    = sale.TotalValue,
                FormOfPayment = sale.FormOfPayment,
                AmountPaid    = sale.AmountPaid,
                Change        = sale.Change,
                ProductSales  = sale.ProductSales
                                .GroupBy(ps => ps.ProductId)
                                .Select(p => new ProductSale()
                {
                    SaleId    = p.First().SaleId,
                    Sale      = p.First().Sale,
                    ProductId = p.First().ProductId,
                    Product   = p.First().Product,
                    Total     = p.Sum(x => x.Total),
                    Quantity  = p.Sum(x => x.Quantity)
                }).ToList()
            }
            );

            foreach (var product in sale.ProductSales)
            {
                product.Product = await _productRepository.GetById(product.ProductId);

                product.Product.Quantity -= product.Quantity;
                await _productRepository.Update(product.Product);
            }

            try
            {
                string printerName = _configuration["Printer:PrinterName"];
                var    printer     = new Printer(printerName, PrinterType.Epson);

                sale.ProductSales = sale.ProductSales
                                    .GroupBy(s => s.ProductId)
                                    .Select(g => new ProductSale
                {
                    ProductId = g.First().ProductId,
                    SaleId    = g.First().SaleId,
                    Sale      = g.First().Sale,
                    Product   = g.First().Product,
                    Quantity  = g.Sum(s => s.Quantity),
                    Total     = g.Sum(s => s.Total)
                }).ToList();

                sale.ProductSales = sale.ProductSales.OrderBy(c => c.Product.ExternalId.Length).ThenBy(c => c.Product.ExternalId).ToList();

                printer.PrintOut(sale);
                printer.PartialPaperCut();
                printer.PrintDocument();
                printer.PrintDocument();
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 15
0
        public IActionResult Post([FromBody] Salesperson value)
        {
            saleRepository.Add(value);

            return(CreatedAtRoute("GetSalesPerson", new { controller = "Sale", id = value.SalespersonId }, value));
        }
Ejemplo n.º 16
0
 public bool Insert(Sale sale)
 {
     _repository.Add(sale);
     return(_repository.SaveChanges());
 }
Ejemplo n.º 17
0
 public void AddSale(Sale sale)
 {
     _saleRepository.Add(sale);
 }
Ejemplo n.º 18
0
        public void AddSale(SaleDTO sale)
        {
            var saleEF = sale.MappingSale();

            saleRepository.Add(saleEF);
        }
Ejemplo n.º 19
0
        public Sale AddSale(Sale Sale)
        {
            ISaleRepository SaleRepository = _dataFactoryRepository.GetDataRepository <ISaleRepository>();

            return(SaleRepository.Add(Sale));
        }
Ejemplo n.º 20
0
        public async Task <SaleDto> Create(Guid userId, SaleForCreationDto saletForCreationDto)
        {
            try
            {
                Client client = null;
                if (saletForCreationDto.ClientId.HasValue)
                {
                    client = await _clientRepository.GetById(saletForCreationDto.ClientId.Value);

                    if (client == null)
                    {
                        throw new KeyNotFoundException($"Client with id: {saletForCreationDto.ClientId} not found.");
                    }
                }

                var sale = new Sale()
                {
                    ClientId    = saletForCreationDto.ClientId,
                    ClientName  = client != null ? client.Name + " " + client.Lastname : saletForCreationDto.ClientName,
                    Date        = saletForCreationDto.Date.ToLocalTime(),
                    PaymentType = saletForCreationDto.PaymentType,
                    CreatedBy   = userId
                };

                decimal total = 0;
                foreach (var detailFC in saletForCreationDto.Details)
                {
                    var product = await _productRepository.GetById(detailFC.ProductId);

                    if (product == null)
                    {
                        throw new KeyNotFoundException($"Product with id: {detailFC.ProductId} not found.");
                    }

                    var price = (await _priceRepository.GetAll())
                                .OrderByDescending(x => x.DateTime)
                                .FirstOrDefault(
                        x => x.ProductId == detailFC.ProductId &&
                        x.DateTime.ToLocalTime() <= saletForCreationDto.Date.ToLocalTime() &&
                        x.PriceType == ePriceTypes.SalePrice &&
                        !x.IsDeleted
                        );

                    FeeRule feeRule = null;
                    if (sale.PaymentType == ePaymentTypes.OwnFees)
                    {
                        feeRule = (await _feeRuleRepository.Find(x => x.ProductId == detailFC.ProductId))
                                  .OrderByDescending(x => x.Date).ThenBy(x => x.FeesAmountTo)
                                  .FirstOrDefault(x => x.Date <= sale.Date && x.FeesAmountTo >= saletForCreationDto.OwnFees.Quantity);
                        if (feeRule == null)
                        {
                            throw new KeyNotFoundException($"Fee Rule not found.");
                        }

                        decimal percentage = feeRule.Percentage * saletForCreationDto.OwnFees.Quantity / 100;
                        total += price.Value * detailFC.Quantity * (1 + percentage);
                    }
                    else
                    {
                        total += price.Value * detailFC.Quantity;
                    }

                    var detail = new Detail()
                    {
                        SaleId    = sale.Id,
                        ProductId = detailFC.ProductId,
                        Quantity  = detailFC.Quantity,
                        UnitPrice = price.Value,
                        FeeRuleId = feeRule?.Id,
                        CreatedBy = userId
                    };
                    product.Stock -= detailFC.Quantity;

                    detail = await _detailRepository.Add(detail);

                    await _productRepository.Update(product);
                }

                Payment payment = null;
                switch (saletForCreationDto.PaymentType)
                {
                case Util.Enums.ePaymentTypes.Cash:
                    var cashDto = (CashForCreationDto)saletForCreationDto.Cash;
                    payment = new Cash(total, cashDto.Discount)
                    {
                        SaleId    = sale.Id,
                        CreatedBy = userId
                    };

                    await _cashRepository.Add((Cash)payment);

                    break;

                case Util.Enums.ePaymentTypes.OwnFees:
                    var ownFeesDto = (OwnFeesForCreationDto)saletForCreationDto.OwnFees;
                    payment = new OwnFees(ownFeesDto.ExpirationDate, total, ownFeesDto.Quantity, userId)
                    {
                        SaleId = sale.Id,
                    };

                    payment = await _ownFeesRepository.Add((OwnFees)payment);

                    foreach (var fee in ((OwnFees)payment).FeeList)
                    {
                        await _feeRepository.Add(fee);
                    }
                    break;

                case Util.Enums.ePaymentTypes.CreditCard:
                    var creditCardDto = (CreditCardForCreationDto)saletForCreationDto.CreditCard;
                    payment = new CreditCard(total, creditCardDto.Discount, creditCardDto.Surcharge)
                    {
                        SaleId    = sale.Id,
                        CardType  = creditCardDto.CardType,
                        Bank      = creditCardDto.Bank,
                        CreatedBy = userId
                    };

                    await _creditCardRepository.Add((CreditCard)payment);

                    break;

                case Util.Enums.ePaymentTypes.DebitCard:
                    var debitCardDto = (DebitCardForCreationDto)saletForCreationDto.DebitCard;
                    payment = new DebitCard(total, debitCardDto.Discount, debitCardDto.Surcharge)
                    {
                        SaleId    = sale.Id,
                        CardType  = debitCardDto.CardType,
                        Bank      = debitCardDto.Bank,
                        CreatedBy = userId
                    };

                    await _debitCardRepository.Add((DebitCard)payment);

                    break;

                case Util.Enums.ePaymentTypes.Cheques:
                    var chequesDto = (ChequesPaymentForCreationDto)saletForCreationDto.Cheques;

                    if (chequesDto.ListOfCheques.Sum(x => x.Value) != total)
                    {
                        throw new InvalidOperationException("The sum of cheques list is different of amount.");
                    }

                    payment = new ChequesPayment()
                    {
                        SaleId    = sale.Id,
                        Amount    = Math.Ceiling(total * 100) / 100,
                        CreatedBy = userId
                    };

                    await _chequesPaymentRepository.Add((ChequesPayment)payment);

                    foreach (var c in chequesDto.ListOfCheques)
                    {
                        var cheque = new Cheque()
                        {
                            ChequesPaymentId = payment.Id,
                            Bank             = c.Bank,
                            Nro       = c.Nro,
                            Value     = c.Value,
                            CreatedBy = userId
                        };

                        await _chequeRepository.Add(cheque);
                    }
                    break;

                default:
                    break;
                }

                sale.PaymentId = payment.Id;
                sale           = await _saleRepository.Add(sale);

                await _saleRepository.CommitAsync();

                return(_mapper.Map <Sale, SaleDto>(sale));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        public async Task <IActionResult> SellStock(StockDetails stockdetails)
        {
            try
            {
                if (CheckValid())
                {
                    PortFolioDetails current = new PortFolioDetails();
                    PortFolioDetails toSell  = new PortFolioDetails();
                    int id = Convert.ToInt32(HttpContext.Session.GetString("Id"));
                    _log4net.Info("Selling the stocks of user with id = " + id);
                    using (var client = new HttpClient())
                    {
                        using (var response = await client.GetAsync("https://localhost:44375/api/NetWorth/GetPortFolioDetailsByID/" + id))
                        {
                            string apiResponse = await response.Content.ReadAsStringAsync();

                            current = JsonConvert.DeserializeObject <PortFolioDetails>(apiResponse);
                        }
                    }
                    toSell.PortFolioId = id;
                    toSell.StockList   = new List <StockDetails>
                    {
                        stockdetails
                    };
                    toSell.MutualFundList = new List <MutualFundDetails>()
                    {
                    };

                    List <PortFolioDetails> list = new List <PortFolioDetails>
                    {
                        current,
                        toSell
                    };

                    AssetSaleResponse assetSaleResponse = new AssetSaleResponse();
                    StringContent     content           = new StringContent(JsonConvert.SerializeObject(list), Encoding.UTF8, "application/json");
                    using (var client = new HttpClient())
                    {
                        using (var response = await client.PostAsync("https://localhost:44375/api/NetWorth/SellAssets", content))
                        {
                            string apiResponse = await response.Content.ReadAsStringAsync();

                            assetSaleResponse = JsonConvert.DeserializeObject <AssetSaleResponse>(apiResponse);
                        }
                    }
                    _log4net.Info("sale of stock of user with id" + current.PortFolioId + "done");
                    Sale _sale = new Sale();
                    _sale.PortFolioID = current.PortFolioId;
                    _sale.NetWorth    = assetSaleResponse.Networth;
                    _sale.status      = assetSaleResponse.SaleStatus;
                    _saleRepository.Add(_sale);

                    return(View("Reciept", assetSaleResponse));
                }
                else
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }
            catch (Exception ex)
            {
                _log4net.Error("An exception occured in the" + nameof(SellStock) + " while selling mutualFund. The message is:" + ex.Message);
                return(RedirectToAction("Index", "Home"));
            }
        }
Ejemplo n.º 22
0
 public Sale Add(Sale sale)
 {
     sale.Validate();
     return(_repository.Add(sale));
 }