source: KernelRecordsMVC.Web/Controllers/TopSellersController.cs@ fa0fbaf

main
Last change on this file since fa0fbaf was fa0fbaf, checked in by mmilevski <markomilevski3@…>, 4 weeks ago

Added major improvements.

  • Property mode set to 100644
File size: 2.4 KB
RevLine 
[fa0fbaf]1using KernelRecordsMVC.Application.ViewModels;
2using KernelRecordsMVC.Domain.Enums;
3using KernelRecordsMVC.Infrastructure.Data;
4using Microsoft.AspNetCore.Mvc;
5using Microsoft.EntityFrameworkCore;
6
7namespace KernelRecordsMVC.Web.Controllers;
8
9public class TopSellersController : Controller
10{
11 private readonly KernelRecordsContext _context;
12
13 public TopSellersController(KernelRecordsContext context)
14 {
15 _context = context;
16 }
17
18 public IActionResult Index()
19 {
20 var completedStatuses = new[]
21 {
22 OrderStatusType.PAID,
23 OrderStatusType.SHIPPED,
24 OrderStatusType.DELIVERED
25 };
26
27 var sellers = _context.OrderProducts
28 .Where(op =>
29 completedStatuses.Contains(op.Order.Status))
30 .GroupBy(op => op.ProductId)
31 .Select(g => new
32 {
33 ProductId = g.Key,
34 QuantitySold = g.Sum(x => x.Quantity)
35 })
36 .OrderByDescending(x => x.QuantitySold)
37 .Take(20)
38 .ToList();
39
40 var productIds = sellers
41 .Select(x => x.ProductId)
42 .ToList();
43
44 var products = _context.Products
45 .Include(p => p.Release)
46 .ThenInclude(r => r.ReleaseArtists)
47 .ThenInclude(ra => ra.Artist)
48 .Where(p => productIds.Contains(p.ProductId))
49 .ToList();
50
51 var result = sellers
52 .Select(s =>
53 {
54 var product = products
55 .First(p => p.ProductId == s.ProductId);
56
57 return new TopSellerViewModel
58 {
59 ProductId = product.ProductId,
60 ReleaseId = product.ReleaseId,
61 ReleaseTitle = product.Release.Title,
62 CoverPhoto = product.Release.CoverPhoto,
63 Format = product.Format.ToString(),
64 Price = product.Price,
65 Stock = product.Stock,
66 SoldQuantity = s.QuantitySold,
67
68 ArtistName = string.Join(
69 ", ",
70 product.Release.ReleaseArtists
71 .OrderBy(x => x.ReleaseOrdinal)
72 .Select(x => x.Artist.ArtistName))
73 };
74 })
75 .ToList();
76
77 return View(result);
78 }
79}
Note: See TracBrowser for help on using the repository browser.