Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StandUpStreak - implement internal counter #345

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/HonzaBotner.Database/HonzaBotnerDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ protected override void OnModelCreating(ModelBuilder builder)
public DbSet<RoleBinding> RoleBindings { get; set; }
public DbSet<Warning> Warnings { get; set; }
public DbSet<Reminder> Reminders { get; set; }
public DbSet<StandUpStat> StandUpStats { get; set; }
}
15 changes: 15 additions & 0 deletions src/HonzaBotner.Database/StandUpStat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace HonzaBotner.Database;

public class StandUpStat
{
public int Id { get; set; }
public ulong UserId { get; set; }
public int Streak { get; set; }
public int LongestStreak { get; set; }
public int Freezes { get; set; }
public DateTime LastDayOfStreak { get; set; }
public int TotalCompleted { get; set; }
public int TotalTasks { get; set; }
}
63 changes: 60 additions & 3 deletions src/HonzaBotner.Discord.Services/Jobs/StandUpJobProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
using HonzaBotner.Discord.Services.Helpers;
using HonzaBotner.Discord.Services.Options;
using HonzaBotner.Scheduler.Contract;
using HonzaBotner.Services.Contract;
using HonzaBotner.Services.Contract.Dto;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

Expand All @@ -22,15 +24,23 @@ public class StandUpJobProvider : IJob

private readonly CommonCommandOptions _commonOptions;

private readonly IStandUpStatsService _statsService;

private IGuildProvider _guildProvider;

public StandUpJobProvider(
ILogger<StandUpJobProvider> logger,
DiscordWrapper discord,
IOptions<CommonCommandOptions> commonOptions
IOptions<CommonCommandOptions> commonOptions,
IStandUpStatsService statsService,
IGuildProvider guildProvider
)
{
_logger = logger;
_discord = discord;
_commonOptions = commonOptions.Value;
_statsService = statsService;
_guildProvider = guildProvider;
}

/// <summary>
Expand All @@ -44,7 +54,8 @@ IOptions<CommonCommandOptions> commonOptions
/// [] - normal
/// []! - critical
/// </summary>
private static readonly Regex Regex = new(@"^ *\[ *(?<State>\S*) *\] *(?<Priority>[!])?", RegexOptions.Multiline);
private static readonly Regex TaskRegex = new(@"^ *\[ *(?<State>\S*) *\] *(?<Priority>[!])?",
RegexOptions.Multiline);

private static readonly List<string> OkList = new() { "check", "done", "ok", "✅" };

Expand Down Expand Up @@ -79,24 +90,70 @@ await channel.GetMessagesBeforeAsync(messageList.Last().Id)
}
}

HashSet<ulong> membersToDm = new();

foreach (DiscordMessage msg in messageList.Where(msg => msg.Timestamp.Date == yesterday))
{
foreach (Match match in Regex.Matches(msg.Content))
int total = 0;
int completed = 0;

foreach (Match match in TaskRegex.Matches(msg.Content))
{
total++;
string state = match.Groups["State"].ToString();
string priority = match.Groups["Priority"].ToString();

if (OkList.Any(s => state.Contains(s)))
{
completed++;
ok.Increment(priority);
}
else
{
fail.Increment(priority);
}
}

// Update DB.
await _statsService.UpdateStats(msg.Author.Id, completed, total);
StandUpStat? stats = await _statsService.GetStats(msg.Author.Id);

if (stats is null)
{
_logger.LogWarning("No stats presented for member {Member}", msg.Author.Mention);
continue;
}

// Send DM to the current member (only once).
if (membersToDm.Contains(msg.Author.Id))
{
continue;
}

membersToDm.Add(msg.Author.Id);

try
{
DiscordGuild guild = await _guildProvider.GetCurrentGuildAsync();
DiscordMember member = await guild.GetMemberAsync(msg.Author.Id);

// Send DM to the member.
string heading = await _statsService.IsValidStreak(msg.Author.Id)
? "Skvělá práce!"
: "Nějak ti to nevyšlo...";
await member.SendMessageAsync($@"
{heading} Včera jsi splnil {completed} z {total} tasků a jsi momentálně na streaku {stats.Streak} s {stats.Freezes} možnými freezes.

Celkově jsi splnil {stats.TotalCompleted} z {stats.TotalTasks} tasků a nejdelší streak jsi měl {stats.LongestStreak} dní.
");
}
catch (Exception e)
{
_logger.LogInformation(e, "Could not send a message to {Member}", msg.Author.Mention);
}
}

// Send stats message to channel.
await channel.SendMessageAsync($@"
Stand-up time, <@&{_commonOptions.StandUpRoleId}>!

Expand Down
10 changes: 10 additions & 0 deletions src/HonzaBotner.Services.Contract/Dto/StandUpStat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using System;

namespace HonzaBotner.Services.Contract.Dto;

public record StandUpStat(
int Id, ulong UserId,
int Streak, int LongestStreak,
int Freezes, DateTime LastDayOfStreak,
int TotalCompleted, int TotalTasks
);
stepech marked this conversation as resolved.
Show resolved Hide resolved
13 changes: 13 additions & 0 deletions src/HonzaBotner.Services.Contract/IStandUpStatsService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System.Threading.Tasks;
using HonzaBotner.Services.Contract.Dto;

namespace HonzaBotner.Services.Contract;

public interface IStandUpStatsService
{
Task<StandUpStat?> GetStats(ulong userId);

Task<bool> IsValidStreak(ulong userId);

Task UpdateStats(ulong userId, int completed, int total);
}
1 change: 1 addition & 0 deletions src/HonzaBotner.Services/ServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public static IServiceCollection AddBotnerServices(this IServiceCollection servi
serviceCollection.AddScoped<IRoleBindingsService, RoleBindingsService>();
serviceCollection.AddScoped<IWarningService, WarningService>();
serviceCollection.AddScoped<IRemindersService, RemindersService>();
serviceCollection.AddScoped<IStandUpStatsService, StandUpStatsService>();

return serviceCollection;
}
Expand Down
169 changes: 169 additions & 0 deletions src/HonzaBotner.Services/StandUpStatsService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
using System;
using System.Threading.Tasks;
using HonzaBotner.Database;
using HonzaBotner.Services.Contract;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using StandUpStat = HonzaBotner.Services.Contract.Dto.StandUpStat;

namespace HonzaBotner.Services;

public class StandUpStatsService : IStandUpStatsService
{
private readonly HonzaBotnerDbContext _dbContext;
private readonly ILogger<StandUpStatsService> _logger;
private const int DaysToAcquireFreeze = 6;
private const int TasksCompletedThreshold = 1;

private const int ComparedDay = -1;

public StandUpStatsService(HonzaBotnerDbContext dbContext, ILogger<StandUpStatsService> logger)
{
_dbContext = dbContext;
_logger = logger;
}

public async Task<StandUpStat?> GetStats(ulong userId)
{
Database.StandUpStat? standUpStat = await _dbContext.StandUpStats
.FirstOrDefaultAsync(streak => streak.UserId == userId);

return standUpStat == null ? null : GetDto(standUpStat);
}

private async Task UpdateStreak(ulong userId, Database.StandUpStat streak)
{
int days = (DateTime.Today.AddDays(ComparedDay - 1) - streak.LastDayOfStreak).Days;

// Streak was already restored today.
if (days == ComparedDay)
{
return;
}

// Streak restored using freezes.
if (await IsValidStreak(userId, GetDto(streak)))
{
streak.Freezes -= days;
streak.Streak++;
streak.LastDayOfStreak = DateTime.Today.AddDays(ComparedDay).ToUniversalTime();

if (streak.Streak > streak.LongestStreak)
{
streak.LongestStreak = streak.Streak;
}

// Freeze acquired.
if (streak.Streak % DaysToAcquireFreeze == 0)
{
streak.Freezes++;
}
}
// Streak was broken and there are not enough freezes available.
else
{
streak.Freezes = 0;
streak.LastDayOfStreak = DateTime.Today.AddDays(ComparedDay).ToUniversalTime();
streak.Streak = 1;
}

try
{
_dbContext.StandUpStats.Update(streak);
await _dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Couldn't update streak {@Streak}", streak);
}
}


public async Task<bool> IsValidStreak(ulong userId)
{
StandUpStat? stats = await GetStats(userId);
return await IsValidStreak(userId, stats);
}

private async Task<bool> IsValidStreak(ulong userId, StandUpStat? streak = null)
{
streak ??= await GetStats(userId);

if (streak is null)
{
return false;
}

int days = (DateTime.Today.AddDays(ComparedDay - 1) - streak.LastDayOfStreak).Days;

return days <= streak.Freezes;
}

public async Task UpdateStats(ulong userId, int tasksCompleted, int tasksTotal)
{
bool streakMaintained = tasksCompleted >= TasksCompletedThreshold;

Database.StandUpStat? stat = await _dbContext.StandUpStats
.FirstOrDefaultAsync(streak => streak.UserId == userId);

if (stat is null)
{
Database.StandUpStat newStat = new()
{
UserId = userId,
Freezes = 0,
LastDayOfStreak =
streakMaintained
? DateTime.Today.AddDays(ComparedDay).ToUniversalTime()
: DateTime.UnixEpoch,
Streak = streakMaintained ? 1 : 0,
LongestStreak = streakMaintained ? 1 : 0,
TotalCompleted = tasksCompleted,
TotalTasks = tasksTotal
};

await _dbContext.StandUpStats.AddAsync(newStat);

try
{
await _dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Couldn't add streak {@Stat}", stat);
}

return;
}

if (streakMaintained)
{
await UpdateStreak(userId, stat);
}

stat.TotalCompleted += tasksCompleted;
stat.TotalTasks += tasksTotal;

try
{
_dbContext.StandUpStats.Update(stat);
await _dbContext.SaveChangesAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Couldn't update streak {@Stat}", stat);
}
}

private static StandUpStat GetDto(Database.StandUpStat standUpStat) =>
new(
standUpStat.Id,
standUpStat.UserId,
standUpStat.Streak,
standUpStat.LongestStreak,
standUpStat.Freezes,
standUpStat.LastDayOfStreak,
standUpStat.TotalCompleted,
standUpStat.TotalTasks
);
}
Loading