feat: add campaign templates and recurring schedules
Deploy Telegram Bot / build-and-push (push) Successful in 3m49s
Deploy Telegram Bot / deploy (push) Successful in 10s

This commit is contained in:
2026-04-28 10:01:18 +03:00
parent a1ec688ec8
commit 0218890a7a
17 changed files with 1075 additions and 14 deletions
@@ -128,6 +128,60 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
return await sessionStore.CloneBatchAsync(batchId, batch.GroupId, interval);
}
public async Task<List<WebCampaignTemplate>?> GetCampaignTemplatesForGmAsync(Guid groupId, long gmId)
{
if (!await GroupBelongsToGmAsync(groupId, gmId))
{
return null;
}
return await sessionStore.GetCampaignTemplatesAsync(groupId);
}
public async Task<WebCampaignTemplate> CreateCampaignTemplateForGmAsync(
Guid groupId,
long gmId,
CreateCampaignTemplateRequest request)
{
if (!await GroupBelongsToGmAsync(groupId, gmId))
{
throw new SessionAccessDeniedException(groupId, gmId);
}
var normalizedRequest = NormalizeCampaignTemplateRequest(request);
return await sessionStore.CreateCampaignTemplateAsync(groupId, normalizedRequest);
}
public async Task DeleteCampaignTemplateForGmAsync(Guid templateId, long gmId)
{
var template = await sessionStore.GetCampaignTemplateAsync(templateId);
if (template is null || !await GroupBelongsToGmAsync(template.GroupId, gmId))
{
throw new SessionAccessDeniedException(templateId, gmId);
}
await sessionStore.DeleteCampaignTemplateAsync(templateId, template.GroupId);
}
public async Task<WebSessionBatch> CreateBatchFromCampaignTemplateForGmAsync(
Guid templateId,
long gmId,
DateTime firstScheduledAt)
{
if (firstScheduledAt <= DateTime.UtcNow)
{
throw new ArgumentOutOfRangeException(nameof(firstScheduledAt), firstScheduledAt, "First scheduled time must be in the future.");
}
var template = await sessionStore.GetCampaignTemplateAsync(templateId);
if (template is null || !await GroupBelongsToGmAsync(template.GroupId, gmId))
{
throw new SessionAccessDeniedException(templateId, gmId);
}
return await sessionStore.CreateBatchFromTemplateAsync(templateId, template.GroupId, firstScheduledAt);
}
public async Task AddCoGmForOwnerAsync(Guid groupId, long ownerTelegramId, long coGmTelegramId, string displayName, string? telegramUsername)
{
if (coGmTelegramId <= 0)
@@ -169,4 +223,48 @@ public sealed class AuthorizedSessionService(ISessionStore sessionStore)
{
return await sessionStore.IsGroupManagerAsync(groupId, gmId);
}
private static CreateCampaignTemplateRequest NormalizeCampaignTemplateRequest(CreateCampaignTemplateRequest request)
{
var name = request.Name.Trim();
var title = request.Title.Trim();
var joinLink = request.JoinLink.Trim();
if (name.Length == 0)
{
throw new ArgumentException("Template name must not be empty.", nameof(request));
}
if (title.Length == 0)
{
throw new ArgumentException("Session title must not be empty.", nameof(request));
}
if (joinLink.Length == 0)
{
throw new ArgumentException("Join link must not be empty.", nameof(request));
}
if (request.SessionCount is < 1 or > 52)
{
throw new ArgumentOutOfRangeException(nameof(request), request.SessionCount, "Session count must be between 1 and 52.");
}
if (request.IntervalDays is < 1 or > 365)
{
throw new ArgumentOutOfRangeException(nameof(request), request.IntervalDays, "Interval must be between 1 and 365 days.");
}
if (request.MaxPlayers is <= 0)
{
throw new ArgumentOutOfRangeException(nameof(request), request.MaxPlayers, "Seat limit must be greater than zero.");
}
return request with
{
Name = name,
Title = title,
JoinLink = joinLink
};
}
}
@@ -18,8 +18,33 @@ public sealed record WebSessionBatch(
int SessionCount,
string NotificationMode = SessionNotificationModeExtensions.GroupAndDirectValue);
public sealed record WebCampaignTemplate(
Guid Id,
Guid GroupId,
string Name,
string Title,
string JoinLink,
int SessionCount,
int IntervalDays,
int? MaxPlayers,
string NotificationMode,
DateTime CreatedAt,
DateTime UpdatedAt);
public sealed record CreateCampaignTemplateRequest(
string Name,
string Title,
string JoinLink,
int SessionCount,
int IntervalDays,
int? MaxPlayers,
SessionNotificationMode NotificationMode);
public static class BatchSchedulePlanner
{
private const int MaxTemplateSessionCount = 52;
private const int MaxTemplateIntervalDays = 365;
public static IReadOnlyList<DateTime> BuildFixedIntervalSchedule(
IEnumerable<DateTime> currentSchedule,
DateTime firstScheduledAt,
@@ -36,6 +61,26 @@ public static class BatchSchedulePlanner
.ToList();
}
public static IReadOnlyList<DateTime> BuildRecurringSchedule(
DateTime firstScheduledAt,
int sessionCount,
int intervalDays)
{
if (sessionCount is < 1 or > MaxTemplateSessionCount)
{
throw new ArgumentOutOfRangeException(nameof(sessionCount), sessionCount, "Session count must be between 1 and 52.");
}
if (intervalDays is < 1 or > MaxTemplateIntervalDays)
{
throw new ArgumentOutOfRangeException(nameof(intervalDays), intervalDays, "Interval must be between 1 and 365 days.");
}
return Enumerable.Range(0, sessionCount)
.Select(index => firstScheduledAt.AddDays(intervalDays * index))
.ToList();
}
public static DateTime ShiftForClone(DateTime scheduledAt, BatchCloneInterval interval) =>
interval switch
{
@@ -18,6 +18,11 @@ public interface ISessionStore
Task UpdateBatchNotificationModeAsync(Guid batchId, Guid groupId, SessionNotificationMode notificationMode);
Task RescheduleBatchAsync(Guid batchId, Guid groupId, DateTime firstScheduledAt, int intervalDays);
Task<WebSessionBatch> CloneBatchAsync(Guid batchId, Guid groupId, BatchCloneInterval interval);
Task<List<WebCampaignTemplate>> GetCampaignTemplatesAsync(Guid groupId);
Task<WebCampaignTemplate?> GetCampaignTemplateAsync(Guid templateId);
Task<WebCampaignTemplate> CreateCampaignTemplateAsync(Guid groupId, CreateCampaignTemplateRequest request);
Task DeleteCampaignTemplateAsync(Guid templateId, Guid groupId);
Task<WebSessionBatch> CreateBatchFromTemplateAsync(Guid templateId, Guid groupId, DateTime firstScheduledAt);
Task AddGroupCoGmAsync(Guid groupId, long ownerTelegramId, long coGmTelegramId, string displayName, string? telegramUsername);
Task RemoveGroupCoGmAsync(Guid groupId, long coGmTelegramId);
}
+208
View File
@@ -63,6 +63,7 @@ internal sealed record WebBatchSessionRow(
long TelegramChatId,
int? ThreadId,
string NotificationMode);
internal sealed record WebTemplateGroupDto(long TelegramChatId);
public sealed class SessionService(
NpgsqlDataSource dataSource,
@@ -753,6 +754,213 @@ public sealed class SessionService(
sourceSessions[0].NotificationMode);
}
public async Task<List<WebCampaignTemplate>> GetCampaignTemplatesAsync(Guid groupId)
{
await using var conn = await dataSource.OpenConnectionAsync();
return (await conn.QueryAsync<WebCampaignTemplate>(
"""
SELECT id AS Id,
group_id AS GroupId,
name AS Name,
title AS Title,
join_link AS JoinLink,
session_count AS SessionCount,
interval_days AS IntervalDays,
max_players AS MaxPlayers,
notification_mode AS NotificationMode,
created_at AS CreatedAt,
updated_at AS UpdatedAt
FROM campaign_templates
WHERE group_id = @GroupId
ORDER BY created_at DESC, name
""",
new { GroupId = groupId })).ToList();
}
public async Task<WebCampaignTemplate?> GetCampaignTemplateAsync(Guid templateId)
{
await using var conn = await dataSource.OpenConnectionAsync();
return await conn.QuerySingleOrDefaultAsync<WebCampaignTemplate>(
"""
SELECT id AS Id,
group_id AS GroupId,
name AS Name,
title AS Title,
join_link AS JoinLink,
session_count AS SessionCount,
interval_days AS IntervalDays,
max_players AS MaxPlayers,
notification_mode AS NotificationMode,
created_at AS CreatedAt,
updated_at AS UpdatedAt
FROM campaign_templates
WHERE id = @TemplateId
""",
new { TemplateId = templateId });
}
public async Task<WebCampaignTemplate> CreateCampaignTemplateAsync(Guid groupId, CreateCampaignTemplateRequest request)
{
await using var conn = await dataSource.OpenConnectionAsync();
return await conn.QuerySingleAsync<WebCampaignTemplate>(
"""
INSERT INTO campaign_templates (
group_id,
name,
title,
join_link,
session_count,
interval_days,
max_players,
notification_mode
)
VALUES (
@GroupId,
@Name,
@Title,
@JoinLink,
@SessionCount,
@IntervalDays,
@MaxPlayers,
@NotificationMode
)
ON CONFLICT (group_id, name) DO UPDATE
SET title = EXCLUDED.title,
join_link = EXCLUDED.join_link,
session_count = EXCLUDED.session_count,
interval_days = EXCLUDED.interval_days,
max_players = EXCLUDED.max_players,
notification_mode = EXCLUDED.notification_mode,
updated_at = now()
RETURNING id AS Id,
group_id AS GroupId,
name AS Name,
title AS Title,
join_link AS JoinLink,
session_count AS SessionCount,
interval_days AS IntervalDays,
max_players AS MaxPlayers,
notification_mode AS NotificationMode,
created_at AS CreatedAt,
updated_at AS UpdatedAt
""",
new
{
GroupId = groupId,
request.Name,
request.Title,
request.JoinLink,
request.SessionCount,
request.IntervalDays,
request.MaxPlayers,
NotificationMode = request.NotificationMode.ToDatabaseValue()
});
}
public async Task DeleteCampaignTemplateAsync(Guid templateId, Guid groupId)
{
await using var conn = await dataSource.OpenConnectionAsync();
await conn.ExecuteAsync(
"DELETE FROM campaign_templates WHERE id = @TemplateId AND group_id = @GroupId",
new { TemplateId = templateId, GroupId = groupId });
}
public async Task<WebSessionBatch> CreateBatchFromTemplateAsync(Guid templateId, Guid groupId, DateTime firstScheduledAt)
{
await using var conn = await dataSource.OpenConnectionAsync();
await using var transaction = await conn.BeginTransactionAsync();
var template = await conn.QuerySingleOrDefaultAsync<WebCampaignTemplate>(
"""
SELECT id AS Id,
group_id AS GroupId,
name AS Name,
title AS Title,
join_link AS JoinLink,
session_count AS SessionCount,
interval_days AS IntervalDays,
max_players AS MaxPlayers,
notification_mode AS NotificationMode,
created_at AS CreatedAt,
updated_at AS UpdatedAt
FROM campaign_templates
WHERE id = @TemplateId
AND group_id = @GroupId
FOR UPDATE
""",
new { TemplateId = templateId, GroupId = groupId },
transaction);
if (template is null)
{
throw new SessionAccessDeniedException(templateId, 0);
}
var group = await conn.QuerySingleOrDefaultAsync<WebTemplateGroupDto>(
"SELECT telegram_chat_id AS TelegramChatId FROM game_groups WHERE id = @GroupId",
new { GroupId = groupId },
transaction);
if (group is null)
{
throw new SessionAccessDeniedException(groupId, 0);
}
var schedule = BatchSchedulePlanner.BuildRecurringSchedule(
firstScheduledAt,
template.SessionCount,
template.IntervalDays);
var batchId = Guid.NewGuid();
var renderedSessions = new List<SessionBatchDto>();
foreach (var scheduledAt in schedule)
{
var sessionId = await conn.ExecuteScalarAsync<Guid>(
"""
INSERT INTO sessions (batch_id, group_id, title, join_link, scheduled_at, status, max_players, notification_mode)
VALUES (@BatchId, @GroupId, @Title, @JoinLink, @ScheduledAt, @Status, @MaxPlayers, @NotificationMode)
RETURNING id
""",
new
{
BatchId = batchId,
GroupId = groupId,
template.Title,
template.JoinLink,
ScheduledAt = scheduledAt,
Status = SessionStatus.Planned,
template.MaxPlayers,
template.NotificationMode
},
transaction);
renderedSessions.Add(new SessionBatchDto(sessionId, scheduledAt, SessionStatus.Planned, template.MaxPlayers));
}
await transaction.CommitAsync();
var renderResult = SessionBatchRenderer.Render(template.Title, renderedSessions, Array.Empty<ParticipantBatchDto>());
var batchMessage = await bot.SendMessage(
chatId: group.TelegramChatId,
text: renderResult.Text,
parseMode: Telegram.Bot.Types.Enums.ParseMode.Html,
replyMarkup: renderResult.Markup);
await conn.ExecuteAsync(
"UPDATE sessions SET batch_message_id = @MessageId WHERE batch_id = @BatchId",
new { MessageId = batchMessage.MessageId, BatchId = batchId });
return new WebSessionBatch(
batchId,
groupId,
template.Title,
template.JoinLink,
renderedSessions.Min(session => session.ScheduledAt),
renderedSessions.Max(session => session.ScheduledAt),
renderedSessions.Count,
template.NotificationMode);
}
private async Task<List<WebDirectNotificationRecipient>> LoadSessionDirectRecipientsAsync(
Npgsql.NpgsqlConnection conn,
Guid sessionId)