1 | using backend.Data;
|
---|
2 | using backend.DTOs;
|
---|
3 | using backend.Email;
|
---|
4 | using backend.Entities;
|
---|
5 | using Microsoft.EntityFrameworkCore;
|
---|
6 |
|
---|
7 | namespace backend.Services
|
---|
8 | {
|
---|
9 | public interface IReviewService
|
---|
10 | {
|
---|
11 | public Task AddReview(CreateReviewRequest review, int userId);
|
---|
12 | public Task<List<ReviewResponse>> GetReviews(int page, int pageSize);
|
---|
13 | public Task<int> GetCount();
|
---|
14 | }
|
---|
15 | public class ReviewService : IReviewService
|
---|
16 | {
|
---|
17 | private readonly DataContext _context = null;
|
---|
18 | private readonly IEmailSender _emailSender;
|
---|
19 |
|
---|
20 | public ReviewService(DataContext context, IEmailSender emailSender)
|
---|
21 | {
|
---|
22 | _context = context;
|
---|
23 | _emailSender = emailSender;
|
---|
24 |
|
---|
25 | }
|
---|
26 |
|
---|
27 | public async Task AddReview(CreateReviewRequest review, int userId)
|
---|
28 | {
|
---|
29 | var user = await _context.Users.FindAsync(userId);
|
---|
30 | var res = await _context.Restoraunts.Include(x => x.Reviews).FirstOrDefaultAsync();
|
---|
31 | if(res.Reviews == null)
|
---|
32 | {
|
---|
33 | res.Reviews = new List<Review>();
|
---|
34 | }
|
---|
35 | res.Reviews.Add(new Review()
|
---|
36 | {
|
---|
37 | Title = review.Title,
|
---|
38 | Description = review.Description,
|
---|
39 | Stars = review.Stars,
|
---|
40 | CreatedAt = DateTime.UtcNow,
|
---|
41 | User = user
|
---|
42 | });
|
---|
43 | _context.Restoraunts.Update(res);
|
---|
44 | await _context.SaveChangesAsync();
|
---|
45 |
|
---|
46 | if (review.Stars < 3)
|
---|
47 | {
|
---|
48 | var adminUser = await _context.Users.FirstOrDefaultAsync(x => x.IsAdmin);
|
---|
49 | await _emailSender.SendEmailAsync("Добивте лоша оценка", $"<html><h1>{review.Title}</h1><p>{review.Description}</p></html>", adminUser.Email);
|
---|
50 | }
|
---|
51 | }
|
---|
52 |
|
---|
53 | public async Task<int> GetCount()
|
---|
54 | {
|
---|
55 | return await _context.Reviews.CountAsync();
|
---|
56 | }
|
---|
57 |
|
---|
58 | public async Task<List<ReviewResponse>> GetReviews(int page, int pageSize)
|
---|
59 | {
|
---|
60 | return await _context.Reviews
|
---|
61 | .Include(x => x.User)
|
---|
62 | .OrderByDescending(x => x.CreatedAt)
|
---|
63 | .Skip(page * pageSize)
|
---|
64 | .Take(pageSize)
|
---|
65 | .Select(x => new ReviewResponse()
|
---|
66 | {
|
---|
67 | CreatedAt = x.CreatedAt,
|
---|
68 | Description = x.Description,
|
---|
69 | Id = x.Id,
|
---|
70 | Stars = x.Stars,
|
---|
71 | Title = x.Title,
|
---|
72 | Username = x.User == null ? "Anonymous" : x.User.Email
|
---|
73 | })
|
---|
74 | .ToListAsync();
|
---|
75 | }
|
---|
76 | }
|
---|
77 | }
|
---|