public async Task <InvoiceReadModel> GetInvoice(string invoiceId)
        {
            Invoice invoice = await _eventRepository.GetByIdAsync(new InvoiceId(invoiceId));

            var taskInvoiceLines = Task.WhenAll(invoice.Lines.Select(async x =>
            {
                var getShipTask    = _shipRepository.GetShip(x.ShipId.ToString());
                var getServiceTask = _shipServiceRepository.GetShipService(x.ServiceId.ToString());
                await Task.WhenAll(getShipTask, getServiceTask);

                Ship ship           = getShipTask.Result;
                ShipService service = getServiceTask.Result;

                return(new InvoiceLineReadModel
                {
                    Description = $"Service: {service.Name} applied for ship: {ship.Name}",
                    Price = service.Price
                });
            }));


            var taskCustomer = Task.Run(async() =>
            {
                Customer foundCustomer      = await _customerRepository.GetCustomerAsync(invoice.CustomerId.ToString());
                CustomerReadModel readModel = new CustomerReadModel
                {
                    Address    = foundCustomer.Address,
                    Email      = foundCustomer.Email,
                    PostalCode = foundCustomer.PostalCode,
                    Residence  = foundCustomer.Residence
                };

                return(readModel);
            });

            var taskRental = Task.Run(async() =>
            {
                Rental foundRental        = await _rentalRepository.GetRental(invoice.RentalId.ToString());
                RentalReadModel readModel = new RentalReadModel
                {
                    Price = foundRental.Price
                };

                return(readModel);
            });

            await Task.WhenAll(taskInvoiceLines, taskCustomer, taskRental);

            var customer = await taskCustomer;
            var lines    = await taskInvoiceLines;
            var rental   = await taskRental;

            return(new InvoiceReadModel
            {
                Customer = customer,
                Lines = lines,
                Rental = rental,
                TotalPrice = rental.Price + lines.Sum(x => x.Price)
            });
        }
Esempio n. 2
0
        public Task Consume(ConsumeContext <AddNewInvoiceCommand> context)
        {
            try
            {
                AddNewInvoiceCommand newInvoice   = context.Message;
                CustomerReadModel    customerRead = _invoiceRepository.GetCustomer(newInvoice.CustomerCode);
                Model.Entity.Invoice invoice;
                List <Item>          items = new List <Item>();
                newInvoice.Items.ToList().ForEach(x =>
                {
                    Item item = new Item(
                        new IsDeliveried(x.Deliveried),
                        new Quantity(x.DeliveriedQuantity),
                        new Price(x.Price),
                        new Name(x.ProductName),
                        new Quantity(x.Quantity),
                        new Price(x.TotalPrice),
                        new Unit(x.UnitName),
                        new Weight(Convert.ToDouble(x.Weight))
                        );
                    items.Add(item);
                });
                if (customerRead != null)
                {
                    invoice = new Model.Entity.Invoice(
                        new Code(newInvoice.Code),
                        new Note(newInvoice.Note),
                        new Status(newInvoice.Status),
                        new Price(newInvoice.TotalPrice),
                        new Weight(newInvoice.WeightTotal),
                        new Identity(customerRead.Id),
                        newInvoice.DeliveryTime,
                        new IsServed(newInvoice.Served),
                        items
                        );
                }
                else
                {
                    return(Task.FromException(new Exception("Lỗi dữ liệu")));
                }



                return(_invoiceRepository.Create(invoice));
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw;
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // NOTE: this must go at the end of Configure
            // ensure db is created
            var serviceScopeFactory = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>();

            using (var serviceScope = serviceScopeFactory.CreateScope())
            {
                var eventStoreDbContext = serviceScope.ServiceProvider.GetService <SimpleEventStoreDbContext>();
                eventStoreDbContext.Database.EnsureCreated();

                // readonly initialization hack for sample purpose
                var readModelDbContext = serviceScope.ServiceProvider.GetService <ReadModelDbContext>();
                readModelDbContext.Database.EnsureCreated();

                var customerFactory    = new GenericEntityFactory <Customer>(eventStoreDbContext);
                var customerEntities   = customerFactory.GetAllEntitiesAsync().Result;
                var customerReadModels = customerEntities.Select(c =>
                {
                    var readModel = new CustomerReadModel();
                    readModel.FromAggregate(c);
                    return(readModel);
                });
                readModelDbContext.Customers.AddRange(customerReadModels);

                // As aggregate membership is a readmodel, we initialize it like this.
                var aggregateMembershipFactory    = new GenericEntityFactory <Core.Membership>(eventStoreDbContext);
                var aggregateMembershipEntities   = aggregateMembershipFactory.GetAllEntitiesAsync().Result;
                var aggregateMembershipReadModels = aggregateMembershipEntities.Select(am =>
                {
                    var model = new MembershipReadModel();
                    model.FromAggregate(am);
                    return(model);
                });
                readModelDbContext.Memberships.AddRange(aggregateMembershipReadModels);

                readModelDbContext.SaveChanges();

                // reporting initialization

                //// readonly initialization hack for sample purpose
                //var reportingDbContext = serviceScope.ServiceProvider.GetService<ReportingReadModelDbContext>();
                //reportingDbContext.Database.EnsureCreated();

                //var reportingModelEventHandlers = new MembershipPointsReportingReadModelHandlers(reportingDbContext);
                //var customerregisteredEvents = eventStoreDbContext.FindEventsAsync<CustomerRegisteredEvent>().Result;
                //var membershipCreatedEvents = eventStoreDbContext.FindEventsAsync<MembershipCreatedEvent>().Result;
                //var membershipPointsEarnedEvents = eventStoreDbContext.FindEventsAsync<MembershipPointsEarnedEvent>().Result;

                //List<dynamic> dynamicCustomerRegistered = customerregisteredEvents
                //    .Select(e => e.EntityJson.FromJson(Type.GetType(e.EntityType)))
                //    .ToList();

                //List<dynamic> dynamicMembershipCreated = membershipCreatedEvents
                //    .Select(e => e.EntityJson.FromJson(Type.GetType(e.EntityType)))
                //    .ToList();

                //List<dynamic> dynamicMembershipPointsEarned = membershipPointsEarnedEvents
                //    .Select(e => e.EntityJson.FromJson(Type.GetType(e.EntityType)))
                //    .ToList();
                //foreach(var @event in dynamicCustomerRegistered)
                //{
                //    reportingModelEventHandlers.Handle(@event);
                //}
                //foreach(var @event in dynamicMembershipCreated)
                //{
                //    reportingModelEventHandlers.Handle(@event);
                //}
                //foreach(var @event in dynamicMembershipPointsEarned)
                //{
                //    reportingModelEventHandlers.Handle(@event);
                //}
            }
        }