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 5 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
2 changes: 2 additions & 0 deletions src/HonzaBotner.Database/HonzaBotnerDbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,6 @@ 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; }

LucyAnne98 marked this conversation as resolved.
Show resolved Hide resolved
}
17 changes: 17 additions & 0 deletions src/HonzaBotner.Database/StandUpStat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
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 LastDayCompleted { get; set; }
public int LastDayTasks { get; set; }
public int TotalCompleted { get; set; }
public int TotalTasks { get; set; }
}
17 changes: 16 additions & 1 deletion src/HonzaBotner.Discord.Services/Jobs/StandUpJobProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using HonzaBotner.Discord.Services.Helpers;
using HonzaBotner.Discord.Services.Options;
using HonzaBotner.Scheduler.Contract;
using HonzaBotner.Services.Contract;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

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

private readonly CommonCommandOptions _commonOptions;

private readonly IStandUpStatsService _statsService;

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

/// <summary>
Expand Down Expand Up @@ -81,20 +86,30 @@ await channel.GetMessagesBeforeAsync(messageList.Last().Id)

foreach (DiscordMessage msg in messageList.Where(msg => msg.Timestamp.Date == yesterday))
{
bool streakMaintained = false;
int total = 0;
int completed = 0;
foreach (Match match in Regex.Matches(msg.Content))
{
string state = match.Groups["State"].ToString();
string priority = match.Groups["Priority"].ToString();
total++;

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

await _statsService.UpdateStats(msg.Author.Id, completed, total, streakMaintained);


}

await channel.SendMessageAsync($@"
Expand Down
13 changes: 13 additions & 0 deletions src/HonzaBotner.Services.Contract/Dto/StandUpStat.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;

namespace HonzaBotner.Services.Contract.Dto;

public class StandUpStat{

LucyAnne98 marked this conversation as resolved.
Show resolved Hide resolved
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; }
};
12 changes: 12 additions & 0 deletions src/HonzaBotner.Services.Contract/IStandUpStatsService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System.Threading.Tasks;
using HonzaBotner.Services.Contract.Dto;
namespace HonzaBotner.Services.Contract;

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

Task<bool> IsValidStreak(ulong userId);

Task UpdateStats(ulong userId, int completed, int total, bool streakMaintained);
}
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
150 changes: 150 additions & 0 deletions src/HonzaBotner.Services/StandUpStatsService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
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;

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

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

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

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

if (days == -1) //Streak was already restored today
{
return;
}

if (days > streak.Freezes) //Streak broken
{
streak.Freezes = 0;
streak.LastDayOfStreak = DateTime.Today.AddDays(-1).ToUniversalTime();
streak.Streak = 1;
}
else //streak restored
{
streak.Freezes -= days;
streak.Streak++;
streak.LastDayOfStreak = DateTime.Today.AddDays(-1).ToUniversalTime() ;

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

if (streak.Streak % DaysToAcquireFreeze == 0) // freeze acquired
{
streak.Freezes++;
}
}

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? streak = await GetStreak(userId);

if (streak is null)
return false;
int days = (DateTime.Today.AddDays(-2) - streak.LastDayOfStreak).Days;

return days <= streak.Freezes;
}

public async Task UpdateStats(ulong userId, int completed, int total, bool streakMaintained) {
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(-1).ToUniversalTime() : DateTime.Today.AddDays(-100).ToUniversalTime(),
LucyAnne98 marked this conversation as resolved.
Show resolved Hide resolved
Streak = streakMaintained? 1 : 0,
LucyAnne98 marked this conversation as resolved.
Show resolved Hide resolved
LongestStreak = streakMaintained? 1 : 0,
LastDayCompleted = completed,
LastDayTasks = total,
TotalCompleted = completed,
TotalTasks = total
};


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.LastDayCompleted = completed;
stat.LastDayTasks = total;
stat.TotalCompleted += completed;
stat.TotalTasks += total;

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.Id,
UserId = standUpStat.UserId,
Streak = standUpStat.Streak,
LongestStreak = standUpStat.LongestStreak,
Freezes = standUpStat.Freezes,
LastDayOfStreak = standUpStat.LastDayOfStreak
};
}
Loading