Beispiel #1
0
 public UnitOfWork(LuaContext context)
 {
     _context = context;
     Authors = new AuthorRepository(_context);
     Books = new BookRepository(_context);
     Customers = new CustomerRepository(_context);
     Rentals = new RentalRepository(_context);
     Stocks = new StockRepository(_context);
 }
        public IssueByIdentifierViewModel(
            IUnitOfWorkFactory unitOfWorkFactory,
            INavigationManager navigation,
            IGuiDispatcher guiDispatcher,
            IUserService userService,
            ILifetimeScope autofacScope,
            StockRepository stockRepository,
            EmployeeRepository employeeRepository,
            FeaturesService featuresService,
            IValidator validator,
            BaseParameters baseParameters,
            IInteractiveQuestion interactive,
            IChangeableConfiguration configuration,
            SizeService sizeService,
            ICardReaderService cardReaderService = null) : base(navigation)
        {
            this.unitOfWorkFactory  = unitOfWorkFactory ?? throw new ArgumentNullException(nameof(unitOfWorkFactory));
            this.guiDispatcher      = guiDispatcher ?? throw new ArgumentNullException(nameof(guiDispatcher));
            this.userService        = userService ?? throw new ArgumentNullException(nameof(userService));
            this.autofacScope       = autofacScope ?? throw new ArgumentNullException(nameof(autofacScope));
            this.employeeRepository = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository));
            this.validator          = validator ?? throw new ArgumentNullException(nameof(validator));
            this.BaseParameters     = baseParameters ?? throw new ArgumentNullException(nameof(baseParameters));
            this.interactive        = interactive ?? throw new ArgumentNullException(nameof(interactive));
            this.configuration      = configuration ?? throw new ArgumentNullException(nameof(configuration));
            SizeService             = sizeService ?? throw new ArgumentNullException(nameof(sizeService));
            this.cardReaderService  = cardReaderService;
            IsModal = false;
            EnableMinimizeMaximize = true;
            Title = "Выдача по картам СКУД";

            UowOfDialog = unitOfWorkFactory.CreateWithoutRoot();
            var entryBuilder = new CommonEEVMBuilderFactory <IssueByIdentifierViewModel>(this, this, UowOfDialog, navigation, autofacScope);

            if (cardReaderService != null)
            {
                cardReaderService.RefreshDevices();
                cardReaderService.СardStatusRead           += RusGuardService_СardStatusRead;
                cardReaderService.CardFamilies.ListChanged += CardFamilies_ListChanged;
            }
            UpdateState();


            WarehouseEntryViewModel = entryBuilder.ForProperty(x => x.Warehouse).MakeByType().Finish();
            Warehouse = stockRepository.GetDefaultWarehouse(UowOfDialog, featuresService, autofacScope.Resolve <IUserService>().CurrentUserId);

            //Настройка таймера сброса
            timerCleanSuccessfullyText           = new Timer(40000);
            timerCleanSuccessfullyText.AutoReset = false;
            timerCleanSuccessfullyText.Elapsed  += delegate(object sender, ElapsedEventArgs e) {
                guiDispatcher.RunInGuiTread(() => SuccessfullyText = null);
            };

            ReadConfig();
        }
Beispiel #3
0
        public void CanInsertList()
        {
            var repository = new StockRepository();
            var stockList  = new List <Stock> {
                new Stock(), new Stock()
            };

            repository.InsertList(stockList);

            Assert.AreEqual(2, repository.Count());
        }
Beispiel #4
0
        public void UpdateIncomeTest()
        {
            var ask = Substitute.For <IInteractiveQuestion>();

            ask.Question(string.Empty).ReturnsForAnyArgs(true);

            using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                var warehouse = new Warehouse {
                    Name = "TestWarehouse"
                };
                uow.Save(warehouse);

                var income = new Income {
                    Warehouse = warehouse,
                    Date      = new DateTime(2017, 1, 1),
                    Operation = IncomeOperations.Enter
                };
                var nomenclature1 = new Nomenclature {
                    Name = "TestNomenclature1"
                };
                uow.Save(nomenclature1);
                var nomenclature2 = new Nomenclature {
                    Name = "TestNomenclature2"
                };
                uow.Save(nomenclature2);
                var item1 = income.AddItem(nomenclature1);
                var item2 = income.AddItem(nomenclature2);

                income.UpdateOperations(uow, ask);
                uow.Save(income);
                uow.Commit();

                var stockRepository = new StockRepository();
                var stock1          = stockRepository.StockBalances(uow, warehouse,
                                                                    new List <Nomenclature> {
                    nomenclature1, nomenclature2
                },
                                                                    new DateTime(2017, 1, 2));
                Assert.That(stock1.Count(), Is.EqualTo(2));

                income.RemoveItem(item1);
                income.UpdateOperations(uow, ask);
                uow.Save(income);
                uow.Commit();

                var stock2 = stockRepository.StockBalances(uow, warehouse,
                                                           new List <Nomenclature> {
                    nomenclature1, nomenclature2
                },
                                                           new DateTime(2017, 1, 2));

                Assert.That(stock2.Count(), Is.EqualTo(1));
            }
        }
Beispiel #5
0
        /// <summary>
        /// Method to update the stock prices after each 5 seconds.
        /// </summary>
        private void SimulateStocksPriceMovement()
        {
            StockRepository stockPriceService = new StockRepository();

            stockPriceService.InitializeStockList();
            timer          = new System.Timers.Timer(5000);
            timer.Elapsed += (o, e) => { stockPriceService.UpdateStockPrices(); };

            //Calling the timer on a Background thread.
            timer.Start();
        }
Beispiel #6
0
        public Offers(Export export)
        {
            myExport = export;
            myExport.OnProgressPlusOneTask("Выгружаем наличие на складе");

            var warehouses      = WarehouseRepository.WarehousesForPublishOnlineStore(myExport.UOW);
            var nomenclatureIds = myExport.Catalog.Goods.NomenclatureIds;
            var warehousesIds   = warehouses.Select(x => x.Id).ToArray();

            amounts = StockRepository.NomenclatureInStock(myExport.UOW, warehousesIds, nomenclatureIds);
        }
Beispiel #7
0
 private void OnLoadCompleted()
 {
     this.RunOnUiThread(() =>
     {
         foreach (var stock in StockRepository.GetStocks())
         {
             this.Stocks.Add(stock);
         }
         this.IsInitialized = true;
     });
 }
Beispiel #8
0
        public ActionResult Index()
        {
            //TODO: Add combined view to various features
            var repo = new StockRepository(new StockContext());
            //var results = repo.GetAllSecurities();
            //var results = repo.GetAllSecuritiesWithPrices().Take(10).ToList();
            var results = repo.GetSpecificSecurity("AAL");

            //var results = repo.GetSpecificSecurityBetweenDates("AAL", DateTime.Parse("03/01/2018 00:00:00"), DateTime.Parse("25/01/2018"));
            return(View(results));
        }
Beispiel #9
0
        public void IdIsAssignedOnInsertList()
        {
            var repository = new StockRepository();

            repository.InsertList(new List <Stock> {
                new Stock(), new Stock()
            });

            Assert.IsNotNull(repository.Get(1));
            Assert.IsNotNull(repository.Get(2));
        }
Beispiel #10
0
        public void Income_ItemWearPercent_SaveInStockTest()
        {
            var ask = Substitute.For <IInteractiveQuestion>();

            ask.Question(string.Empty).ReturnsForAnyArgs(true);

            using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                var warehouse = new Warehouse();
                uow.Save(warehouse);

                var sizeType = new SizeType();
                uow.Save(sizeType);

                var nomenclatureType = new ItemsType {
                    Name     = "Тестовый тип номенклатуры",
                    SizeType = sizeType
                };
                uow.Save(nomenclatureType);

                var nomenclature = new Nomenclature {
                    Type = nomenclatureType
                };
                uow.Save(nomenclature);

                var sizeX = new Size {
                    Name = "X", SizeType = sizeType
                };
                uow.Save(sizeX);

                var income = new Income {
                    Warehouse = warehouse,
                    Date      = new DateTime(2017, 1, 1),
                    Operation = IncomeOperations.Enter
                };
                var incomeItem1 = income.AddItem(nomenclature);
                incomeItem1.WearSize    = sizeX;
                incomeItem1.WearPercent = 0.8m;
                incomeItem1.Amount      = 10;
                income.UpdateOperations(uow, ask);
                var validator = new QS.Validation.ObjectValidator();
                Assert.That(validator.Validate(income), Is.True);
                uow.Save(income);
                uow.Commit();

                var stock = new StockRepository()
                            .StockBalances(uow, warehouse, new List <Nomenclature> {
                    nomenclature
                }, DateTime.Now);
                var stockItem = stock.First();
                Assert.That(stockItem.Amount, Is.EqualTo(10));
                Assert.That(stockItem.WearPercent, Is.EqualTo(0.8m));
            }
        }
        public CompletionViewModel(IEntityUoWBuilder uowBuilder,
                                   IUnitOfWorkFactory unitOfWorkFactory,
                                   INavigationManager navigation,
                                   IUserService userService,
                                   StockRepository stockRepository,
                                   FeaturesService featuresService,
                                   ILifetimeScope autofacScope,
                                   BaseParameters baseParameters,
                                   IInteractiveQuestion interactive,
                                   SizeService sizeService,
                                   IValidator validator = null) : base(uowBuilder, unitOfWorkFactory, navigation, validator)
        {
            var entryBuilder = new CommonEEVMBuilderFactory <Completion>(this, Entity, UoW, navigation, autofacScope);

            this.interactive     = interactive;
            this.featuresService = featuresService;
            SizeService          = sizeService;

            if (UoW.IsNew)
            {
                Entity.CreatedbyUser = userService.GetCurrentUser(UoW);
            }

            if (Entity.SourceWarehouse == null)
            {
                Entity.SourceWarehouse = stockRepository.GetDefaultWarehouse
                                             (UoW, featuresService, autofacScope.Resolve <IUserService>().CurrentUserId);
            }

            WarehouseExpenseEntryViewModel = entryBuilder.ForProperty(x => x.SourceWarehouse)
                                             .UseViewModelJournalAndAutocompleter <WarehouseJournalViewModel>()
                                             .UseViewModelDialog <WarehouseViewModel>()
                                             .Finish();

            if (Entity.ResultWarehouse == null)
            {
                Entity.ResultWarehouse = stockRepository.GetDefaultWarehouse
                                             (UoW, featuresService, autofacScope.Resolve <IUserService>().CurrentUserId);
            }

            WarehouseReceiptEntryViewModel = entryBuilder.ForProperty(x => x.ResultWarehouse)
                                             .UseViewModelJournalAndAutocompleter <WarehouseJournalViewModel>()
                                             .UseViewModelDialog <WarehouseViewModel>()
                                             .Finish();

            Validations.Clear();
            Validations.Add(new ValidationRequest(Entity,
                                                  new ValidationContext(Entity, new Dictionary <object, object> {
                { nameof(BaseParameters), baseParameters }, { nameof(IUnitOfWork), UoW }
            })));
            Entity.PropertyChanged += Entity_PropertyChanged;
            lastWarehouse           = Entity.SourceWarehouse;
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            StockRepository stockRepository = new StockRepository(
                Settings.Default.AzureCosmosDBEndpointUrl,
                Settings.Default.AzureCosmodBDPrimaryKey,
                Settings.Default.AzureCosmosDatabaseName);

            Task.WaitAll(stockRepository.EnsureCollection());

            Product[] products = GetDemoProducts();
            Task.WaitAll(stockRepository.AddEntities(products));
        }
Beispiel #13
0
        public void GetAllTests()
        {
            var connection = new SqliteConnection("DataSource=:memory:");

            connection.Open();
            try
            {
                var options = new DbContextOptionsBuilder <DatabaseContext>().UseSqlite(connection).Options;
                using (var context = new DatabaseContext(options))
                {
                    context.Database.EnsureCreated();
                }

                var stockCollection = new List <Stock>
                {
                    new Stock
                    {
                        Price            = new decimal(12.32),
                        Quantity         = 7,
                        StockType        = StockType.Bond,
                        CommisionPercent = 2.0
                    },
                    new Stock
                    {
                        Price            = new decimal(72.11),
                        Quantity         = 96,
                        StockType        = StockType.Equity,
                        CommisionPercent = 0.5
                    }
                };
                using (var context = new DatabaseContext(options))
                {
                    foreach (var stock in stockCollection)
                    {
                        context.Stocks.Add(stock);
                    }

                    context.SaveChanges();
                }

                using (var context = new DatabaseContext(options))
                {
                    var repository = new StockRepository(context);
                    var stocks     = repository.GetAllStocks().ToList();
                    Assert.Equal(2, stocks.Count);
                    Assert.True(stocks.IsDeepEqual(stockCollection));
                }
            }
            finally
            {
                connection.Close();
            }
        }
        public ActionResult Create(Stock stock)
        {
            try
            {
                StockRepository.Insert(stock);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
        public ActionResult Edit(int id, Stock stock)
        {
            try
            {
                StockRepository.Update(stock);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #16
0
 public UnitOfWork()
 {
     _dbContext               = new ApplicationDbContext();
     BasketHeaderRepository   = new BasketHeaderRepository(_dbContext);
     CashDrawerRepository     = new CashDrawerRepository(_dbContext);
     CustomerRepository       = new CustomerRepository(_dbContext);
     JournalRepository        = new JournalRepository(_dbContext);
     MeansOfPaymentRepository = new MeansOfPaymentRepository(_dbContext);
     ProductRepository        = new ProductRepository(_dbContext);
     ProductTypeRepository    = new ProductTypeRepository(_dbContext);
     StockRepository          = new StockRepository(_dbContext);
     UserRepository           = new UserRepository(_dbContext);
 }
Beispiel #17
0
        public void GetInitialStockTest()
        {
            stockList = StockRepository.GetStocks();

            if (stockList.Count() <= 0)
            {
                Assert.IsEmpty(stockList);
            }
            else
            {
                Assert.IsNotEmpty(stockList);
            }
        }
Beispiel #18
0
        protected void Application_Start()
        {
            StockRepository = new StockRepository();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            StartStockMarketSimulator();

            InitializeServiceBus();
        }
Beispiel #19
0
        private void ModificarStock(decimal cantidad, Boolean sumarastock)
        {
            if (sumarastock)
            {
                cantidad = cantidad * -1;
            }

            Stock.StockActual             = Stock.StockActual - cantidad;
            Stock.FechaUltimaModificacion = DateTime.Now;

            StockRepository.Modificar(Stock);
            StockRepository.Commit();
        }
Beispiel #20
0
        public async void UpdateAsync_ReturnsCorrectResult()
        {
            var stockCollection = new Mock <IMongoCollection <StockDocument> >();
            var context         = new Mock <IStockDbContext>();

            context.Setup(s => s.StockCollection).Returns(stockCollection.Object).Verifiable();

            var repo = new StockRepository(context.Object, mapper);

            Stock oldStock = new Stock("Tian Stock Company", "TSC", 84, 80, "NASDAQ", false);

            stockCollection.Setup(c => c.CountDocumentsAsync(
                                      It.IsAny <FilterDefinition <StockDocument> >(),
                                      It.IsAny <CountOptions>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(1);

            await repo.UpdateAsync(oldStock);

            stockCollection.Verify(c => c.ReplaceOneAsync(
                                       It.IsAny <FilterDefinition <StockDocument> >(),
                                       It.IsAny <StockDocument>(),
                                       It.IsAny <ReplaceOptions>(),
                                       It.IsAny <CancellationToken>()),
                                   Times.Once());

            Stock newStock = new Stock("Zzz Stock Company", "ZSC", 86, 82, "NASDAQ", false);

            stockCollection.Setup(c => c.CountDocumentsAsync(
                                      It.IsAny <FilterDefinition <StockDocument> >(),
                                      It.IsAny <CountOptions>(),
                                      It.IsAny <CancellationToken>()))
            .ReturnsAsync(0);

            try
            {
                await repo.UpdateAsync(newStock);
            }
            catch (Exception ex)
            {
                Assert.Equal("NotFoundInDbException", ex.GetType().Name);
                stockCollection.Verify(c => c.ReplaceOneAsync(
                                           It.IsAny <FilterDefinition <StockDocument> >(),
                                           It.IsAny <StockDocument>(),
                                           It.IsAny <ReplaceOptions>(),
                                           It.IsAny <CancellationToken>()),
                                       Times.Once());
            }

            context.Verify();
        }
        public InsertFinancialReportForm()
        {
            InitializeComponent();
            stockRepo     = new StockRepository();
            financialRepo = new FinancialReportRepository();

            AssetTextBox.KeyPress       += new KeyPressEventHandler(AssetTextBox_KeyPress);
            LiabilitiesTextBox.KeyPress += new KeyPressEventHandler(LiabilitiesTextBox_KeyPress);
            SalesTextBox.KeyPress       += new KeyPressEventHandler(SalesTextBox_KeyPress);
            EquityTextBox.KeyPress      += new KeyPressEventHandler(EquityTextBox_KeyPress);
            GrossProfitTextBox.KeyPress += new KeyPressEventHandler(GrossProfitTextBox_KeyPress);
            NetIncomeTextBox.KeyPress   += new KeyPressEventHandler(NetIncomeTextBox_KeyPress);
            CashFlowTextBox.KeyPress    += new KeyPressEventHandler(CashFlowTextBox_KeyPress);
        }
Beispiel #22
0
        public DecreaseStockQuantityTransaction(ITwoPhaseRepository twoPhaseRepository,
                                                Dictionary <string, string> transactionParams) : base(twoPhaseRepository,
                                                                                                      transactionParams)
        {
            if (transactionParams is null ||
                _requiredTransactionParams.Any(key => !transactionParams.ContainsKey(key)))
            {
                throw new MissingTransactionParamException();
            }

            _stockRepository = TwoPhaseRepository as StockRepository;
            _logger          = ApplicationLogging.CreateLogger <DecreaseStockQuantityTransaction>();
            _logger.LogInformation($"DecreaseStockQuantityTransaction was created. Transaction Id = {TransactionId}");
        }
        public void SaveStockTest()
        {
            // Arrange
            DbContextOptions <BreadShopDatabaseContext> options =
                new DbContextOptionsBuilder <BreadShopDatabaseContext>()
                .UseInMemoryDatabase(databaseName: "BreadShopTestDatabase")
                .Options;

            using (BreadShopDatabaseContext dbContext =
                       new BreadShopDatabaseContext(options))
            {
                dbContext.Products.Add(
                    new Product()
                {
                    ProductId    = 1,
                    Ingrediants  = "ingrediants",
                    Descriptions = "descriptions",
                    Quantity     = 500,
                });

                dbContext.SaveChanges();
                IList <Product> newProduct = new List <Product>()
                {
                    new Product()
                    {
                        ProductId    = 1,
                        Ingrediants  = "ingrediants",
                        Descriptions = "descriptions",
                        Quantity     = 500,
                    }
                };

                Stock stock =
                    new Stock()
                {
                    TotalPrice    = 5000,
                    TotalQuantity = 500,
                };

                StockRepository stockRepository = new StockRepository(dbContext);
                stockRepository.SaveStock(stock, newProduct);
                int productsCount = dbContext.Set <Stock>()
                                    .Where(saveProduct =>
                                           stock.StockId == stock.StockId).Count();

                //Assert
                Assert.Equal(1, productsCount);
                dbContext.Dispose();
            }
        }
Beispiel #24
0
        public CategoryStockViewModel GetStockByCategory(int categoryId)
        {
            StockRepository    stockRepository    = new StockRepository();
            CategoryRepository categoryRepository = new CategoryRepository();
            var dataList = stockRepository.GetStockByCategory(categoryId);

            CategoryStockViewModel results = new CategoryStockViewModel()
            {
                CategoryID   = categoryId,
                CategoryName = categoryRepository.GetCategoryName(categoryId),
                StockList    = ConvertStockListViewModel(dataList)
            };

            return(results);
        }
        public void GetDefaultWarehouse_OneWarehouseTest()
        {
            var featuresService = Substitute.For <FeaturesService>();

            featuresService.Available(WorkwearFeature.Warehouses).Returns(true);
            using (var uow = UnitOfWorkFactory.CreateWithoutRoot()) {
                var warehouse1 = new Warehouse();
                warehouse1.Name = "Единственный";
                uow.Save(warehouse1);
                uow.Commit();

                var defaultWarehouse = new StockRepository().GetDefaultWarehouse(uow, new FeaturesService(), 0);
                Assert.That(defaultWarehouse.Name, Is.EqualTo("Единственный"));
            }
        }
Beispiel #26
0
        public ActionResult Edit(int id, StockControl stockControl)
        {
            try
            {
                StockControlRepository.Update(stockControl);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                var stocks = StockRepository.GetStocks();
                ViewData["StockId"] = new SelectList(stocks, "Id", "StockName");
                return(View());
            }
        }
        public void AddBranch_AddSingleBranch_ReturnCreatedBranchAndDefaultDataBranch()
        {
            //Arrange
            StockRepository stubStockRepository = FakesFactory.CreateStockRepositoryFake();

            //Act
            IBranch <StockEntity> allBranch = new RedisBranch <StockEntity>();

            allBranch.SetBranchId("BRANCH_ALL");
            allBranch.FilterBy(i => i.IsActive).GroupBy("All", i => "All");
            stubStockRepository.AddBranch(allBranch);

            //Assert
            Assert.Equal(20, stubStockRepository.GetBranches().Count());
        }
        private List <StockItem> InitializeWithStock(params StockItem[] stock)
        {
            var items = new List <StockItem>();

            items.AddRange(stock);

            _importer = Substitute.For <IDataImporter>();
            _importer
            .ImportStock()
            .Returns(items);

            _stockRepository = new StockRepository(_importer);

            return(items);
        }
Beispiel #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SkuLookupDialog" /> class.
        /// </summary>
        /// <param name="bookingDialog">The booking dialog.</param>
        public SkuLookupDialog(BookingDialog bookingDialog, StockRepository stockRepository) : base(nameof(SkuLookupDialog))
        {
            _stockRepo = stockRepository;

            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
            AddDialog(bookingDialog);
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
            {
                LookupStepAsync,
                RouteStockStepAsync,
                FinalStepAsync,
            }));
            InitialDialogId = nameof(WaterfallDialog);
        }
Beispiel #30
0
        private void CargarProducto(ProductoCompleto original)
        {
            txtCodigo.Text = original.Descripcion;
            //Busco el stock para traer la cantidad
            Stock = StockRepository.Obtener(s => s.ProductoId == original.ProductoId &&
                                            s.MaxiKioscoId == AppSettings.MaxiKioscoId);

            Producto    = original;
            Descripcion = original.Descripcion;
            Precio      = original.PrecioConIVA;
            // controlo que haya stock de este producto

            CantidadOriginal = Stock == null ? "0" : Stock.StockActual.ToString();
            HabilitarEdicion();
        }
        public ActionResult DeleteConfirmed(int id)
        {
            var stock = StockRepository.GetStockById(id);

            try
            {
                StockRepository.Remove(stock);

                return(RedirectToAction(nameof(Index)));
            }
            catch
            {
                return(View());
            }
        }
        public void StockRepositoryTest_AddStock_Sucess()
        {
            try
            {
                StockRepository stoqueRepository = new StockRepository();
                Stock stock = stoqueRepository.GetByIDs(1);
                stock.Quantity = 10;
                int actual = stoqueRepository.AddStock(stock);
                Assert.AreEqual(1, actual);
            }
            catch (Exception)
            {

                throw;
            }
        }
        public Stock GetStockBySymbol(string symbol)
        {
            if (string.IsNullOrWhiteSpace(symbol))
            {
                throw new ArgumentNullException("smybol");
            }

            using (var context = ContainerHelper.Instance.Resolve<IRepositoryContext>())
            {
                try
                {
                    var repository = new StockRepository(context);
                    return repository.GetStockBySymbol(symbol);
                }
                catch
                {
                    //这里可能会因为Repository<Stock>.Single()找不到记录抛出异常
                    return null;
                }
            }
        }
 public void StockRepositoryTest_CreateStock_1()
 {
     StockRepository stoqueRepository = new StockRepository();
     int actual = stoqueRepository.Creates(new Stock { ManageStock = true, MaximunQuantity = 20, MinimunQuantity = 100, ProductID = 2, Quantity = 50 });
     Assert.AreEqual(expected: 1, actual: actual);
 }
 public void StockRepositoryTest_UpdateStock_1()
 {
     StockRepository stoqueRepository = new StockRepository();
     int actual = stoqueRepository.Update(new Stock { ManageStock = true, MaximunQuantity = 20, MinimunQuantity = 100, ProductID = 3, Quantity = 50 });
     Assert.AreEqual(expected: 1, actual: actual, message: "Fail");
 }
Beispiel #36
0
        private void Aceptar()
        {
            if (PopupAbierto)
                PopupAbierto = false;
            else if (MensajeErrorAbierto)
                MensajeErrorAbierto = false;
            else if (ConfirmacionAbierta)
            {
                ConfirmacionAbierta = false;
            }
            else
            {
                if (dgvListado.Rows.Count > 0)
                {
                    var lineas = new List<VentaProducto>();
                    decimal total = 0;
                    decimal costoTotal = 0;
                    for (int i = 0; i <= dgvListado.Rows.Count - 1; i++)
                    {
                        var linea = new VentaProducto();

                        linea.Cantidad = decimal.Parse(dgvListado.Rows[i].Cells["Cantidad"].Value.ToString());
                        linea.Eliminado = false;
                        linea.Identifier = Guid.NewGuid();
                        linea.Precio = Convert.ToDecimal(dgvListado.Rows[i].Cells["Unitario"].Value.ToString().Replace("$", ""));
                        linea.ProductoId = (int)dgvListado.Rows[i].Cells["productoId"].Value;
                        linea.Costo = dgvListado.Rows[i].Cells["Costo"].Value == null
                                                ? 0
                                                : Convert.ToDecimal(dgvListado.Rows[i].Cells["Costo"].Value.ToString().Replace("$", ""));

                        var recargo = dgvListado.Rows[i].Cells["Recargo"].Value;
                        linea.EsPromocion = bool.Parse(dgvListado.Rows[i].Cells["EsPromocion"].Value.ToString());
                        linea.AdicionalPorExcepcion = recargo == null
                                                                ? (decimal?)null :
                                                                Convert.ToDecimal(recargo.ToString().Replace("$", "")) * linea.Cantidad;
                        linea.Desincronizado = true;

                        total += Convert.ToDecimal(linea.Cantidad) * linea.Precio.GetValueOrDefault();
                        costoTotal += Convert.ToDecimal(linea.Cantidad) * linea.Costo;
                        lineas.Add(linea);
                    }

                    ConfirmacionAbierta = true;
                    var frmConfirmar = new frmConfirmarVenta(total);
                    if (frmConfirmar.ShowDialog() == DialogResult.OK)
                    {
                        ConfirmacionAbierta = false;
                        var venta = new Venta
                        {
                            ImporteTotal = total,
                            CostoTotal = costoTotal,
                            Identifier = Guid.NewGuid(),
                            Eliminado = false,
                            CierreCajaId = UsuarioActual.CierreCajaIdActual,
                            FechaVenta = DateTime.Now,
                            VentaProductos = lineas
                        };
                        venta.CierreCajaId = UsuarioActual.CierreCajaIdActual;
                        var stockRepository = new StockRepository();
                        var stockTransaccionRepository = new EFRepository<StockTransaccion>();

                        var seAgregoStock = false;
                        var seAgregoTransaccion = false;

                        //Agrego primero a la coleccion las lineas secundarias correspondientes a promociones
                        var secundarias = new List<VentaProducto>();
                        foreach (var linea in lineas.Where(l => l.EsPromocion))
                        {
                            var productos = ProductoPromocionRepository.Listado().Where(p => p.PadreId == linea.ProductoId && !p.Eliminado).ToList();
                            secundarias.AddRange(productos.Select(p => new VentaProducto()
                                                                       {
                                                                           Cantidad = p.Unidades * linea.Cantidad,
                                                                           ProductoId = p.HijoId
                                                                       }));
                        }

                        lineas.AddRange(secundarias);

                        foreach (var line in lineas)
                        {
                            var stockSt = new StockTransaccion
                            {
                                Cantidad = line.Cantidad * (-1),
                                StockTransaccionTipoId = 1,
                                Identifier = Guid.NewGuid(),
                                Desincronizado = true
                            };

                            var stock = stockRepository.ObtenerByProducto(line.ProductoId, AppSettings.MaxiKioscoId);
                            if (stock != null)
                            {
                                stockSt.StockId = stock.StockId;
                                stock.StockActual = stock.StockActual - Convert.ToDecimal(line.Cantidad);
                                stockTransaccionRepository.Agregar(stockSt);
                                stockRepository.Modificar(stock);
                                seAgregoTransaccion = true;
                                seAgregoStock = true;
                            }
                            else
                            {
                                stock = new Stock()
                                {
                                    Identifier = Guid.NewGuid(),
                                    MaxiKioscoId = AppSettings.MaxiKioscoId,
                                    ProductoId = line.ProductoId,
                                    StockActual = -line.Cantidad,
                                    OperacionCreacion = "Venta en DESKTOP",
                                    FechaCreacion = DateTime.Now,
                                    StockTransacciones = new List<StockTransaccion> { stockSt }
                                };
                                stockRepository.Agregar(stock);
                                seAgregoStock = true;
                            }
                        }

                        if (seAgregoStock)
                            stockRepository.Commit();
                        if (seAgregoTransaccion)
                            stockTransaccionRepository.Commit();

                        Repository.Agregar(venta);
                        if (Repository.Commit())
                        {
                            Limpiar();
                        }
                        else
                        {
                            Mensajes.Guardar(false, "Ha ocurrido un error al registrar la venta. Por favor intente nuevamente");
                        }
                        ReiniciarVenta();
                    }
                }
            }
        }
 public StockUnitOfWork()
 {
     Stock = new StockRepository(_context);
     FavoriteStock = new FavoriteStockRepository(_context);
 }