예제 #1
0
        public async Task CreateAsync(string categorySlug, DateTime date, string headline, string description,
                                      decimal?price, DateTime?eventDate, string?imageUrl)
        {
            var category = await ValidateAsync(categorySlug, date);

            var article = new Article
            {
                CategoryId  = category.Id,
                Date        = date,
                Headline    = headline,
                Description = description,
                Price       = price,
                EventDate   = eventDate
            };

            if (!string.IsNullOrEmpty(imageUrl))
            {
                article.Image = new ArticleImage
                {
                    Url = imageUrl
                };
            }

            await EnsureJumpStartExistAsync(article.Date);

            await _dbContext.Articles.AddAsync(article);

            await _dbContext.SaveChangesAsync();
        }
예제 #2
0
        public async Task CreateAsync(int categoryId, DateTime date, string headline, string description,
                                      decimal?price, DateTime?eventDate, string?imageUrl)
        {
            var category = await _dbContext.Categories.OfType <PostCategory>()
                           .FirstOrDefaultAsync(item => item.Id == categoryId);

            if (category is null)
            {
                throw new RecordNotFoundException($"Category {categoryId} not found");
            }

            var post = new Post
            {
                CategoryId  = categoryId,
                Date        = date,
                Headline    = headline,
                Description = description,
                Price       = price,
                EventDate   = eventDate,
            };

            if (!string.IsNullOrEmpty(imageUrl))
            {
                post.Image = new PostImage
                {
                    Url = imageUrl
                };
            }

            await _dbContext.Posts.AddAsync(post);

            await _dbContext.SaveChangesAsync();
        }
예제 #3
0
        public async Task DeleteAsync(int productId)
        {
            var product = await GetAsync(productId);

            _dbContext.ShoppingProducts.Remove(product);

            await _dbContext.SaveChangesAsync();
        }
예제 #4
0
        public async Task SaveAsync(int clientId, ClientNoteModel model, User user)
        {
            var client = await ValidateAsync(user, clientId);

            client = Map(model, client);

            _dbContext.Clients.Update(client);
            await _dbContext.SaveChangesAsync();
        }
예제 #5
0
        public async Task CreateAsync(string tenantSlug, ClientModel model, User user)
        {
            var tenant = await ValidateAsync(user, tenantSlug);

            var client = await MapAsync(new Client(), model, tenant);

            _dbContext.Clients.Add(client);
            await _dbContext.SaveChangesAsync();
        }
예제 #6
0
        public async Task CreateAsync(NewJumpStartModel model)
        {
            var jumpStart = Map(new NewJumpStart(), model);

            jumpStart.Status = NewJumpStartStatus.Preview;

            _dbContext.NewJumpStarts.Add(jumpStart);
            await _dbContext.SaveChangesAsync();
        }
        public async Task SendAsync(int newJmpStartId)
        {
            var newJumpStart = await _dbContext.NewJumpStarts
                               .FirstOrDefaultAsync(item => item.Id == newJmpStartId && item.Status == NewJumpStartStatus.Sending);

            await SendEmailAsync(newJumpStart);

            newJumpStart.Status = NewJumpStartStatus.Sent;
            _dbContext.NewJumpStarts.Update(newJumpStart);
            await _dbContext.SaveChangesAsync();
        }
예제 #8
0
        public async Task DeleteAsync(int productId, User user)
        {
            var product = await _dbContext.ShoppingProducts
                          .Include(item => item.Category)
                          .ThenInclude(item => item.Tenant)
                          .FirstOrDefaultAsync(item => item.Id == productId);

            await CheckPermissionAsync(product.Category, user);

            _dbContext.ShoppingProducts.Remove(product);

            await _dbContext.SaveChangesAsync();
        }
예제 #9
0
        public async Task DeleteAsync(int id, User user)
        {
            var category = await GetAsync(id);

            if (category is null)
            {
                throw new RecordNotFoundException($"Category {id} not found");
            }

            await _tenantService.CheckPermissionAsync(user, category.Tenant.Slug);

            _dbContext.ProductCategories.Remove(category);

            await _dbContext.SaveChangesAsync();
        }
예제 #10
0
        public async Task SendAsync(int memoId)
        {
            var memo = await _dbContext.Memos.FirstOrDefaultAsync(item => item.Id == memoId);

            var company = await _dbContext.Companies.FirstOrDefaultAsync(item => item.Name == VolkswagenCompany.Slug);

            var templateData = new Dictionary <string, object>
            {
                { "subject", memo.Subject },
                { "date", memo.Date },
                { "to", memo.To },
                // To handle new lines correctly we are replacing them with <br> and use {{{description}}}
                // so we have to html encode here
                { "description", Regex.Replace(HttpUtility.HtmlEncode(memo.Description), @"\r\n?|\n", "<br>") }
            };

            var recipients = await _dbContext.EmailRecipients
                             .Where(item => item.MemoId == memoId && item.Status == EmailStatus.ReadyToSend)
                             .ToListAsync();

            foreach (var batch in recipients.Batch(SendGridService.BatchSize))
            {
                await _sendGridService.SendEmail(company.Id, recipients, templateData, nameof(EmailRecipient.MemoId),
                                                 memo.Id.ToString());

                foreach (var recipient in batch)
                {
                    recipient.Status = EmailStatus.Sent;
                }

                await _dbContext.SaveChangesAsync();
            }
        }
예제 #11
0
        public async Task CreatePdfAsync(int jumpStartId)
        {
            var jumpStart = await _dbContext.JumpStarts
                            .FirstOrDefaultAsync(item => item.Id == jumpStartId && item.HasPdf == false);

            if (jumpStart is null)
            {
                // We already created pdf for this one
                return;
            }

            var articles = await _dbContext.Articles
                           .Include(item => item.Category)
                           .ThenInclude(item => item.Image)
                           .Where(item => item.Date == jumpStart.DateTime.Date)
                           .OrderBy(item => item.Order).ToListAsync();

            var pdfData = await _puppeteerService.BuildPdfAsync(jumpStart.DateTime, articles);

            await UploadPdfAsync(jumpStart, pdfData);

            jumpStart.HasPdf = true;
            _dbContext.Update(jumpStart);

            await _dbContext.SaveChangesAsync();

            _backgroundJobClient.Enqueue <EmailRecipientJob>(job =>
                                                             job.CreateForJumpStart(jumpStart.Id));
        }
예제 #12
0
        public async Task <string> CreateAsync(string companySlug, TenantCreateModel model, User user)
        {
            var company = await ValidateAsync(companySlug, user);

            var tenant = Map(model, company, user);

            _dbContext.Tenants.Add(tenant);
            await _dbContext.SaveChangesAsync();

            tenant.Slug = _slugService.GetSlug(tenant.Name, tenant.Id);

            _dbContext.Tenants.Update(tenant);
            await _dbContext.SaveChangesAsync();

            return(tenant.Slug);
        }
예제 #13
0
        public async Task CreateAsync(DateTime dateTime, List <string> distributionGroups, List <int> postIds)
        {
            var posts = await _dbContext.Posts.Where(item => postIds.Contains(item.Id))
                        .ToListAsync();

            var isValid = posts.All(item => item.Date.Date <= dateTime.Date && item.JumpStartId == null) &&
                          posts.Count == postIds.Count;

            if (!isValid)
            {
                throw new InvalidActionException("Invalid posts");
            }

            var jumpStart = new JumpStart
            {
                DateTime           = dateTime,
                DistributionGroups = string.Join(',', distributionGroups),
                Status             = JumpStartStatus.ReadyToSend,
                Posts = posts
            };

            foreach (var post in posts)
            {
                post.JumpStart = jumpStart;
                post.Order     = postIds.IndexOf(post.Id);
            }

            _dbContext.UpdateRange(posts);

            await _dbContext.SaveChangesAsync();

            _backgroundJobClient.Enqueue <JumpStartPdfService>(service =>
                                                               service.CreatePdfAsync(jumpStart.Id));
        }
예제 #14
0
        public async Task SetValueAsync <T>(string companySlug, T value)
        {
            var json = JsonConvert.SerializeObject(value);

            var config = await _dbContext.Settings
                         .Include(item => item.Company)
                         .FirstOrDefaultAsync(item => item.Company.Slug == companySlug.ToLower());

            if (config is null)
            {
                var company = await _dbContext.Companies
                              .FirstOrDefaultAsync(item => item.Slug == companySlug.ToLower());

                _dbContext.Settings.Add(new Setting
                {
                    CompanyId = company.Id,
                    Value     = json
                });
            }
            else
            {
                config.Value = json;
                _dbContext.Update(config);
            }

            await _dbContext.SaveChangesAsync();
        }
예제 #15
0
        private async Task <RoomType> CreateRoomType(MeredithDbContext dbContext, int days = 0)
        {
            var roomType = new RoomType
            {
                Name = "Test"
            };

            for (var i = 0; i < days; i++)
            {
                roomType.Prices.Add(new HotelPrice
                {
                    Amount = 10,
                    Date   = Start.AddDays(i)
                });
            }

            for (var i = 0; i < 1; i++)
            {
                roomType.Rooms.Add(new Room {
                    Number = i.ToString()
                });
            }

            dbContext.RoomTypes.Add(roomType);
            await dbContext.SaveChangesAsync();

            return(roomType);
        }
        private async Task Create(string distributionGroups, Func <EmailRecipient, EmailRecipient> keySetter)
        {
            var recipients = await GetRecipients(distributionGroups);

            foreach (var batch in recipients.Batch(100))
            {
                var memoRecipients = batch.Select(item => new EmailRecipient
                {
                    Email             = item.Email,
                    DistributionGroup = item.DistributionGroup,
                    Status            = EmailStatus.ReadyToSend
                }).Select(keySetter);

                _dbContext.EmailRecipients.AddRange(memoRecipients);
                await _dbContext.SaveChangesAsync();
            }
        }
예제 #17
0
        private async Task <JumpStart> CreateAsync(DateTime dateTime, List <string> distributionGroups,
                                                   List <Article> articles)
        {
            var jumpStart = new JumpStart
            {
                DateTime           = dateTime,
                Status             = JumpStartStatus.Preview,
                DistributionGroups = distributionGroups
            };

            _dbContext.JumpStarts.Add(jumpStart);

            Rearrange(articles);

            await _dbContext.SaveChangesAsync();

            return(jumpStart);
        }
예제 #18
0
        public async Task SendAsync(int jumpStartId)
        {
            var jumpStart = await _dbContext.JumpStarts
                            .FirstOrDefaultAsync(item => item.Id == jumpStartId && item.Status == JumpStartStatus.Sending);

            var articles = await _dbContext.Articles
                           .Include(item => item.Image)
                           .Include(item => item.Category)
                           .ThenInclude(item => item.Image)
                           .Where(item => item.Date == jumpStart.DateTime.Date)
                           .OrderBy(item => item.Order).ToListAsync();

            await SendEmailAsync(jumpStart, articles);

            jumpStart.Status = JumpStartStatus.Sent;
            _dbContext.JumpStarts.Update(jumpStart);
            await _dbContext.SaveChangesAsync();
        }
예제 #19
0
        public async Task SendAsync(int jumpStartId)
        {
            var jumpStart = await _dbContext.JumpStarts
                            .Include(item => item.Posts)
                            .ThenInclude(item => item.Image)
                            .Include(item => item.Posts)
                            .ThenInclude(item => item.Category)
                            .ThenInclude(item => item.Image)
                            .FirstOrDefaultAsync(item => item.Id == jumpStartId && item.Status == JumpStartStatus.ReadyToSend);

            jumpStart.Posts = jumpStart.Posts.OrderBy(item => item.Order).ToList();

            await SendEmailAsync(jumpStart);

            jumpStart.Status = JumpStartStatus.Sent;
            _dbContext.JumpStarts.Update(jumpStart);
            await _dbContext.SaveChangesAsync();
        }
예제 #20
0
        public async Task CreateAsync(List <string> distributionGroups, string subject, string date, string to,
                                      string description)
        {
            var memo = new Memo
            {
                DistributionGroups = string.Join(',', distributionGroups),
                Subject            = subject,
                Date             = date,
                To               = to,
                Description      = description,
                CreationDateTime = DateTime.UtcNow
            };

            _dbContext.Memos.Add(memo);
            await _dbContext.SaveChangesAsync();

            _backgroundJobClient.Enqueue <EmailRecipientService>(service =>
                                                                 service.CreateForMemo(memo.Id));
        }
예제 #21
0
        private async Task Create(int companyId, List <string> distributionGroups, Func <Data.Entity.Models.Email, Data.Entity.Models.Email> keySetter)
        {
            var dateTime   = DateTime.UtcNow;
            var recipients = await GetRecipients(distributionGroups);

            foreach (var batch in recipients.Batch(100))
            {
                var memoRecipients = batch.Select(item => new Data.Entity.Models.Email
                {
                    CompanyId        = companyId,
                    EmailAddress     = item.Email,
                    Group            = item.DistributionGroup,
                    Status           = EmailStatus.ReadyToSend,
                    CreationDateTime = dateTime
                }).Select(keySetter);

                _dbContext.Emails.AddRange(memoRecipients);
                await _dbContext.SaveChangesAsync();
            }
        }
예제 #22
0
        public async Task <Page> CreateAsync(int companyId, int?categoryId, string slug, string name, string title,
                                             string header, string featuredImage, string backgroundImage, string callToAction, string callToActionLink,
                                             string description, string custom)
        {
            var company = _dbContext.Companies.FirstOrDefaultAsync(item => item.Id == companyId);

            if (company is null)
            {
                throw new InvalidActionException("Company does not exist");
            }

            if (categoryId.HasValue)
            {
                var category = _dbContext.Categories.FirstOrDefaultAsync(item => item.Id == categoryId);
                if (category is null)
                {
                    throw new InvalidActionException("Category does not exist");
                }
            }

            var page = new Page
            {
                CompanyId  = companyId,
                CategoryId = categoryId,
                Slug       = slug,
                //Name = name,
                //Title = title,
                //Header = header,
                FeaturedImage   = featuredImage,
                BackgroundImage = backgroundImage,
                //CallToAction = callToAction,
                CallToActionLink = callToActionLink,
                //Description = description,
                Custom = custom
            };

            _dbContext.Pages.Add(page);
            await _dbContext.SaveChangesAsync();

            return(page);
        }
예제 #23
0
        public async Task CreateAsync(string categorySlug, DateTime date, string headline, string description,
                                      string?excerpt, DateTime?eventDate, string?imageUrl, int?imageWidth, int?imageHeight)
        {
            var category = await ValidateAsync(categorySlug, date);

            var article = new Article
            {
                CategoryId  = category.Id,
                Date        = date,
                Headline    = headline,
                Description = description,
                Excerpt     = excerpt,
                EventDate   = eventDate
            };

            await SetImageAsync(article, imageUrl, imageWidth, imageHeight);

            await _dbContext.Articles.AddAsync(article);

            await _dbContext.SaveChangesAsync();
        }
예제 #24
0
        public async Task <OkResult> Create(List <SendGridEventItem> events)
        {
            foreach (var eventList in events.Batch(100))
            {
                foreach (var eventItem in eventList)
                {
                    await eventItem.Apply(_dbContext);
                }

                await _dbContext.SaveChangesAsync();
            }

            return(Ok());
        }
예제 #25
0
        public async Task CreateAsync(MemoModel model)
        {
            var memo = new Memo
            {
                DistributionGroups = model.DistributionGroups,
                Subject            = model.Subject,
                Date             = model.Date,
                To               = model.To,
                Description      = model.Description,
                PdfUrl           = model.PdfUrl,
                CreationDateTime = DateTime.UtcNow
            };

            _dbContext.Memos.Add(memo);
            await _dbContext.SaveChangesAsync();

            _backgroundJobClient.Enqueue <EmailRecipientJob>(job =>
                                                             job.CreateForMemo(memo.Id));
        }
예제 #26
0
        public async Task SendAsync(int memoId)
        {
            var memo = await _dbContext.Memos.FirstOrDefaultAsync(item => item.Id == memoId);

            var recipients = await _dbContext.Emails
                             .Where(item => item.MemoId == memoId && item.Status == EmailStatus.ReadyToSend)
                             .ToListAsync();

            var emailInfo = await GetEmailInfoAsync(memo, recipients);

            await _sendGridService.SendEmailAsync(emailInfo);

            foreach (var recipient in recipients)
            {
                recipient.Status = EmailStatus.Sent;
            }

            await _dbContext.SaveChangesAsync();
        }
예제 #27
0
        public async Task SendAsync()
        {
            var newJumpStarts = await _dbContext.NewJumpStarts
                                .Where(item => item.Status == NewJumpStartStatus.Preview &&
                                       item.DateTime < DateTime.UtcNow.AddMinutes(15)).ToListAsync();

            foreach (var newJumpStart in newJumpStarts)
            {
                newJumpStart.Status = NewJumpStartStatus.Sending;
            }

            _dbContext.UpdateRange(newJumpStarts);
            await _dbContext.SaveChangesAsync();

            foreach (var newJumpStart in newJumpStarts)
            {
                _backgroundJobClient.Enqueue <EmailRecipientJob>(job =>
                                                                 job.CreateForNewJumpStart(newJumpStart.Id));
            }
        }
예제 #28
0
        public async Task SendAsync()
        {
            var jumpStarts = new List <JumpStart>();
            var settings   = await _settingsService.GetValueAsync <VolkswagenSettings>(VolkswagenCompany.Slug);

            var dailyPlans = await _jumpStartPlanService.GetAsync();

            dailyPlans = dailyPlans.Where(item => item.DateTime < DateTime.UtcNow.AddMinutes(15)).ToList();

            foreach (var dailyPlan in dailyPlans)
            {
                var jumpStart = dailyPlan.JumpStart;

                if (jumpStart is null)
                {
                    if (!settings.EnableAutoSend)
                    {
                        // Do not send these articles because admin didn't schedule it and the auto send is off
                        continue;
                    }

                    jumpStart = await CreateJumpStart(dailyPlan.DateTime, dailyPlan.DistributionGroups,
                                                      dailyPlan.Articles);
                }

                jumpStart.Status = JumpStartStatus.Sending;
                jumpStarts.Add(jumpStart);
            }

            _dbContext.UpdateRange(jumpStarts);
            await _dbContext.SaveChangesAsync();

            foreach (var jumpStart in jumpStarts)
            {
                _backgroundJobClient.Enqueue <JumpStartPdfJob>(service =>
                                                               service.CreatePdfAsync(jumpStart.Id));
            }
        }
예제 #29
0
        public async Task <HotelReservation> CreateReservation(int roomTypeId, DateTime startDate, DateTime endDate,
                                                               string fullName, string email, string?message, string?phoneCountry, string phone, int numberOfGuests)
        {
            var roomType = await _meredithDbContext.RoomTypes
                           .FirstOrDefaultAsync(rt => rt.Id == roomTypeId);

            if (roomType is null)
            {
                throw new RecordNotFoundException();
            }

            var availableRooms = await _meredithDbContext.Rooms
                                 .Where(r => !r.Reservations
                                        .Any(re => re.Start >= startDate && re.End <= endDate))
                                 .ToListAsync();

            if (availableRooms.Count == 0)
            {
                throw new InvalidActionException("There are no rooms available of this type");
            }

            var totalDays = (int)endDate.Subtract(startDate).TotalDays;

            if (totalDays <= 0)
            {
                throw new InvalidActionException("Invalid number of days to reserve");
            }

            var dailyPrices = await _meredithDbContext.Prices
                              .OfType <HotelPrice>()
                              .Where(p => p.Date >= startDate && p.Date < endDate).ToListAsync();

            var paidDays = dailyPrices.Count;

            if (paidDays != totalDays)
            {
                throw new InvalidActionException("Not all days have prices set");
            }

            var totalAmount = dailyPrices.Sum(item => item.Amount);
            // 10% VAT
            var vat = totalAmount / 10;

            totalAmount += vat;

            var user = await _userService.GetUserAsync(_user);

            var reservation = new HotelReservation
            {
                Amount         = totalAmount,
                Created        = DateTime.UtcNow,
                Start          = startDate,
                End            = endDate,
                Email          = email,
                Message        = message,
                Name           = fullName,
                NumberOfGuests = numberOfGuests,
                Phone          = phone,
                RoomId         = availableRooms.First().Id,
                User           = user
            };

            _meredithDbContext.Reservations.Add(reservation);
            await _meredithDbContext.SaveChangesAsync();

            await _emailService.SendReservationEmail(reservation, roomType, dailyPrices, vat,
                                                     paidDays, phoneCountry, phone);

            return(reservation);
        }
예제 #30
0
        private async Task <MeredithDbContext> InitializeDb(string name)
        {
            var options = new DbContextOptionsBuilder <MeredithDbContext>()
                          .UseInMemoryDatabase(name)
                          .Options;

            var meredithDbContext = new MeredithDbContext(options);

            // Add two roomTypes
            var roomTypes = new List <RoomType>
            {
                new RoomType
                {
                    Id = 1
                },
                new RoomType

                {
                    Id = 2
                }
            };

            meredithDbContext.RoomTypes.AddRange(roomTypes);

            // Add three rooms for each roomType
            var id = 1;

            foreach (var roomType in roomTypes)
            {
                for (var i = 0; i < 3; i++)
                {
                    meredithDbContext.Rooms.Add(new Room
                    {
                        Id         = id,
                        RoomTypeId = roomType.Id
                    });

                    id++;
                }
            }

            // For each roomType add prices for 5 days from 1/1/2020
            id = 1;
            foreach (var roomType in roomTypes)
            {
                for (var i = 0; i < 5; i++)
                {
                    meredithDbContext.Prices.Add(new HotelPrice
                    {
                        Id         = id,
                        Date       = new DateTime(2020, 1, 1).AddDays(i),
                        RoomTypeId = roomType.Id,
                        Amount     = id * 100
                    });

                    id++;
                }
            }

            meredithDbContext.Reservations.AddRange(new HotelReservation
            {
                Id     = 1,
                RoomId = 1,
                Start  = new DateTime(2020, 1, 1),
                End    = new DateTime(2020, 1, 2)
            },
                                                    new HotelReservation
            {
                Id     = 2,
                RoomId = 2,
                Start  = new DateTime(2020, 1, 2),
                End    = new DateTime(2020, 1, 4)
            });

            await meredithDbContext.SaveChangesAsync();

            return(meredithDbContext);
        }