コード例 #1
0
        public async Task <bool> HandleAsync(FinishShoppingListCommand command, CancellationToken cancellationToken)
        {
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var shoppingList = await shoppingListRepository.FindByAsync(command.ShoppingListId, cancellationToken);

            if (shoppingList == null)
            {
                throw new DomainException(new ShoppingListNotFoundReason(command.ShoppingListId));
            }

            cancellationToken.ThrowIfCancellationRequested();

            IShoppingList nextShoppingList = shoppingList.Finish(command.CompletionDate);

            cancellationToken.ThrowIfCancellationRequested();

            using var transaction = await transactionGenerator.GenerateAsync(cancellationToken);

            await shoppingListRepository.StoreAsync(shoppingList, cancellationToken);

            await shoppingListRepository.StoreAsync(nextShoppingList, cancellationToken);

            await transaction.CommitAsync(cancellationToken);

            return(true);
        }
コード例 #2
0
        public async Task <IEnumerable <ItemSearchReadModel> > HandleAsync(ItemSearchQuery query, CancellationToken cancellationToken)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            if (string.IsNullOrWhiteSpace(query.SearchInput))
            {
                return(Enumerable.Empty <ItemSearchReadModel>());
            }

            var store = await storeRepository.FindByAsync(new StoreId(query.StoreId.Value), cancellationToken);

            if (store == null)
            {
                throw new DomainException(new StoreNotFoundReason(query.StoreId));
            }

            IEnumerable <IStoreItem> storeItems = await itemRepository
                                                  .FindActiveByAsync(query.SearchInput.Trim(), query.StoreId, cancellationToken);

            IShoppingList shoppingList = await shoppingListRepository
                                         .FindActiveByAsync(query.StoreId, cancellationToken);

            var itemIdsOnShoppingList = shoppingList.Items.Select(item => item.Id);

            var itemsNotOnShoppingList = storeItems
                                         .Where(item => !itemIdsOnShoppingList.Contains(item.Id));

            return(await itemSearchReadModelConversionService.ConvertAsync(itemsNotOnShoppingList, store, cancellationToken));
        }
コード例 #3
0
        public static TinyShopping.ApplicationModels.ShoppingList ToModel(this IShoppingList item)
        {
            var ret = new TinyShopping.ApplicationModels.ShoppingList();

            item.MemberviseCopyTo(ret);
            return(ret);
        }
コード例 #4
0
        public ShoppingListView(IShoppingList shoppingList)
        {
            if (shoppingList is null)
            {
                throw new ArgumentNullException(nameof(shoppingList));
            }

            var items = shoppingList.Items is null ? new ShoppingListItem[0] : shoppingList.Items;

            Array.Sort(items);

            // Your milage may vary when it comes to color here. There are still a few bugs to iron
            // out in the rendering system. So far this is working in VS Code on macOS Catalina.
            Add(new ContentView($"{shoppingList.ListName}".Rgb(168, 139, 50)));
            Add(new ContentView("\n"));

            var view = new TableView <ShoppingListItem>();

            view.Items = items;
            view.AddColumn <TextSpan>(item => item.Quantity.ToString().LightGreen(), new ContentView("#".UnderlineRed()));
            view.AddColumn <TextSpan>(item => item.Name.White(), new ContentView("Items to Purchase".UnderlineRed()));
            Add(view);

            Add(new ContentView("\n"));
            Add(new ContentView("\n"));
        }
コード例 #5
0
        public ScanServiceTests()
        {
            _mockDataStore = MockHelper.GetMockDataStore();
            _shoppingList  = new ShoppingList();

            _scanService = new ScanService(_mockDataStore.Object, _shoppingList);
        }
        public IShoppingListItem CreateUnique(IShoppingList shoppingList)
        {
            var usedItemIds = shoppingList.Items.Select(i => i.Id.Value);
            var itemId      = commonFixture.NextInt(exclude: usedItemIds);

            return(Create(itemId));
        }
        internal async Task AddItemToShoppingList(IShoppingList shoppingList, IShoppingListItem item,
                                                  SectionId sectionId, CancellationToken cancellationToken)
        {
            var store = await storeRepository.FindByAsync(shoppingList.StoreId, cancellationToken);

            if (store == null)
            {
                throw new DomainException(new StoreNotFoundReason(shoppingList.StoreId));
            }

            if (!store.ContainsSection(sectionId))
            {
                throw new DomainException(new SectionInStoreNotFoundReason(sectionId, store.Id));
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (!shoppingList.Sections.Any(s => s.Id == sectionId))
            {
                var section = shoppingListSectionFactory.CreateEmpty(sectionId);
                shoppingList.AddSection(section);
            }

            shoppingList.AddItem(item, sectionId);
        }
        private async Task StoreModifiedListAsync(Entities.ShoppingList existingShoppingListEntity,
                                                  IShoppingList shoppingList, CancellationToken cancellationToken)
        {
            var shoppingListEntityToStore = toEntityConverter.ToEntity(shoppingList);
            var onListMappings            = existingShoppingListEntity.ItemsOnList.ToDictionary(map => map.ItemId);

            dbContext.Entry(shoppingListEntityToStore).State = EntityState.Modified;
            foreach (var map in shoppingListEntityToStore.ItemsOnList)
            {
                cancellationToken.ThrowIfCancellationRequested();
                if (onListMappings.TryGetValue(map.ItemId, out var existingMapping))
                {
                    // mapping was modified
                    map.Id = existingMapping.Id;
                    dbContext.Entry(map).State = EntityState.Modified;
                    onListMappings.Remove(map.ItemId);
                }
                else
                {
                    // mapping was added
                    dbContext.Entry(map).State = EntityState.Added;
                }
            }

            // mapping was deleted
            foreach (var map in onListMappings.Values)
            {
                dbContext.Entry(map).State = EntityState.Deleted;
            }

            cancellationToken.ThrowIfCancellationRequested();

            await dbContext.SaveChangesAsync();
        }
        public async Task ConvertAsync_WithValidData_ShouldConvertToReadModel(IShoppingList list, IStore store,
                                                                              IEnumerable <IStoreItem> items, IEnumerable <IItemCategory> itemCategories,
                                                                              IEnumerable <IManufacturer> manufacturers, ShoppingListReadModel expected)
        {
            // Arrange
            var fixture                    = commonFixture.GetNewFixture();
            var storeRepositoryMock        = new StoreRepositoryMock(fixture);
            var itemRepositoryMock         = new ItemRepositoryMock(fixture);
            var itemCategoryRepositoryMock = new ItemCategoryRepositoryMock(fixture);
            var manufacturerRepositoryMock = new ManufacturerRepositoryMock(fixture);

            var service = fixture.Create <ShoppingListReadModelConversionService>();

            storeRepositoryMock.SetupFindByAsync(store.Id, store);
            itemRepositoryMock.SetupFindByAsync(items.Select(i => i.Id), items);
            itemCategoryRepositoryMock.SetupFindByAsync(itemCategories.Select(cat => cat.Id), itemCategories);
            manufacturerRepositoryMock.SetupFindByAsync(manufacturers.Select(m => m.Id), manufacturers);

            // Act
            var result = await service.ConvertAsync(list, default);

            // Assert
            using (new AssertionScope())
            {
                result.Should().BeEquivalentTo(expected);
            }
        }
 public void VerifyStoreAsyncOnce(IShoppingList shoppingList)
 {
     mock.Verify(
         i => i.StoreAsync(
             It.Is <IShoppingList>(list => list == shoppingList),
             It.IsAny <CancellationToken>()),
         Times.Once);
 }
 public void SetupFindActiveByAsync(StoreId storeId, IShoppingList returnValue)
 {
     mock
     .Setup(i => i.FindActiveByAsync(
                It.Is <StoreId>(id => id == storeId),
                It.IsAny <CancellationToken>()))
     .Returns(Task.FromResult(returnValue));
 }
コード例 #12
0
        public static RootCommand UseListCommand(this RootCommand rootCommand, IShoppingList shoppingList)
        {
            var removeCommand = new Command("list", "Displays the list of items in the shopping list");

            removeCommand.Handler = CommandHandler.Create <IConsole>((console) => shoppingList.Print(console));
            rootCommand.AddCommand(removeCommand);
            return(rootCommand);
        }
コード例 #13
0
 private static bool Equals(IShoppingList srcList, IShoppingList dstList, ITaxRateTable taxTable)
 {
     return(srcList != null && dstList != null &&
            srcList.IsEmpty() == dstList.IsEmpty() &&
            srcList.GetAllItemCount() == dstList.GetAllItemCount() &&
            srcList.Sum(null) == dstList.Sum(null) &&
            srcList.Sum(taxTable) == dstList.Sum(taxTable));
 }
 public void SetupFindByAsync(ShoppingListId shoppingListId,
                              IShoppingList returnValue)
 {
     mock
     .Setup(instance => instance.FindByAsync(
                It.Is <ShoppingListId>(id => id == shoppingListId),
                It.IsAny <CancellationToken>()))
     .Returns(Task.FromResult(returnValue));
 }
コード例 #15
0
        private static void Main(string[] args)
        {
            Console.Title = "Shopping List";

            Console.WriteLine("".PadRight(60, '*'));
            Console.WriteLine("Shopping List Program Start.");

            Console.WriteLine("Create shooping manager.");
            IShoppingManager shoppingManager = new ShoppingManager();

            while (true)
            {
                Console.WriteLine("Create shooping list.");
                IShoppingList newShowList = shoppingManager.CreateRandomShoppingList();
                IShoppingList checkList   = new DotNetTopic.Level2.Tudh.ShoppingList(DateTime.Now);
                Console.WriteLine("".PadRight(60, '-'));

                Console.WriteLine("Shopping List Detail");
                Console.WriteLine("Date:\t{0}", newShowList.Time);
                Console.WriteLine("{0,-20}{1,12}{2,12}{3,12}", "Name", "Count", "Price(¥)", "Rate(%)");
                foreach (var each in newShowList)
                {
                    checkList.Add(each, newShowList.GetItemCount(each));
                    Console.WriteLine("{0,-20}{1,12}{2,12:f2}{3,12:f1}", each.Name, newShowList.GetItemCount(each), each.Price, shoppingManager.CurrentTaxRateTable.GetTaxRate(each.Type) * 100);
                }

                Console.WriteLine("                    \t{0,-10}{1,10}", "计算值", "参考值");

                var oldColor = Console.ForegroundColor;
                if (!Equals(newShowList, checkList, shoppingManager.CurrentTaxRateTable))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }

                Console.WriteLine("Total Count:        \t{0,-10}{1,16}", newShowList.GetAllItemCount(), checkList.GetAllItemCount());
                Console.WriteLine("Total Price(Origin):\t{0,-10:f1}{1,16:f1}", newShowList.Sum(e => e.Price * newShowList.GetItemCount(e)), checkList.Sum(e => e.Price * newShowList.GetItemCount(e)));
                Console.WriteLine("Total Price(No Tax):\t{0,-10:f1}{1,16:f1}", newShowList.Sum(null), checkList.Sum(null));
                Console.WriteLine("Total Price:        \t{0,-10:f1}{1,16:f1}", newShowList.Sum(shoppingManager.CurrentTaxRateTable), checkList.Sum(shoppingManager.CurrentTaxRateTable));

                Console.ForegroundColor = oldColor;

                Console.WriteLine("".PadRight(60, '-'));
                Console.WriteLine();

                Console.WriteLine("Press any key to continue, press q to quit.");
                if (Console.ReadLine() == "q")
                {
                    break;
                }
            }

            Console.WriteLine("Shopping List Program End.");
            Console.WriteLine("".PadRight(60, '*'));

            Console.ReadLine();
        }
コード例 #16
0
ファイル: FileRepositoryTests.cs プロジェクト: toktuff/prep
        public void SetUp()
        {
            _mockery = new MockRepository();
            _mockFileSystem = _mockery.DynamicMock<IFileSystem>();
            _mockShoppingList = _mockery.DynamicMock<IShoppingList>();
            _id = Guid.NewGuid();
            _nameCorrespondingToId = _id.ToString("N").ToUpper();

            _mockShoppingList.Stub(x => x.Id).Return(_id);
        }
 public void VerifyAddItemToShoppingListOnce(IShoppingList shoppingList, TemporaryItemId temporaryItemId,
                                             SectionId sectionId, float quantity)
 {
     mock.Verify(i => i.AddItemToShoppingList(
                     shoppingList,
                     temporaryItemId,
                     sectionId,
                     quantity,
                     It.IsAny <CancellationToken>()));
 }
コード例 #18
0
        public ShoppingListVM(IShoppingList model)
        {
            _model         = model;
            AddItemCommand = new Command(() =>
            {
                IShoppingItem newItem = _model.CreateNewItem();
                _model.Items.Add(newItem);
                Items.Add(new ShoppingItemVM(newItem));
            });

            Items = new ObservableCollection <ShoppingItemVM>(model.Items.Select(modelItem => new ShoppingItemVM(modelItem)));
        }
            public IStore CreateStore(IShoppingList shoppingList, SectionId sectionId)
            {
                var sectionDef = StoreSectionDefinition.FromId(sectionId);
                var section    = StoreSectionFixture.Create(sectionDef);

                var storeDef = new StoreDefinition
                {
                    Id       = shoppingList.StoreId,
                    Sections = section.ToMonoList()
                };

                return(StoreFixture.CreateValid(storeDef));
            }
コード例 #20
0
        public IStoreItem CreateValidFor(IShoppingList shoppingList)
        {
            var storeDefinition = StoreDefinition.FromId(shoppingList.StoreId);
            var store           = storeFixture.Create(storeDefinition);

            var availabilities = storeItemAvailabilityFixture.CreateManyValidWith(store, 4);
            var definition     = new StoreItemDefinition
            {
                Availabilities = availabilities
            };

            return(CreateValid(definition));
        }
        private async Task StoreAsNewListAsync(IShoppingList shoppingList, CancellationToken cancellationToken)
        {
            var entity = toEntityConverter.ToEntity(shoppingList);

            dbContext.Entry(entity).State = EntityState.Added;
            foreach (var onListMap in entity.ItemsOnList)
            {
                dbContext.Entry(onListMap).State = EntityState.Added;
            }

            cancellationToken.ThrowIfCancellationRequested();

            await dbContext.SaveChangesAsync();
        }
コード例 #22
0
        private ShoppingListReadModel ToReadModel(IShoppingList shoppingList, IStore store,
                                                  Dictionary <ItemId, IStoreItem> storeItems, Dictionary <ItemCategoryId, IItemCategory> itemCategories,
                                                  Dictionary <ManufacturerId, IManufacturer> manufacturers)
        {
            List <ShoppingListSectionReadModel> sectionReadModels = new List <ShoppingListSectionReadModel>();

            foreach (var section in shoppingList.Sections)
            {
                List <ShoppingListItemReadModel> itemReadModels = new List <ShoppingListItemReadModel>();
                foreach (var item in section.Items)
                {
                    var storeItem = storeItems[item.Id];

                    var itemReadModel = new ShoppingListItemReadModel(
                        item.Id,
                        storeItem.Name,
                        storeItem.IsDeleted,
                        storeItem.Comment,
                        storeItem.IsTemporary,
                        storeItem.Availabilities.First(av => av.StoreId == store.Id).Price,
                        storeItem.QuantityType.ToReadModel(),
                        storeItem.QuantityInPacket,
                        storeItem.QuantityTypeInPacket.ToReadModel(),
                        storeItem.ItemCategoryId == null ? null : itemCategories[storeItem.ItemCategoryId].ToReadModel(),
                        storeItem.ManufacturerId == null ? null : manufacturers[storeItem.ManufacturerId].ToReadModel(),
                        item.IsInBasket,
                        item.Quantity);

                    itemReadModels.Add(itemReadModel);
                }

                var storeSection = store.Sections.First(s => s.Id == section.Id);

                var sectionReadModel = new ShoppingListSectionReadModel(
                    section.Id,
                    storeSection.Name,
                    storeSection.SortingIndex,
                    storeSection.IsDefaultSection,
                    itemReadModels);

                sectionReadModels.Add(sectionReadModel);
            }

            return(new ShoppingListReadModel(
                       shoppingList.Id,
                       shoppingList.CompletionDate,
                       store.ToShoppingListStoreReadModel(),
                       sectionReadModels));
        }
コード例 #23
0
        public void AddSection_WithSectionAlreadyInShoppingList_ShouldThrowDomainException()
        {
            IShoppingList        shoppingList = shoppingListFixture.CreateValid();
            IShoppingListSection section      = commonFixture.ChooseRandom(shoppingList.Sections);

            // Act
            Action action = () => shoppingList.AddSection(section);

            // Assert
            using (new AssertionScope())
            {
                action.Should().Throw <DomainException>()
                .Where(e => e.Reason.ErrorCode == ErrorReasonCode.SectionAlreadyInShoppingList);
            }
        }
        public async Task AddItemToShoppingList(IShoppingList shoppingList, TemporaryItemId temporaryItemId,
                                                SectionId sectionId, float quantity, CancellationToken cancellationToken)
        {
            if (shoppingList is null)
            {
                throw new ArgumentNullException(nameof(shoppingList));
            }
            if (temporaryItemId is null)
            {
                throw new ArgumentNullException(nameof(temporaryItemId));
            }

            IStoreItem storeItem = await LoadItem(temporaryItemId, cancellationToken);

            await AddItemToShoppingList(shoppingList, storeItem, sectionId, quantity, cancellationToken);
        }
        internal async Task AddItemToShoppingList(IShoppingList shoppingList, IStoreItem storeItem,
                                                  SectionId sectionId, float quantity, CancellationToken cancellationToken)
        {
            ValidateItemIsAvailableAtStore(storeItem, shoppingList.StoreId, out var availability);

            if (sectionId == null)
            {
                sectionId = availability.DefaultSectionId;
            }

            cancellationToken.ThrowIfCancellationRequested();

            IShoppingListItem shoppingListItem = CreateShoppingListItem(storeItem.Id, quantity);

            await AddItemToShoppingList(shoppingList, shoppingListItem, sectionId, cancellationToken);
        }
コード例 #26
0
        public void AddItem_WithSectionNotFound_ShouldThrowDomainException()
        {
            IShoppingList     shoppingList = shoppingListFixture.CreateValid();
            IShoppingListItem item         = shoppingListItemFixture.CreateUnique(shoppingList);
            var existingSectionIds         = shoppingList.Sections.Select(s => s.Id.Value);
            int sectionId = commonFixture.NextInt(exclude: existingSectionIds);

            // Act
            Action action = () => shoppingList.AddItem(item, new SectionId(sectionId));

            // Assert
            using (new AssertionScope())
            {
                action.Should().Throw <DomainException>()
                .Where(e => e.Reason.ErrorCode == ErrorReasonCode.SectionInStoreNotFound);
            }
        }
コード例 #27
0
        public void AddSection_WithNewSection_ShouldThrowDomainException()
        {
            IShoppingList shoppingList       = shoppingListFixture.CreateValid();
            var           existingSectionIds = shoppingList.Sections.Select(s => s.Id.Value);

            var sectionDef = ShoppingListSectionDefinition.FromId(commonFixture.NextInt(existingSectionIds));
            IShoppingListSection section = shoppingListSectionFixture.CreateValid(sectionDef);

            // Act
            shoppingList.AddSection(section);

            // Assert
            using (new AssertionScope())
            {
                shoppingList.Sections.Should().Contain(section);
            }
        }
コード例 #28
0
        public static RootCommand UseAddItemCommand(this RootCommand rootCommand, IShoppingList shoppingList)
        {
            var addCommmand = new Command("add-item", "Adds a grocery item to the list")
            {
                new Option <int>(new string[] { "--quantity", "-q" }, () => 1, "The number of items to add (between 1 and 999)")
                .WithinRange(1, 999),
                new Argument <string>("name")
                {
                    Description = "The name of the grocery item"
                }
            };

            addCommmand.AddAlias("add");

            addCommmand.Handler = CommandHandler.Create <IConsole, string, int>(async(console, name, quantity) =>
                                                                                await shoppingList.AddItemsAsync(console, name, quantity));

            rootCommand.AddCommand(addCommmand);
            return(rootCommand);
        }
        public async Task StoreAsync(IShoppingList shoppingList, CancellationToken cancellationToken)
        {
            if (shoppingList == null)
            {
                throw new ArgumentNullException(nameof(shoppingList));
            }

            if (shoppingList.Id.Value <= 0)
            {
                await StoreAsNewListAsync(shoppingList, cancellationToken);

                return;
            }

            cancellationToken.ThrowIfCancellationRequested();

            var listEntity = await FindEntityByIdAsync(shoppingList.Id);

            cancellationToken.ThrowIfCancellationRequested();

            await StoreModifiedListAsync(listEntity, shoppingList, cancellationToken);
        }
コード例 #30
0
        public async Task <ShoppingListReadModel> ConvertAsync(IShoppingList shoppingList, CancellationToken cancellationToken)
        {
            if (shoppingList is null)
            {
                throw new System.ArgumentNullException(nameof(shoppingList));
            }

            var ItemIds   = shoppingList.Items.Select(i => i.Id);
            var itemsDict = (await itemRepository.FindByAsync(ItemIds, cancellationToken))
                            .ToDictionary(i => i.Id);

            var itemCategoryIds    = itemsDict.Values.Where(i => i.ItemCategoryId != null).Select(i => i.ItemCategoryId);
            var itemCategoriesDict = (await itemCategoryRepository.FindByAsync(itemCategoryIds, cancellationToken))
                                     .ToDictionary(cat => cat.Id);

            var manufacturerIds   = itemsDict.Values.Where(i => i.ManufacturerId != null).Select(i => i.ManufacturerId);
            var manufacturersDict = (await manufacturerRepository.FindByAsync(manufacturerIds, cancellationToken))
                                    .ToDictionary(man => man.Id);

            IStore store = await storeRepository.FindByAsync(shoppingList.StoreId, cancellationToken);

            return(ToReadModel(shoppingList, store, itemsDict, itemCategoriesDict, manufacturersDict));
        }
コード例 #31
0
 public ShoppingController(IConfiguration configuration, ILogger <ShoppingController> logger, IShoppingList shoppingList)
 {
     _configuration = configuration;
     _logger        = logger;
     _shoppingList  = shoppingList;
 }
コード例 #32
0
 public void Add(IShoppingList list)
 {
     //   _fileSystem.Save(list.Id.ToString("N"), new MemoryStream());
     _fileSystem.Save(list.Id.ToString("N").ToUpper(), null);
 }