Files
Hy2026/backend/Infrastructure/Persistence/TrendService.cs
T
Rafał Tyński bad37a6ab9 feat(backend): add knowledge base, innovation library and trends modules
Add knowledge item and innovation CRUD with search/filtering, published-only visibility for non-staff, admin publish/update, challenge dictionary, problem aggregation with trends (admin only) and canonical embedding text preparation for matchmaking.
2026-10-04 02:32:33 +02:00

80 lines
2.8 KiB
C#

using SurrealDb.Net;
using TarninaHub.Application.Abstractions;
using TarninaHub.Application.Dtos;
namespace TarninaHub.Infrastructure.Persistence;
public sealed class TrendService : ITrendService
{
private readonly ISurrealDbClient _client;
public TrendService(ISurrealDbClient client)
{
_client = client;
}
public async Task<TrendsResponse> GetAsync(
string? challengeId,
DateTimeOffset from,
DateTimeOffset to,
CancellationToken cancellationToken)
{
var counts = await CountSubmissionsAsync(challengeId, from, to, cancellationToken);
var challenges = await LoadChallengesAsync(cancellationToken);
var points = challenges
.Where(challenge => string.IsNullOrWhiteSpace(challengeId)
|| string.Equals(challenge.Id, challengeId, StringComparison.Ordinal))
.Select(challenge => new TrendPoint(
challenge.Id,
challenge.Name,
counts.GetValueOrDefault(challenge.Id)))
.OrderByDescending(point => point.SubmissionCount)
.ToList();
return new TrendsResponse(from, to, points);
}
private async Task<Dictionary<string, int>> CountSubmissionsAsync(
string? challengeId,
DateTimeOffset from,
DateTimeOffset to,
CancellationToken cancellationToken)
{
var parameters = new Dictionary<string, object?> { ["from"] = from, ["to"] = to };
var clauses = new List<string> { "created_at >= $from", "created_at <= $to" };
if (!string.IsNullOrWhiteSpace(challengeId))
{
var (table, id) = SurrealRecordId.Split(challengeId);
clauses.Add("problem.challenge = type::record($challengeTable, $challengeId)");
parameters["challengeTable"] = table;
parameters["challengeId"] = id;
}
var response = await _client.RawQuery(
"SELECT type::string(problem.challenge) AS challenge FROM submission WHERE " +
string.Join(" AND ", clauses) + ";",
parameters,
cancellationToken);
response.EnsureAllOks();
var rows = response.GetValue<List<TrendSubmissionRow>>(0) ?? [];
return rows
.Where(row => !string.IsNullOrWhiteSpace(row.Challenge))
.GroupBy(row => row.Challenge)
.ToDictionary(group => group.Key, group => group.Count());
}
private async Task<List<ChallengeRow>> LoadChallengesAsync(CancellationToken cancellationToken)
{
var response = await _client.RawQuery(
"SELECT type::string(id) AS id, name, order FROM social_challenge ORDER BY order;",
cancellationToken: cancellationToken);
response.EnsureAllOks();
return response.GetValue<List<ChallengeRow>>(0) ?? [];
}
}