Skip to content
This repository has been archived by the owner on Jul 12, 2024. It is now read-only.

Commit

Permalink
fix: cron job calc rating
Browse files Browse the repository at this point in the history
  • Loading branch information
foxminchan committed Jun 5, 2024
1 parent d667ea5 commit 6450452
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 30 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RookieShop.Infrastructure.HostedServices;
using RookieShop.Persistence;
Expand All @@ -11,12 +12,12 @@ public sealed class CalculateRatingWorker : CronJobBackgroundService
private readonly ILogger<CalculateRatingWorker> _logger;
private readonly IServiceProvider _serviceProvider;

public CalculateRatingWorker(ILogger<CalculateRatingWorker> logger, IServiceProvider serviceProvider)
public CalculateRatingWorker(ILogger<CalculateRatingWorker> logger, IServiceProvider serviceProvider,
IHostEnvironment environment)
{
_logger = logger;
_serviceProvider = serviceProvider;
Cron = "0 0 0 * * ?"; // Run at midnight
// Cron = "0 */1 * * * ?"; // Run every minute
Cron = environment.IsDevelopment() ? "0 */1 * * * ?" : "0 0 0 * * ?";
}

protected override async Task DoWork(CancellationToken stoppingToken)
Expand All @@ -27,44 +28,33 @@ protected override async Task DoWork(CancellationToken stoppingToken)

var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

_logger.LogInformation("[{Worker}] Calculate rating worker running at: {Time}",
nameof(CalculateRatingWorker),
DateTimeOffset.Now);

var productRatings = await dbContext.Feedbacks
.GroupBy(f => f.ProductId)
.Select(g => new
var feedbacks = await dbContext.Feedbacks
.GroupBy(feedback => feedback.ProductId)
.Select(group => new
{
ProductId = g.Key,
AverageRating = g.Average(f => f.Rating),
TotalReviews = g.Count()
ProductId = group.Key,
AverageRating = group.Average(feedback => feedback.Rating),
TotalFeedback = group.Count()
})
.ToListAsync(stoppingToken);

var allProductIds = await dbContext.Products
.Select(p => p.Id)
.ToListAsync(stoppingToken);

foreach (var productId in allProductIds)
foreach (var feedback in feedbacks)
{
var productRating =
productRatings.Find(r => r.ProductId == productId);

var product =
await dbContext.Products.FindAsync([productId, stoppingToken], cancellationToken: stoppingToken);
var product = await dbContext.Products
.IgnoreAutoIncludes()
.Where(product => !product.IsDeleted)
.FirstOrDefaultAsync(product => product.Id == feedback.ProductId, stoppingToken);

if (product is null) continue;

product.AverageRating = productRating?.AverageRating ?? 0;
product.AverageRating = feedback.AverageRating;

product.TotalReviews = productRating?.TotalReviews ?? 0;
product.TotalReviews = feedback.TotalFeedback;

dbContext.Products.Update(product);
}

await dbContext.SaveChangesAsync(stoppingToken);

_logger.LogInformation("[{Worker}] Calculate rating worker completed at: {Time}",
_logger.LogInformation("[{Worker}] Calculate rating worker running at: {Time}",
nameof(CalculateRatingWorker),
DateTimeOffset.Now);
}
Expand Down
3 changes: 3 additions & 0 deletions src/RookieShop.Domain/Entities/ProductAggregator/Product.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,4 +66,7 @@ public void RemoveStock(int quantityDesired)
CategoryId = categoryId;
Status = Guard.Against.EnumOutOfRange(status);
}

public void UpdateRating(double rating, int totalFeedback) =>
(AverageRating, TotalReviews) = (rating, totalFeedback);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ public sealed class ProductsFilterSpec : Specification<Product>
.ApplyOrdering(orderBy, isDescending);
}

public ProductsFilterSpec() => Query.Where(product => !product.IsDeleted);
public ProductsFilterSpec() => Query
.Where(product => !product.IsDeleted);
}
2 changes: 1 addition & 1 deletion src/RookieShop.Infrastructure/Email/Extension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ private static void ConfigureEmailService(this IHostApplicationBuilder builder)
})
.AddTimeout(TimeSpan.FromSeconds(10)));

builder.Services.AddMarten(conn);
builder.Services.AddMarten(conn).UseLightweightSessions();

builder.Services.AddScoped<ISmtpService, SmtpService>();

Expand Down

0 comments on commit 6450452

Please sign in to comment.