コード例 #1
0
        public async Task <IActionResult> GetCustomer(Guid customerId)
        {
            CustomerOutput output = await _getCustomerDetailsUseCase.Execute(customerId);

            _presenter.Populate(output);
            return(_presenter.ViewModel);
        }
コード例 #2
0
        public async Task Process(GetCustomerDetailsInput input)
        {
            Customer customer = await customerReadOnlyRepository.Get(input.CustomerId);

            if (customer == null)
            {
                throw new CustomerNotFoundException($"The customer {input.CustomerId} does not exist or it was not processed yet.");
            }

            List <Order> orders = await orderReadOnlyRepository.GetByCustomer(input.CustomerId);

            List <OrderOutput> orderOutputs = new List <OrderOutput>();

            if (orders.Count == 0)
            {
                throw new CustomerNotFoundException($"No order found for customer {input.CustomerId}.");
            }
            else
            {
                foreach (var item in orders)
                {
                    OrderOutput orderOutput = outputConverter.Map <OrderOutput>(item);
                    orderOutputs.Add(orderOutput);
                }
            }


            CustomerOutput output = outputConverter.Map <CustomerOutput>(customer);

            output = new CustomerOutput(customer.Id, customer.PIN.Text, customer.Name.Text, orderOutputs);

            outputBoundary.Populate(output);
        }
コード例 #3
0
 public CheckoutOutput(CustomerOutput customer, BasketOutput basket, DateTime orderDate, double totalPrice)
 {
     Customer   = customer;
     Basket     = basket;
     OrderDate  = orderDate;
     TotalPrice = totalPrice;
 }
コード例 #4
0
        public async Task <CustomerOutput> Execute(Guid customerId)
        {
            Customer customer = await _customerReadOnlyRepository.Get(customerId);

            if (customer == null)
            {
                throw new CustomerNotFoundException($"The customer {customerId} does not exists or is not processed yet.");
            }

            List <AccountOutput> accounts = new List <AccountOutput> ();

            foreach (Guid accountId in customer.Accounts.ToReadOnlyCollection())
            {
                Account account = await _accountReadOnlyRepository.Get(accountId);

                if (account != null)
                {
                    AccountOutput accountOutput = new AccountOutput(account);
                    accounts.Add(accountOutput);
                }
            }

            CustomerOutput output = new CustomerOutput(customer, accounts);

            return(output);
        }
コード例 #5
0
        /// <summary>
        /// Метод получает одно задание заказчика.
        /// </summary>
        /// <param name="userName">Логин юзера.</param>
        /// <param name="taskId">Id задачи. Может быть null.</param>
        /// <returns>Коллекцию заданий.</returns>
        async Task <IList> GetSingleTask(string userName, long?taskId)
        {
            // Выбирает объект задачи, который нужно редактировать.
            TaskEntity oEditTask = await _postgre.Tasks.Where(t => t.TaskId == taskId).FirstOrDefaultAsync();

            // Выбирает список специализаций конкретной категории по коду категории.
            IList aTaskSpecializations = await _postgre.TaskCategories
                                         .Where(c => c.CategoryCode.Equals(oEditTask.CategoryCode))
                                         .Select(s => s.Specializations)
                                         .FirstOrDefaultAsync();

            string specName = string.Empty;

            // Выбирает название специализации.
            foreach (Specialization spec in aTaskSpecializations)
            {
                if (spec.SpecCode.Equals(oEditTask.SpecCode))
                {
                    specName = spec.SpecName;
                }
            }

            // Получит логин и иконку профиля заказчика задания.
            CustomerOutput customer = await _userService.GetCustomerLoginByTaskId(taskId);

            // TODO: отрефачить этот метод, чтоб не обращаться два раза к БД за получением задания.
            var oTask = await(from tasks in _postgre.Tasks
                              join categories in _postgre.TaskCategories on tasks.CategoryCode equals categories.CategoryCode
                              join statuses in _postgre.TaskStatuses on tasks.StatusCode equals statuses.StatusCode
                              where tasks.TaskId == taskId
                              select new
            {
                tasks.CategoryCode,
                tasks.CountOffers,
                tasks.CountViews,
                tasks.OwnerId,
                tasks.SpecCode,
                categories.CategoryName,
                specName,
                tasks.StatusCode,
                statuses.StatusName,
                taskBegda = string.Format("{0:f}", tasks.TaskBegda),
                //taskEndda = string.Format("{0:f}", tasks.TaskEndda),
                tasks.TaskEndda,
                tasks.TaskTitle,
                tasks.TaskDetail,
                tasks.TaskId,
                taskPrice = string.Format("{0:0,0}", tasks.TaskPrice),
                tasks.TypeCode,
                userName,
                customerLogin       = customer.UserName,
                customerProfileIcon = customer.UserIcon
            })
                        .ToListAsync();

            return(oTask);
        }
コード例 #6
0
 public RentOutput(Rent rent)
 {
     Id                 = rent.Id;
     RentDate           = rent.RentDate;
     rentExpirationDate = rent.rentExpirationDate;
     Status             = rent.Status;
     FullPrice          = rent.FullPrice;
     CustomerId         = rent.CustomerId;
     Customer           = new CustomerOutput(rent.Customer);
     Items              = new List <RentItemOutput>(rent.Items.Select(item => new RentItemOutput(item)));
 }
コード例 #7
0
        public async Task Process(RegisterInput input)
        {
            Customer customer = new Customer(input.PIN, input.Name);

            await customerWriteOnlyRepository.Add(customer);

            CustomerOutput customerOutput = outputConverter.Map <CustomerOutput>(customer);

            RegisterOutput output = new RegisterOutput(customerOutput);

            outputBoundary.Populate(output);
        }
コード例 #8
0
        /// <summary>
        /// Метод получит логин и иконку профиля заказчика по Id его задания.
        /// </summary>
        /// <param name="taskId">Id задания.</param>
        /// <returns>Данные заказчика.</returns>
        public async Task <CustomerOutput> GetCustomerLoginByTaskId(long?taskId)
        {
            try
            {
                if (taskId <= 0)
                {
                    throw new NotFoundTaskIdException(taskId);
                }

                // Получит Id заказчика, который создал задание.
                string customerId = await _postgre.Tasks
                                    .Where(t => t.TaskId == taskId)
                                    .Select(t => t.OwnerId)
                                    .FirstOrDefaultAsync();

                // Если заказчика задания с таким OwnerId не найдено.
                if (string.IsNullOrEmpty(customerId))
                {
                    throw new NotFoundTaskCustomerIdException(customerId);
                }

                // Найдет логин и иконку профиля заказчика задания и мапит к типу CustomerOutput.
                MapperConfiguration config = new MapperConfiguration(cfg => cfg.CreateMap <UserEntity, CustomerOutput>());
                Mapper         mapper      = new Mapper(config);
                CustomerOutput customer    = mapper.Map <CustomerOutput>(await _postgre.Users
                                                                         .Where(u => u.Id
                                                                                .Equals(customerId))
                                                                         .FirstOrDefaultAsync());

                // Если логина заказчика задания не найдено.
                if (!string.IsNullOrEmpty(customer.UserName))
                {
                    // Если у заказчика не установлена иконка профиля, то запишет ее по дефолту.
                    if (string.IsNullOrEmpty(customer.UserIcon))
                    {
                        customer.UserIcon = NoPhotoUrl.NO_PHOTO;
                    }

                    return(customer);
                }

                throw new NotFoundCustomerLoginException();
            }

            catch (Exception ex)
            {
                Logger _logger = new Logger(_db, ex.GetType().FullName, ex.Message.ToString(), ex.StackTrace);
                _ = _logger.LogCritical();
                throw new Exception(ex.Message.ToString());
            }
        }
コード例 #9
0
        public void Populate(CustomerOutput output, Controller controller)
        {
            List <AccountDetailsModel> accounts = new List <AccountDetailsModel>();

            foreach (var account in output.Accounts)
            {
                accounts.Add(new AccountDetailsModel(
                                 account.AccountId,
                                 account.CurrentBalance));
            }

            CustomerDetailsModel model = new CustomerDetailsModel(
                output.CustomerId,
                output.Personnummer,
                output.Name,
                accounts
                );

            ViewModel = controller.View(model);
        }
コード例 #10
0
        public async Task Process(AddBasketInput input)
        {
            Customer customer = await customerReadOnlyRepository.Get(input.CustomerId);

            if (customer == null)
            {
                throw new CustomerNotFoundException($"The customer {input.CustomerId} does not exist or it was not processed yet.");
            }

            Basket basket = new Basket(customer.Id);

            await basketWriteOnlyRepository.Add(basket);

            CustomerOutput customerOutput = outputConverter.Map <CustomerOutput>(customer);
            BasketOutput   basketOutput   = outputConverter.Map <BasketOutput>(basket);

            AddBasketOutput output = new AddBasketOutput(customerOutput, basketOutput);

            outputBoundary.Populate(output);
        }
コード例 #11
0
        public async Task Process(RegisterInput message)
        {
            Customer customer = new Customer(message.PIN, message.Name);

            Account account = new Account();

            account.Open(customer.Id, new Credit(account.Id, message.InitialAmount));
            customer.Register(account.Id);

            var customerEvents = customer.GetEvents();
            var accountEvents  = account.GetEvents();

            await bus.Publish(customerEvents);

            await bus.Publish(accountEvents);

            //
            // To ensure the Customer and Account are created in the database
            // we wait for the records be available in the following queries
            // with retry
            //

            bool consumerReady = await RetryGet(async() => await customerReadOnlyRepository.Get(customer.Id)) &&
                                 await RetryGet(async() => await accountReadOnlyRepository.Get(account.Id));

            if (!consumerReady)
            {
                customer = null;
                account  = null;

                //
                // TODO: Throw exception, monitor the inconsistencies and fail fast.
                //
            }

            CustomerOutput customerOutput = responseConverter.Map <CustomerOutput>(customer);
            AccountOutput  accountOutput  = responseConverter.Map <AccountOutput>(account);
            RegisterOutput output         = new RegisterOutput(customerOutput, accountOutput);

            outputBoundary.Populate(output);
        }
コード例 #12
0
        public async Task Process(RegisterInput input)
        {
            Customer customer = new Customer(input.PIN, input.Name);

            Account account = new Account(customer.Id);
            Credit  credit  = new Credit(account.Id, input.InitialAmount);

            account.Deposit(credit);

            customer.Register(account.Id);

            await customerWriteOnlyRepository.Add(customer);

            await accountWriteOnlyRepository.Add(account, credit);

            CustomerOutput customerOutput = outputConverter.Map <CustomerOutput>(customer);
            AccountOutput  accountOutput  = outputConverter.Map <AccountOutput>(account);
            RegisterOutput output         = new RegisterOutput(customerOutput, accountOutput);

            outputBoundary.Populate(output);
        }
コード例 #13
0
        public RegisterOutput(Customer customer, Account account)
        {
            List <TransactionOutput> transactionOutputs = new List <TransactionOutput> ();

            foreach (ITransaction transaction in account.Transactions.ToReadOnlyCollection())
            {
                transactionOutputs.Add(
                    new TransactionOutput(
                        transaction.Description,
                        transaction.Amount,
                        transaction.TransactionDate));
            }

            Account = new AccountOutput(account.Id, account.GetCurrentBalance(), transactionOutputs);

            List <AccountOutput> accountOutputs = new List <AccountOutput> ();

            accountOutputs.Add(Account);

            Customer = new CustomerOutput(customer, accountOutputs);
        }
コード例 #14
0
        public async Task Process(GetCustomerDetailsInput input)
        {
            //
            // TODO: The following queries could be simplified
            //

            Customer customer = await customerReadOnlyRepository.Get(input.CustomerId);

            if (customer == null)
            {
                throw new CustomerNotFoundException($"The customer {input.CustomerId} does not exists or is not processed yet.");
            }

            List <AccountOutput> accounts = new List <AccountOutput>();

            foreach (var accountId in customer.Accounts)
            {
                Account account = await accountReadOnlyRepository.Get(accountId);

                //
                // TODO: The "Accout closed state" is not propagating to the Customer Aggregate
                //

                if (account != null)
                {
                    AccountOutput accountOutput = outputConverter.Map <AccountOutput>(account);
                    accounts.Add(accountOutput);
                }
            }

            CustomerOutput output = outputConverter.Map <CustomerOutput>(customer);

            output = new CustomerOutput(
                customer.Id,
                customer.PIN.Text,
                customer.Name.Text,
                accounts);

            outputBoundary.Populate(output);
        }
コード例 #15
0
        public void Populate(CustomerOutput output)
        {
            if (output == null)
            {
                ViewModel = new NoContentResult();
                return;
            }

            List <AccountDetailsModel> accounts = new List <AccountDetailsModel> ();

            foreach (var account in output.Accounts)
            {
                List <TransactionModel> transactions = new List <TransactionModel> ();

                foreach (var item in account.Transactions)
                {
                    var transaction = new TransactionModel(
                        item.Amount,
                        item.Description,
                        item.TransactionDate);

                    transactions.Add(transaction);
                }

                accounts.Add(new AccountDetailsModel(
                                 account.AccountId,
                                 account.CurrentBalance,
                                 transactions));
            }

            CustomerDetailsModel model = new CustomerDetailsModel(
                output.CustomerId,
                output.Personnummer,
                output.Name,
                accounts
                );

            ViewModel = new ObjectResult(model);
        }
コード例 #16
0
        public async Task Process(CheckoutInput input)
        {
            Customer customer = await customerReadOnlyRepository.Get(input.CustomerId);

            if (customer == null)
            {
                throw new CustomerNotFoundException($"The customer {input.CustomerId} does not exist or it was not processed yet.");
            }

            Basket basket = await basketReadOnlyRepository.Get(input.BasketId);

            if (basket == null)
            {
                throw new BasketNotFoundException($"The basket {input.BasketId} does not exist or it was already deleted.");
            }

            CustomerOutput customerOutput = outputConverter.Map <CustomerOutput>(customer);
            BasketOutput   basketOutput   = outputConverter.Map <BasketOutput>(basket);

            CheckoutOutput output = new CheckoutOutput(customerOutput, basketOutput, input.OrderDate, basket.GetTotalPrice().Value);

            outputBoundary.Populate(output);
        }
コード例 #17
0
        public async Task GetCustomerDetails_ValidId_ShouldReturnAnCustomer()
        {
            //ARRANGE
            var customerId = Guid.NewGuid();
            var ssn        = new SSN("0101010000");
            var name       = new Name("Test_Customer");

            var accountList = new AccountCollection();
            var account     = new Account(customerId);

            accountList.Add(account.Id);

            var customer = Customer.Load(customerId, name, ssn, accountList);

            _accountReadOnlyRepository.Setup(m => m.Get(account.Id)).Returns(Task.FromResult(account));
            _customerReadOnlyRepository.Setup(m => m.Get(customerId)).Returns(Task.FromResult(customer));

            //ACT
            CustomerOutput customerOutPut = await getCustomerDetailsUseCase.Execute(customerId);

            //ASSERT
            _accountReadOnlyRepository.Verify(v => v.Get(account.Id), Times.Once());
            Assert.Equal(customerOutPut.CustomerId, customerId);
        }
コード例 #18
0
 public AddBasketOutput(CustomerOutput customer, BasketOutput basket)
 {
     Customer = customer;
     Basket   = basket;
 }
コード例 #19
0
 public RegisterOutput(CustomerOutput customer, AccountOutput account)
 {
     Customer = customer;
     Account  = account;
 }
コード例 #20
0
 public RegisterOutput(CustomerOutput customer)
 {
     Customer = customer;
 }